From fc74cfdda688ee0ec5741a4c875317ec22b6717f Mon Sep 17 00:00:00 2001 From: Leonard Viktor Pooch Date: Mon, 13 Dec 2021 18:04:27 +0100 Subject: [PATCH] Revert "Merge branch 'develop' into MON-10917-sql-conection-uptime" This reverts commit b9ec8c9a480cc60a1f8fe4ac0f9351b648dd8864, reversing changes made to 2dde25a90bfb2841e9389d0e4890c60a1348c5d2. --- .gitignore | 46 +- CMakeLists.txt | 58 +- README.md | 14 +- bbdo/CMakeLists.txt | 100 - bbdo/events.hh | 128 -- bbdo/generate-accessor.py | 94 - bbdo/rebuild.proto | 24 - bbdo/service.proto | 28 - centreon-broker/CMakeLists.txt | 134 +- centreon-broker/bam/CMakeLists.txt | 46 +- .../bam/inc/com/centreon/broker/bam/ba.hh | 17 +- .../centreon/broker}/bam/ba_duration_event.hh | 5 +- .../inc/com/centreon/broker}/bam/ba_event.hh | 4 +- .../inc/com/centreon/broker}/bam/ba_status.hh | 4 +- .../centreon/broker/bam/bool_expression.hh | 6 +- .../centreon/broker/bam/configuration/ba.hh | 2 +- .../bam/configuration/bool_expression.hh | 2 +- .../centreon/broker/bam/configuration/kpi.hh | 42 +- .../bam/dimension_ba_bv_relation_event.hh | 4 +- .../broker}/bam/dimension_ba_event.hh | 5 +- .../bam/dimension_ba_timeperiod_relation.hh | 4 +- .../broker}/bam/dimension_bv_event.hh | 5 +- .../broker}/bam/dimension_kpi_event.hh | 5 +- .../broker}/bam/dimension_timeperiod.hh | 5 +- .../bam/dimension_timeperiod_exception.hh | 4 +- .../bam/dimension_timeperiod_exclusion.hh | 4 +- .../bam/dimension_truncate_table_signal.hh | 4 +- .../com/centreon/broker/bam/impact_values.hh | 17 +- .../broker}/bam/inherited_downtime.hh | 5 +- .../inc/com/centreon/broker/bam/internal.hh | 51 + .../bam/inc/com/centreon/broker/bam/kpi.hh | 2 +- .../bam/inc/com/centreon/broker/bam/kpi_ba.hh | 13 +- .../com/centreon/broker/bam/kpi_boolexp.hh | 12 +- .../inc/com/centreon/broker}/bam/kpi_event.hh | 11 +- .../com/centreon/broker/bam/kpi_service.hh | 26 +- .../com/centreon/broker}/bam/kpi_status.hh | 4 +- .../inc/com/centreon/broker}/bam/rebuild.hh | 4 +- .../centreon/broker/bam/reporting_stream.hh | 2 +- .../bam/src/availability_thread.cc | 1 + centreon-broker/bam/src/ba.cc | 88 +- .../bam/src}/ba_duration_event.cc | 4 +- .../bam/src}/ba_event.cc | 9 +- .../bam/src}/ba_status.cc | 5 +- centreon-broker/bam/src/bool_expression.cc | 10 +- centreon-broker/bam/src/bool_metric.cc | 2 +- .../bam/src/configuration/applier/kpi.cc | 4 +- centreon-broker/bam/src/configuration/kpi.cc | 24 +- .../bam/src/configuration/reader_v2.cc | 14 +- .../src}/dimension_ba_bv_relation_event.cc | 10 +- .../bam/src}/dimension_ba_event.cc | 4 +- .../src}/dimension_ba_timeperiod_relation.cc | 5 +- .../bam/src}/dimension_bv_event.cc | 4 +- .../bam/src}/dimension_kpi_event.cc | 4 +- .../bam/src}/dimension_timeperiod.cc | 4 +- .../src}/dimension_timeperiod_exception.cc | 4 +- .../src}/dimension_timeperiod_exclusion.cc | 4 +- .../src}/dimension_truncate_table_signal.cc | 4 +- .../bam/src/event_cache_visitor.cc | 7 +- centreon-broker/bam/src/exp_parser.cc | 2 +- centreon-broker/bam/src/impact_values.cc | 13 +- .../bam/src}/inherited_downtime.cc | 10 +- centreon-broker/bam/src/kpi_ba.cc | 16 +- centreon-broker/bam/src/kpi_boolexp.cc | 14 +- .../bam/src}/kpi_event.cc | 8 +- centreon-broker/bam/src/kpi_service.cc | 21 +- .../bam/src}/kpi_status.cc | 4 +- centreon-broker/bam/src/main.cc | 72 +- centreon-broker/bam/src/metric_book.cc | 2 +- centreon-broker/bam/src/monitoring_stream.cc | 15 +- .../bam/src}/rebuild.cc | 5 +- centreon-broker/bam/src/reporting_stream.cc | 99 +- centreon-broker/bam/test/ba/kpi_ba.cc | 14 +- centreon-broker/bam/test/ba/kpi_service.cc | 49 +- .../test/exp_builder/availability_builder.cc | 6 +- centreon-broker/bam/test/test-visitor.hh | 20 +- centreon-broker/cmake/package.cmake | 6 +- centreon-broker/cmake/tool.cmake | 3 +- centreon-broker/config/central-broker.json.in | 8 +- .../core/inc/com/centreon/broker/bbdo/ack.hh | 3 +- .../core/inc/com/centreon/broker/bbdo/stop.hh | 3 +- .../inc/com/centreon/broker/bbdo/stream.hh | 26 +- .../centreon/broker/bbdo/version_response.hh | 7 +- .../centreon/broker/config/applier/state.hh | 4 +- .../com/centreon/broker/config/endpoint.hh | 6 +- .../inc/com/centreon/broker/config/state.hh | 9 +- .../com/centreon/broker/instance_broadcast.hh | 2 +- .../inc/com/centreon/broker/io/event_info.hh | 4 +- .../core/inc/com/centreon/broker/io/events.hh | 43 +- .../inc/com/centreon/broker/io/protobuf.hh | 114 -- .../inc/com/centreon/broker/io/protocols.hh | 4 +- .../core/inc/com/centreon/broker/io/raw.hh | 5 +- .../core/inc/com/centreon/broker/io/stream.hh | 2 +- .../com/centreon/broker/misc/filesystem.hh | 2 - .../com/centreon/broker/misc/global_lock.hh | 18 +- .../core/inc/com/centreon/broker/misc/misc.hh | 4 - .../centreon/broker/multiplexing/engine.hh | 27 +- .../centreon/broker/multiplexing/hooker.hh | 51 + .../com/centreon/broker/multiplexing/muxer.hh | 18 +- .../com/centreon/broker/mysql_connection.hh | 1 - .../broker/processing/stat_visitable.hh | 2 +- .../inc/com/centreon/broker/stats/center.hh | 2 +- .../inc/com/centreon/broker/version.hh.in | 6 +- centreon-broker/core/src/bbdo/ack.cc | 3 +- centreon-broker/core/src/bbdo/connector.cc | 2 +- centreon-broker/core/src/bbdo/internal.cc | 25 +- centreon-broker/core/src/bbdo/stop.cc | 3 +- centreon-broker/core/src/bbdo/stream.cc | 378 ++-- .../core/src/bbdo/version_response.cc | 12 +- centreon-broker/core/src/broker_impl.cc | 12 +- centreon-broker/core/src/brokerrpc.cc | 13 +- .../core/src/compression/stream.cc | 21 +- .../core/src/config/applier/modules.cc | 2 +- .../core/src/config/applier/state.cc | 22 +- centreon-broker/core/src/config/endpoint.cc | 65 +- centreon-broker/core/src/config/parser.cc | 33 +- centreon-broker/core/src/config/state.cc | 34 - .../core/src/instance_broadcast.cc | 4 +- centreon-broker/core/src/io/events.cc | 150 +- centreon-broker/core/src/main.cc | 4 +- centreon-broker/core/src/misc/diagnostic.cc | 3 +- centreon-broker/core/src/misc/filesystem.cc | 25 - centreon-broker/core/src/misc/global_lock.cc | 29 + centreon-broker/core/src/misc/string.cc | 3 +- centreon-broker/core/src/modules/handle.cc | 2 +- .../core/src/multiplexing/engine.cc | 268 ++- .../core/src/multiplexing/hooker.cc | 47 + .../core/src/multiplexing/muxer.cc | 7 +- centreon-broker/core/src/mysql.cc | 2 + centreon-broker/core/src/mysql_connection.cc | 28 +- centreon-broker/core/src/mysql_manager.cc | 2 +- .../core/src/processing/failover.cc | 16 +- centreon-broker/core/src/stats/center.cc | 23 +- centreon-broker/core/src/time/timerange.cc | 31 +- centreon-broker/core/test/bbdo/category.cc | 16 +- centreon-broker/core/test/bbdo/output.cc | 2 +- .../test/compression/stream/memory_stream.hh | 3 +- centreon-broker/core/test/config/parser.cc | 377 +--- centreon-broker/core/test/misc/perfdata.cc | 566 ------ .../core/test/modules/bad_version_module.cc | 5 +- .../core/test/modules/null_module.cc | 5 +- .../core/test/multiplexing/engine/hook.cc | 143 ++ .../core/test/multiplexing/engine/hooker.hh | 54 + .../test/multiplexing/engine/start_stop.cc | 35 +- .../core/test/multiplexing/engine/unhook.cc | 138 ++ centreon-broker/core/test/rpc/brokerrpc.cc | 8 +- centreon-broker/core/test/time/timerange.cc | 19 +- centreon-broker/deps.go | 2 - centreon-broker/generator/src/dummy.cc | 3 +- centreon-broker/generator/src/main.cc | 16 +- centreon-broker/graphite/CMakeLists.txt | 1 - .../centreon/broker/graphite/macro_cache.hh | 4 +- .../inc/com/centreon/broker/graphite/query.hh | 4 +- .../com/centreon/broker/graphite/stream.hh | 5 +- centreon-broker/graphite/src/main.cc | 22 +- centreon-broker/graphite/src/stream.cc | 10 +- centreon-broker/influxdb/CMakeLists.txt | 1 - .../com/centreon/broker/influxdb/influxdb.hh | 4 +- .../centreon/broker/influxdb/influxdb12.hh | 2 +- .../broker/influxdb/line_protocol_query.hh | 4 +- .../centreon/broker/influxdb/macro_cache.hh | 4 +- centreon-broker/influxdb/src/main.cc | 24 +- centreon-broker/influxdb/src/stream.cc | 10 +- centreon-broker/influxdb/test/factory.cc | 140 +- .../influxdb/test/line_protocol_query.cc | 2 +- centreon-broker/lua/CMakeLists.txt | 11 +- .../com/centreon/broker/lua/macro_cache.hh | 12 +- .../lua/inc/com/centreon/broker/lua/stream.hh | 2 +- centreon-broker/lua/src/broker_event.cc | 6 +- centreon-broker/lua/src/broker_utils.cc | 15 +- centreon-broker/lua/src/luabinding.cc | 4 +- centreon-broker/lua/src/main.cc | 44 +- centreon-broker/lua/test/lua.cc | 2 +- centreon-broker/neb/CMakeLists.txt | 2 +- .../centreon/broker/neb/acknowledgement.hh | 3 +- .../inc/com/centreon/broker/neb/comment.hh | 2 +- .../centreon/broker/neb/custom_variable.hh | 3 +- .../broker/neb/custom_variable_status.hh | 2 +- .../inc/com/centreon/broker/neb/downtime.hh | 2 +- .../com/centreon/broker/neb/event_handler.hh | 2 +- .../centreon/broker/neb/flapping_status.hh | 3 +- .../neb/inc/com/centreon/broker/neb/host.hh | 2 +- .../inc/com/centreon/broker/neb/host_check.hh | 2 +- .../centreon/broker/neb/host_dependency.hh | 3 +- .../inc/com/centreon/broker/neb/host_group.hh | 2 +- .../centreon/broker/neb/host_group_member.hh | 3 +- .../com/centreon/broker/neb/host_parent.hh | 2 +- .../com/centreon/broker/neb/host_status.hh | 2 +- .../inc/com/centreon/broker/neb/instance.hh | 2 +- .../broker/neb/instance_configuration.hh | 2 +- .../centreon/broker/neb/instance_status.hh | 3 +- .../inc/com/centreon/broker/neb/log_entry.hh | 2 +- .../neb/inc/com/centreon/broker/neb/module.hh | 2 +- .../broker/neb/responsive_instance.hh | 3 +- .../inc/com/centreon/broker/neb/service.hh | 2 +- .../com/centreon/broker/neb/service_check.hh | 2 +- .../centreon/broker/neb/service_dependency.hh | 3 +- .../com/centreon/broker/neb/service_group.hh | 2 +- .../broker/neb/service_group_member.hh | 3 +- .../com/centreon/broker/neb/service_status.hh | 3 +- .../neb/inc/com/centreon/clib/version.hh | 44 +- .../neb/inc/com/centreon/clib/version.hh.in | 20 +- .../neb/inc/com/centreon/clib_lock_guard.hh | 22 +- .../com/centreon/engine/anomalydetection.hh | 2 +- .../engine/commands/command_listener.hh | 8 +- .../engine/configuration/anomalydetection.hh | 3 +- .../engine/configuration/applier/scheduler.hh | 2 +- .../engine/configuration/applier/state.hh | 2 +- .../centreon/engine/configuration/parser.hh | 2 +- .../com/centreon/engine/downtimes/downtime.hh | 6 +- .../engine/downtimes/downtime_manager.hh | 3 +- .../inc/com/centreon/engine/engine_impl.hh | 10 +- .../inc/com/centreon/engine/events/loop.hh | 10 +- .../com/centreon/engine/events/timed_event.hh | 2 +- .../com/centreon/engine/exceptions/error.hh | 2 +- .../neb/inc/com/centreon/engine/my_lock.hh | 23 +- .../neb/inc/com/centreon/engine/nebstructs.hh | 4 +- .../neb/inc/com/centreon/engine/opt.hh | 2 +- .../neb/inc/com/centreon/engine/statistics.hh | 3 +- .../com/centreon/engine/timezone_manager.hh | 5 +- .../neb/inc/com/centreon/engine/version.hh.in | 6 +- .../neb/inc/com/centreon/exceptions/basic.hh | 2 +- .../com/centreon/exceptions/interruption.hh | 2 +- .../inc/com/centreon/io/directory_entry.hh | 4 +- .../neb/inc/com/centreon/io/file_entry.hh | 6 +- .../neb/inc/com/centreon/io/file_stream.hh | 2 +- .../neb/inc/com/centreon/logging/backend.hh | 9 +- .../neb/inc/com/centreon/logging/file.hh | 2 +- .../neb/inc/com/centreon/logging/logger.hh | 20 +- .../neb/inc/com/centreon/logging/syslogger.hh | 2 +- .../inc/com/centreon/logging/temp_logger.hh | 4 +- .../neb/inc/com/centreon/misc/argument.hh | 2 +- .../neb/inc/com/centreon/misc/command_line.hh | 2 +- .../neb/inc/com/centreon/misc/get_options.hh | 4 +- .../neb/inc/com/centreon/misc/stringifier.hh | 2 +- centreon-broker/neb/src/acknowledgement.cc | 3 +- centreon-broker/neb/src/broker.cc | 81 +- centreon-broker/neb/src/callbacks.cc | 8 +- centreon-broker/neb/src/comment.cc | 3 +- centreon-broker/neb/src/custom_variable.cc | 2 +- .../neb/src/custom_variable_status.cc | 2 +- centreon-broker/neb/src/downtime.cc | 3 +- centreon-broker/neb/src/event_handler.cc | 2 +- centreon-broker/neb/src/flapping_status.cc | 2 +- centreon-broker/neb/src/host.cc | 3 +- centreon-broker/neb/src/host_check.cc | 2 +- centreon-broker/neb/src/host_dependency.cc | 2 +- centreon-broker/neb/src/host_group.cc | 2 +- centreon-broker/neb/src/host_group_member.cc | 2 +- centreon-broker/neb/src/host_parent.cc | 2 +- centreon-broker/neb/src/host_status.cc | 2 +- centreon-broker/neb/src/instance.cc | 3 +- .../neb/src/instance_configuration.cc | 2 +- centreon-broker/neb/src/instance_status.cc | 3 +- centreon-broker/neb/src/log_entry.cc | 3 +- centreon-broker/neb/src/module.cc | 3 +- centreon-broker/neb/src/neb.cc | 4 +- .../neb/src/responsive_instance.cc | 2 +- centreon-broker/neb/src/service.cc | 3 +- centreon-broker/neb/src/service_check.cc | 2 +- centreon-broker/neb/src/service_dependency.cc | 2 +- centreon-broker/neb/src/service_group.cc | 2 +- .../neb/src/service_group_member.cc | 2 +- centreon-broker/neb/src/service_status.cc | 2 +- centreon-broker/neb/test/custom_variable.cc | 5 +- .../neb/test/custom_variable_status.cc | 6 +- centreon-broker/neb/test/event_handler.cc | 5 +- centreon-broker/neb/test/flapping_status.cc | 5 +- centreon-broker/neb/test/host_check.cc | 5 +- centreon-broker/neb/test/host_dependency.cc | 2 +- centreon-broker/neb/test/host_parent.cc | 5 +- centreon-broker/neb/test/instance.cc | 2 +- centreon-broker/neb/test/instance_status.cc | 3 +- centreon-broker/neb/test/log_entry.cc | 2 +- centreon-broker/neb/test/module.cc | 2 +- centreon-broker/neb/test/randomize.cc | 49 +- centreon-broker/neb/test/service_check.cc | 3 +- .../neb/test/service_dependency.cc | 3 +- centreon-broker/notification/CMakeLists.txt | 161 ++ .../centreon/broker/notification/action.hh | 107 ++ .../notification/builders/command_builder.hh | 58 + .../builders/command_by_id_builder.hh | 53 + .../notification/builders/composed_builder.hh | 64 + .../builders/composed_command_builder.hh | 49 + .../builders/composed_contact_builder.hh | 52 + .../builders/composed_dependency_builder.hh | 58 + .../builders/composed_node_builder.hh | 49 + .../composed_notification_method_builder.hh | 53 + .../composed_notification_rule_builder.hh | 50 + .../builders/composed_timeperiod_builder.hh | 58 + .../notification/builders/contact_builder.hh | 73 + .../builders/contact_by_id_builder.hh | 56 + .../builders/dependency_builder.hh | 80 + .../builders/dependency_by_node_id_builder.hh | 62 + .../builders/global_macro_builder.hh | 55 + .../notification/builders/macro_builder.hh | 78 + .../notification/builders/node_builder.hh | 54 + .../builders/node_by_node_id_builder.hh | 54 + .../notification/builders/node_set_builder.hh | 54 + .../builders/notification_method_builder.hh | 54 + .../notification_method_by_id_builder.hh | 53 + .../builders/notification_rule_builder.hh | 54 + .../notification_rule_by_id_builder.hh | 50 + .../notification_rule_by_node_builder.hh | 51 + .../builders/timeperiod_builder.hh | 96 + .../builders/timeperiod_by_id_builder.hh | 49 + .../builders/timeperiod_linker.hh | 59 + .../centreon/broker/notification/connector.hh | 68 + .../centreon/broker/notification}/factory.hh | 24 +- .../notification/loaders/command_loader.hh | 47 + .../notification/loaders/contact_loader.hh | 48 + .../notification/loaders/dependency_loader.hh | 56 + .../notification/loaders/escalation_loader.hh | 61 + .../notification/loaders/macro_loader.hh | 47 + .../notification/loaders/node_loader.hh | 48 + .../loaders/notification_method_loader.hh | 48 + .../loaders/notification_rule_loader.hh | 48 + .../notification/loaders/timeperiod_loader.hh | 49 + .../broker/notification/macro_context.hh | 64 + .../broker/notification/macro_generator.hh | 71 + .../broker/notification/macro_getters.hh | 480 +++++ .../broker/notification/node_cache.hh | 102 + .../notification/notification_scheduler.hh | 85 + .../broker/notification/object_cache.hh | 170 ++ .../broker/notification/objects/command.hh | 85 + .../broker/notification/objects/contact.hh | 62 + .../broker/notification/objects/defines.hh | 59 + .../broker/notification/objects/dependency.hh | 114 ++ .../broker/notification/objects/node.hh | 85 + .../broker/notification/objects/node_id.hh | 66 + .../objects/notification_method.hh | 85 + .../notification/objects/notification_rule.hh | 73 + .../broker/notification/objects/record.hh | 42 + .../centreon/broker/notification/process.hh | 83 + .../broker/notification/process_manager.hh | 70 + .../centreon/broker/notification/run_queue.hh | 73 + .../com/centreon/broker/notification/state.hh | 102 + .../centreon/broker/notification/stream.hh | 96 + .../utilities/get_datetime_string.hh | 54 + .../notification/utilities/ptr_typedef.hh} | 20 +- .../notification/utilities/qhash_func.hh} | 17 +- centreon-broker/notification/mysql_v3.sql | 91 + centreon-broker/notification/src/action.cc | 468 +++++ .../src/builders/command_by_id_builder.cc | 42 + .../src/builders/composed_command_builder.cc | 39 + .../src/builders/composed_contact_builder.cc | 54 + .../builders/composed_dependency_builder.cc | 71 + .../src/builders/composed_node_builder.cc | 38 + .../composed_notification_method_builder.cc | 42 + .../composed_notification_rule_builder.cc | 42 + .../builders/composed_timeperiod_builder.cc | 88 + .../src/builders/contact_by_id_builder.cc | 57 + .../builders/dependency_by_node_id_builder.cc | 52 + .../src/builders/global_macro_builder.cc | 58 + .../src/builders/node_by_node_id_builder.cc | 40 + .../src/builders/node_set_builder.cc | 38 + .../notification_method_by_id_builder.cc | 43 + .../notification_rule_by_id_builder.cc | 43 + .../notification_rule_by_node_builder.cc | 44 + .../src/builders/timeperiod_by_id_builder.cc | 42 + .../src/builders/timeperiod_linker.cc | 98 + centreon-broker/notification/src/connector.cc | 119 ++ centreon-broker/notification/src/factory.cc | 121 ++ .../src/loaders/command_loader.cc | 66 + .../src/loaders/contact_loader.cc | 81 + .../src/loaders/dependency_loader.cc | 208 ++ .../src/loaders/escalation_loader.cc | 141 ++ .../notification/src/loaders/macro_loader.cc | 139 ++ .../notification/src/loaders/node_loader.cc | 89 + .../src/loaders/notification_method_loader.cc | 69 + .../src/loaders/notification_rule_loader.cc | 68 + .../src/loaders/timeperiod_loader.cc | 133 ++ .../notification/src/macro_context.cc | 82 + .../notification/src/macro_generator.cc | 447 +++++ .../notification/src/macro_getters.cc | 368 ++++ centreon-broker/notification/src/main.cc | 64 + .../notification/src/node_cache.cc | 391 ++++ .../src/notification_scheduler.cc | 192 ++ .../notification/src/objects/command.cc | 186 ++ .../notification/src/objects/contact.cc | 87 + .../notification/src/objects/defines.cc | 98 + .../notification/src/objects/dependency.cc | 275 +++ .../notification/src/objects/node.cc | 248 +++ .../notification/src/objects/node_id.cc | 153 ++ .../src/objects/notification_method.cc | 241 +++ .../src/objects/notification_rule.cc | 143 ++ centreon-broker/notification/src/process.cc | 171 ++ .../notification/src/process_manager.cc | 129 ++ centreon-broker/notification/src/run_queue.cc | 196 ++ centreon-broker/notification/src/state.cc | 391 ++++ centreon-broker/notification/src/stream.cc | 536 ++++++ .../src/utilities/get_datetime_string.cc | 112 ++ .../notification/src/utilities/qhash_func.cc | 32 + .../rpm/centreon-broker.spectemplate | 1209 ++++++++++++ .../rpm/debian/centreon-broker-cbmod.postinst | 8 + .../rpm/debian/centreon-broker-cbmod.triggers | 1 + .../rpm/debian/centreon-broker-core.postinst | 9 + .../rpm/debian/centreon-broker-core.postrm | 7 + .../packaging/rpm/debian/changelog.in | 5 + centreon-broker/packaging/rpm/debian/compat | 1 + centreon-broker/packaging/rpm/debian/control | 52 + .../packaging/rpm/debian/copyright | 1 + centreon-broker/packaging/rpm/debian/rules | 51 + .../packaging/rpm/debian/source/format | 1 + centreon-broker/packaging/script/rpmbuild.sh | 42 + centreon-broker/rrd/CMakeLists.txt | 7 +- .../inc/com/centreon/broker/rrd/backend.hh | 2 - .../rrd/inc/com/centreon/broker/rrd/cached.hh | 19 +- .../rrd/inc/com/centreon/broker/rrd/lib.hh | 1 - centreon-broker/rrd/src/creator.cc | 9 +- centreon-broker/rrd/src/lib.cc | 30 +- centreon-broker/rrd/src/main.cc | 37 +- centreon-broker/rrd/src/output.cc | 125 +- centreon-broker/script/systemd/cbd.service.in | 2 +- centreon-broker/simu/CMakeLists.txt | 10 +- centreon-broker/simu/src/main.cc | 28 +- centreon-broker/simu/test/simu.cc | 2 +- centreon-broker/sql/src/stream.cc | 1 + .../inc/com/centreon/broker/stats/builder.hh | 2 +- centreon-broker/stats/test/stats.cc | 52 +- centreon-broker/storage/CMakeLists.txt | 29 +- .../broker/storage/conflict_manager.hh | 6 +- .../inc/com/centreon/broker/storage/events.hh | 2 +- .../broker/storage/exceptions/perfdata.hh | 52 + .../centreon/broker}/storage/index_mapping.hh | 4 +- .../com/centreon/broker/storage/internal.hh | 16 +- .../com/centreon/broker}/storage/metric.hh | 16 +- .../broker}/storage/metric_mapping.hh | 3 +- .../inc/com/centreon/broker/storage/parser.hh | 53 + .../com/centreon/broker/storage}/perfdata.hh | 58 +- .../com/centreon/broker}/storage/rebuild.hh | 4 +- .../centreon/broker}/storage/remove_graph.hh | 4 +- .../com/centreon/broker}/storage/status.hh | 4 +- .../inc/com/centreon/broker/storage/stream.hh | 2 +- .../storage/src/conflict_manager.cc | 28 +- .../storage/src/conflict_manager_sql.cc | 4 +- .../storage/src/conflict_manager_storage.cc | 361 ++-- .../src/exceptions/perfdata.cc} | 19 +- .../storage/src}/index_mapping.cc | 10 +- centreon-broker/storage/src/main.cc | 43 +- .../storage/src}/metric.cc | 17 +- .../storage/src}/metric_mapping.cc | 10 +- .../src/parser.cc} | 41 +- .../src/misc => storage/src}/perfdata.cc | 13 +- .../storage/src}/rebuild.cc | 5 +- centreon-broker/storage/src/rebuild.proto | 24 - centreon-broker/storage/src/rebuilder.cc | 66 +- .../storage/src}/remove_graph.cc | 4 +- .../storage/src}/status.cc | 11 +- centreon-broker/storage/src/stream.cc | 13 +- centreon-broker/storage/test/connector.cc | 2 +- centreon-broker/storage/test/metric.cc | 9 +- centreon-broker/storage/test/perfdata.cc | 213 ++- centreon-broker/storage/test/rebuild.cc | 5 +- centreon-broker/storage/test/rebuild2.cc | 184 -- centreon-broker/storage/test/remove_graph.cc | 6 +- centreon-broker/storage/test/status-entry.cc | 10 +- centreon-broker/storage/test/status.cc | 5 +- centreon-broker/tcp/src/tcp_async.cc | 4 +- centreon-broker/tcp/src/tcp_connection.cc | 6 +- centreon-broker/tcp/test/acceptor.cc | 14 +- centreon-broker/test/CMakeLists.txt | 13 +- centreon-broker/unified_sql/CMakeLists.txt | 88 - .../centreon/broker/unified_sql/connector.hh | 63 - .../centreon/broker/unified_sql/rebuilder.hh | 105 -- .../broker/unified_sql/stored_timestamp.hh | 64 - .../com/centreon/broker/unified_sql/stream.hh | 340 ---- centreon-broker/unified_sql/src/connector.cc | 66 - centreon-broker/unified_sql/src/factory.cc | 180 -- centreon-broker/unified_sql/src/main.cc | 115 -- centreon-broker/unified_sql/src/rebuild.proto | 24 - centreon-broker/unified_sql/src/rebuilder.cc | 465 ----- .../unified_sql/src/stored_timestamp.cc | 114 -- centreon-broker/unified_sql/src/stream.cc | 545 ------ centreon-broker/unified_sql/src/stream_sql.cc | 1680 ----------------- .../unified_sql/src/stream_storage.cc | 654 ------- .../unified_sql/test/conflict_manager.cc | 134 -- centreon-broker/unified_sql/test/connector.cc | 94 - centreon-broker/unified_sql/test/metric.cc | 66 - centreon-broker/unified_sql/test/perfdata.cc | 558 ------ centreon-broker/unified_sql/test/rebuild.cc | 49 - centreon-broker/unified_sql/test/rebuild2.cc | 184 -- .../unified_sql/test/remove_graph.cc | 47 - .../unified_sql/test/status-entry.cc | 131 -- centreon-broker/unified_sql/test/status.cc | 133 -- centreon-broker/watchdog/CMakeLists.txt | 3 +- .../watchdog/src/configuration_parser.cc | 2 +- centreon-clib/CMakeLists.txt | 173 +- centreon-clib/cmake/package.cmake | 6 +- .../inc/com/centreon/clib/version.hh.in | 20 +- .../packaging/rpm/centreon-clib.spectemplate | 136 ++ .../rpm/debian/centreon-clib.triggers | 1 + .../packaging/rpm/debian/changelog.in | 5 + centreon-clib/packaging/rpm/debian/compat | 1 + centreon-clib/packaging/rpm/debian/control | 13 + centreon-clib/packaging/rpm/debian/copyright | 1 + centreon-clib/packaging/rpm/debian/rules | 16 + .../packaging/rpm/debian/source/format | 1 + centreon-clib/packaging/script/rpmbuild.sh | 42 + centreon-clib/test/CMakeLists.txt | 3 +- centreon-clib/test/handle_manager.cc | 4 +- centreon-clib/test/logging.cc | 4 +- centreon-clib/test/task_manager.cc | 20 +- centreon-connector/CMakeLists.txt | 23 +- centreon-connector/cmake/Findclib.cmake | 51 + .../inc/com/centreon/connector/namespace.hh | 10 +- centreon-connector/common/src/log.cc | 3 +- .../rpm/centreon-connector.spectemplate | 153 ++ .../packaging/script/rpmbuild.sh | 42 + centreon-connector/perl/CMakeLists.txt | 15 +- .../centreon/connector/perl/checks/check.hh | 5 +- .../com/centreon/connector/perl/options.hh | 2 +- .../centreon/connector/perl/orders/parser.hh | 2 +- centreon-connector/perl/src/checks/check.cc | 9 +- centreon-connector/perl/src/embedded_perl.cc | 5 +- centreon-connector/perl/src/main.cc | 2 +- centreon-connector/perl/src/multiplexer.cc | 4 +- centreon-connector/perl/src/policy.cc | 9 +- centreon-connector/perl/src/reporter.cc | 9 +- centreon-connector/perl/test/connector.cc | 47 +- centreon-connector/perl/test/embedded_perl.cc | 1 - centreon-connector/perl/test/main.cc | 4 +- centreon-connector/ssh/CMakeLists.txt | 17 +- centreon-connector/ssh/src/checks/check.cc | 8 +- centreon-connector/ssh/src/main.cc | 13 +- centreon-connector/ssh/src/multiplexer.cc | 2 +- centreon-connector/ssh/src/orders/parser.cc | 12 +- .../ssh/src/sessions/socket_handle.cc | 12 +- centreon-connector/ssh/test/buffer_handle.cc | 6 +- centreon-connector/ssh/test/checks.cc | 9 +- .../connector/command_execute_log_file.cc | 5 +- centreon-connector/ssh/test/fake_listener.cc | 6 + centreon-connector/ssh/test/fake_listener.hh | 8 +- centreon-connector/ssh/test/orders.cc | 3 + .../connector/build/CMakeLists.txt | 7 + .../centreon/benchmark/connector/connector.hh | 4 +- .../centreon/benchmark/connector/plugin.hh | 2 +- .../connector/src/basic_exception.cc | 4 +- .../connector/src/benchmark.cc | 6 +- .../connector/src/connector.cc | 20 +- .../centreon-benchmark/connector/src/main.cc | 13 +- .../centreon-benchmark/connector/src/misc.cc | 7 +- .../connector/src/plugin.cc | 17 +- centreon-engine/CMakeLists.txt | 294 ++- centreon-engine/cmake/package.cmake | 6 +- centreon-engine/conf/CMakeLists.txt | 23 +- centreon-engine/enginerpc/CMakeLists.txt | 2 + centreon-engine/enginerpc/engine_impl.cc | 298 ++- centreon-engine/enginerpc/enginerpc.cc | 4 +- .../enginerpc/examples/service_check.py | 4 +- .../com/centreon/engine/anomalydetection.hh | 2 +- .../engine/commands/command_listener.hh | 8 +- .../engine/configuration/anomalydetection.hh | 3 +- .../engine/configuration/applier/scheduler.hh | 2 +- .../engine/configuration/applier/state.hh | 2 +- .../centreon/engine/configuration/parser.hh | 2 +- .../com/centreon/engine/downtimes/downtime.hh | 6 +- .../engine/downtimes/downtime_manager.hh | 3 +- .../inc/com/centreon/engine/engine_impl.hh | 10 +- .../inc/com/centreon/engine/events/loop.hh | 10 +- .../com/centreon/engine/events/timed_event.hh | 2 +- .../com/centreon/engine/exceptions/error.hh | 2 +- .../inc/com/centreon/engine/my_lock.hh | 23 +- .../inc/com/centreon/engine/nebstructs.hh | 4 +- .../inc/com/centreon/engine/notifier.hh | 4 +- .../inc/com/centreon/engine/opt.hh | 2 +- .../inc/com/centreon/engine/service.hh | 2 +- .../inc/com/centreon/engine/statistics.hh | 3 +- .../com/centreon/engine/timezone_manager.hh | 5 +- .../inc/com/centreon/engine/version.hh.in | 6 +- centreon-engine/modules/bench/CMakeLists.txt | 6 +- .../modules/external_commands/CMakeLists.txt | 10 +- .../modules/external_commands/processing.hh | 4 +- .../modules/external_commands/src/utils.cc | 3 +- .../rpm/centreon-engine.spectemplate | 506 +++++ ...gine_integrate_centreon_engine2centreon.sh | 0 .../rpm/debian/centreon-engine.triggers | 1 + .../packaging/rpm/debian/changelog.in | 5 + centreon-engine/packaging/rpm/debian/compat | 1 + centreon-engine/packaging/rpm/debian/control | 13 + .../packaging/rpm/debian/copyright | 1 + centreon-engine/packaging/rpm/debian/postinst | 7 + centreon-engine/packaging/rpm/debian/postrm | 5 + centreon-engine/packaging/rpm/debian/rules | 36 + .../packaging/rpm/debian/source/format | 1 + centreon-engine/packaging/script/rpmbuild.sh | 43 + centreon-engine/scripts/centengine.service.in | 4 +- centreon-engine/src/broker.cc | 7 +- centreon-engine/src/command_manager_old.cc | 223 +++ centreon-engine/src/comment.cc | 35 +- .../src/compatibility/CMakeLists.txt | 4 +- .../src/configuration/anomalydetection.cc | 264 ++- .../configuration/applier/anomalydetection.cc | 65 +- .../src/configuration/applier/contact.cc | 2 +- .../configuration/applier/hostescalation.cc | 8 +- .../src/configuration/applier/scheduler.cc | 59 +- .../applier/serviceescalation.cc | 11 +- centreon-engine/src/configuration/object.cc | 25 +- centreon-engine/src/configuration/service.cc | 6 +- centreon-engine/src/configuration/state.cc | 21 +- centreon-engine/src/contactgroup.cc | 34 +- centreon-engine/src/customvariable.cc | 4 +- centreon-engine/src/dependency.cc | 12 +- centreon-engine/src/downtimes/downtime.cc | 7 +- .../src/downtimes/host_downtime.cc | 39 +- .../src/downtimes/service_downtime.cc | 106 +- centreon-engine/src/events/loop.cc | 4 +- centreon-engine/src/events/sched_info.cc | 1 + centreon-engine/src/exceptions/error.cc | 3 +- centreon-engine/src/main.cc | 2 +- .../src/retention/applier/comment.cc | 4 +- centreon-engine/src/service.cc | 19 +- centreon-engine/src/simumod/CMakeLists.txt | 2 +- centreon-engine/src/statistics.cc | 8 +- centreon-engine/src/xsddefault.cc | 5 +- centreon-engine/test/commands/CMakeLists.txt | 4 +- .../configuration/applier/check_scheduler.cc | 2 +- .../test/events/handle_timed_event.cc | 2 +- centreon-engine/tests/CMakeLists.txt | 3 + centreon-engine/tests/commands/connector.cc | 10 +- .../applier/applier-anomalydetection.cc | 18 +- .../applier/applier-connector.cc | 8 +- .../configuration/applier/applier-contact.cc | 4 +- .../applier/applier-contactgroup.cc | 13 +- .../configuration/applier/applier-host.cc | 8 +- .../applier/applier-hostescalation.cc | 11 +- .../applier/applier-hostgroup.cc | 11 +- .../configuration/applier/applier-service.cc | 8 +- .../applier/applier-serviceescalation.cc | 10 +- .../applier/applier-servicegroup.cc | 8 +- .../tests/configuration/contact.cc | 8 +- .../tests/contacts/contactgroup-config.cc | 9 +- .../tests/contacts/simple-contactgroup.cc | 8 +- centreon-engine/tests/downtimes/downtime.cc | 4 +- centreon-engine/tests/enginerpc/enginerpc.cc | 15 +- .../tests/external_commands/host.cc | 8 +- .../tests/external_commands/service.cc | 6 +- .../tests/macros/macro_hostname.cc | 200 +- centreon-engine/tests/macros/macro_service.cc | 246 ++- centreon-engine/tests/main.cc | 4 +- .../host_downtime_notification.cc | 14 +- .../host_flapping_notification.cc | 6 +- .../service_flapping_notification.cc | 20 +- .../service_timeperiod_notification.cc | 1 + centreon-engine/tests/retention/dump.cc | 12 +- .../get_next_valid_time/generic_month_date.cc | 1 + .../get_next_valid_time/normal_weekday.cc | 1 + .../offset_weekday_of_generic_month.cc | 1 + .../offset_weekday_of_specific_month.cc | 1 + .../specific_month_date.cc | 1 + centreon-engine/tests/timeperiod/utils.cc | 2 +- centreon-tests/.eslintignore | 5 + centreon-tests/.eslintrc.js | 8 + .../broker-database/networkFailure.robot | 220 +-- centreon-tests/broker-engine/hostgroups.robot | 32 - .../broker-engine/retention-duplicates.robot | 203 +- centreon-tests/broker-engine/rrd.robot | 119 +- centreon-tests/broker/sql.robot | 132 +- centreon-tests/broker/start-stop.robot | 38 - centreon-tests/resources/BrokerDatabase.py | 23 + centreon-tests/resources/Common.py | 8 +- centreon-tests/resources/Engine.py | 12 +- centreon-tests/resources/resources.robot | 6 +- .../resources/specific-duplication.py | 102 +- ci/debian/centreon-clib-dev.install | 2 +- ci/debian/centreon-clib.install | 3 +- ci/debian/centreon-connector-perl.install | 2 +- ci/debian/centreon-connector-ssh.install | 2 +- ci/debian/centreon-engine-dev.install | 2 + ci/debian/centreon-engine.install | 8 +- ci/debian/rules | 18 +- ci/scripts/collect-deb-package.sh | 17 +- ci/scripts/collect-rpm-package.sh | 64 +- ci/scripts/collect-sources-delivery.sh | 2 +- ci/scripts/collect-unit-tests.sh | 2 +- cmake.sh | 20 +- new_centreon_collect.sh | 316 ++++ packaging/rpm/centreon-collect.spec | 464 ----- packaging/script/rpmbuild.sh | 41 - 678 files changed, 19652 insertions(+), 12566 deletions(-) delete mode 100644 bbdo/CMakeLists.txt delete mode 100644 bbdo/events.hh delete mode 100755 bbdo/generate-accessor.py delete mode 100644 bbdo/rebuild.proto delete mode 100644 bbdo/service.proto rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/ba_duration_event.hh (92%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/ba_event.hh (93%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/ba_status.hh (93%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/dimension_ba_bv_relation_event.hh (95%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/dimension_ba_event.hh (92%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/dimension_ba_timeperiod_relation.hh (94%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/dimension_bv_event.hh (91%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/dimension_kpi_event.hh (92%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/dimension_timeperiod.hh (92%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/dimension_timeperiod_exception.hh (95%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/dimension_timeperiod_exclusion.hh (95%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/dimension_truncate_table_signal.hh (94%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/inherited_downtime.hh (91%) create mode 100644 centreon-broker/bam/inc/com/centreon/broker/bam/internal.hh rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/kpi_event.hh (87%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/kpi_status.hh (94%) rename {bbdo => centreon-broker/bam/inc/com/centreon/broker}/bam/rebuild.hh (92%) rename {bbdo/bam => centreon-broker/bam/src}/ba_duration_event.cc (97%) rename {bbdo/bam => centreon-broker/bam/src}/ba_event.cc (90%) rename {bbdo/bam => centreon-broker/bam/src}/ba_status.cc (97%) rename {bbdo/bam => centreon-broker/bam/src}/dimension_ba_bv_relation_event.cc (89%) rename {bbdo/bam => centreon-broker/bam/src}/dimension_ba_event.cc (97%) rename {bbdo/bam => centreon-broker/bam/src}/dimension_ba_timeperiod_relation.cc (96%) rename {bbdo/bam => centreon-broker/bam/src}/dimension_bv_event.cc (97%) rename {bbdo/bam => centreon-broker/bam/src}/dimension_kpi_event.cc (98%) rename {bbdo/bam => centreon-broker/bam/src}/dimension_timeperiod.cc (97%) rename {bbdo/bam => centreon-broker/bam/src}/dimension_timeperiod_exception.cc (96%) rename {bbdo/bam => centreon-broker/bam/src}/dimension_timeperiod_exclusion.cc (95%) rename {bbdo/bam => centreon-broker/bam/src}/dimension_truncate_table_signal.cc (91%) rename {bbdo/bam => centreon-broker/bam/src}/inherited_downtime.cc (88%) rename {bbdo/bam => centreon-broker/bam/src}/kpi_event.cc (96%) rename {bbdo/bam => centreon-broker/bam/src}/kpi_status.cc (97%) rename {bbdo/bam => centreon-broker/bam/src}/rebuild.cc (93%) delete mode 100644 centreon-broker/core/inc/com/centreon/broker/io/protobuf.hh rename bbdo/bam/state.hh => centreon-broker/core/inc/com/centreon/broker/misc/global_lock.hh (75%) create mode 100644 centreon-broker/core/inc/com/centreon/broker/multiplexing/hooker.hh create mode 100644 centreon-broker/core/src/misc/global_lock.cc create mode 100644 centreon-broker/core/src/multiplexing/hooker.cc delete mode 100644 centreon-broker/core/test/misc/perfdata.cc create mode 100644 centreon-broker/core/test/multiplexing/engine/hook.cc create mode 100644 centreon-broker/core/test/multiplexing/engine/hooker.hh create mode 100644 centreon-broker/core/test/multiplexing/engine/unhook.cc create mode 100644 centreon-broker/notification/CMakeLists.txt create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/action.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/command_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/command_by_id_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_command_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_contact_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_dependency_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_node_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_notification_method_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_notification_rule_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_timeperiod_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/contact_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/contact_by_id_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/dependency_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/dependency_by_node_id_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/global_macro_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/macro_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_by_node_id_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_set_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_method_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_method_by_id_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_by_id_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_by_node_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_by_id_builder.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_linker.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/connector.hh rename centreon-broker/{unified_sql/inc/com/centreon/broker/unified_sql => notification/inc/com/centreon/broker/notification}/factory.hh (68%) create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/loaders/command_loader.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/loaders/contact_loader.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/loaders/dependency_loader.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/loaders/escalation_loader.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/loaders/macro_loader.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/loaders/node_loader.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/loaders/notification_method_loader.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/loaders/notification_rule_loader.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/loaders/timeperiod_loader.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/macro_context.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/macro_generator.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/macro_getters.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/node_cache.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/notification_scheduler.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/object_cache.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/objects/command.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/objects/contact.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/objects/defines.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/objects/dependency.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/objects/node.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/objects/node_id.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/objects/notification_method.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/objects/notification_rule.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/objects/record.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/process.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/process_manager.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/run_queue.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/state.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/stream.hh create mode 100644 centreon-broker/notification/inc/com/centreon/broker/notification/utilities/get_datetime_string.hh rename centreon-broker/{unified_sql/inc/com/centreon/broker/unified_sql/internal.hh => notification/inc/com/centreon/broker/notification/utilities/ptr_typedef.hh} (63%) rename centreon-broker/{unified_sql/inc/com/centreon/broker/unified_sql/events.hh => notification/inc/com/centreon/broker/notification/utilities/qhash_func.hh} (63%) create mode 100644 centreon-broker/notification/mysql_v3.sql create mode 100644 centreon-broker/notification/src/action.cc create mode 100644 centreon-broker/notification/src/builders/command_by_id_builder.cc create mode 100644 centreon-broker/notification/src/builders/composed_command_builder.cc create mode 100644 centreon-broker/notification/src/builders/composed_contact_builder.cc create mode 100644 centreon-broker/notification/src/builders/composed_dependency_builder.cc create mode 100644 centreon-broker/notification/src/builders/composed_node_builder.cc create mode 100644 centreon-broker/notification/src/builders/composed_notification_method_builder.cc create mode 100644 centreon-broker/notification/src/builders/composed_notification_rule_builder.cc create mode 100644 centreon-broker/notification/src/builders/composed_timeperiod_builder.cc create mode 100644 centreon-broker/notification/src/builders/contact_by_id_builder.cc create mode 100644 centreon-broker/notification/src/builders/dependency_by_node_id_builder.cc create mode 100644 centreon-broker/notification/src/builders/global_macro_builder.cc create mode 100644 centreon-broker/notification/src/builders/node_by_node_id_builder.cc create mode 100644 centreon-broker/notification/src/builders/node_set_builder.cc create mode 100644 centreon-broker/notification/src/builders/notification_method_by_id_builder.cc create mode 100644 centreon-broker/notification/src/builders/notification_rule_by_id_builder.cc create mode 100644 centreon-broker/notification/src/builders/notification_rule_by_node_builder.cc create mode 100644 centreon-broker/notification/src/builders/timeperiod_by_id_builder.cc create mode 100644 centreon-broker/notification/src/builders/timeperiod_linker.cc create mode 100644 centreon-broker/notification/src/connector.cc create mode 100644 centreon-broker/notification/src/factory.cc create mode 100644 centreon-broker/notification/src/loaders/command_loader.cc create mode 100644 centreon-broker/notification/src/loaders/contact_loader.cc create mode 100644 centreon-broker/notification/src/loaders/dependency_loader.cc create mode 100644 centreon-broker/notification/src/loaders/escalation_loader.cc create mode 100644 centreon-broker/notification/src/loaders/macro_loader.cc create mode 100644 centreon-broker/notification/src/loaders/node_loader.cc create mode 100644 centreon-broker/notification/src/loaders/notification_method_loader.cc create mode 100644 centreon-broker/notification/src/loaders/notification_rule_loader.cc create mode 100644 centreon-broker/notification/src/loaders/timeperiod_loader.cc create mode 100644 centreon-broker/notification/src/macro_context.cc create mode 100644 centreon-broker/notification/src/macro_generator.cc create mode 100644 centreon-broker/notification/src/macro_getters.cc create mode 100644 centreon-broker/notification/src/main.cc create mode 100644 centreon-broker/notification/src/node_cache.cc create mode 100644 centreon-broker/notification/src/notification_scheduler.cc create mode 100644 centreon-broker/notification/src/objects/command.cc create mode 100644 centreon-broker/notification/src/objects/contact.cc create mode 100644 centreon-broker/notification/src/objects/defines.cc create mode 100644 centreon-broker/notification/src/objects/dependency.cc create mode 100644 centreon-broker/notification/src/objects/node.cc create mode 100644 centreon-broker/notification/src/objects/node_id.cc create mode 100644 centreon-broker/notification/src/objects/notification_method.cc create mode 100644 centreon-broker/notification/src/objects/notification_rule.cc create mode 100644 centreon-broker/notification/src/process.cc create mode 100644 centreon-broker/notification/src/process_manager.cc create mode 100644 centreon-broker/notification/src/run_queue.cc create mode 100644 centreon-broker/notification/src/state.cc create mode 100644 centreon-broker/notification/src/stream.cc create mode 100644 centreon-broker/notification/src/utilities/get_datetime_string.cc create mode 100644 centreon-broker/notification/src/utilities/qhash_func.cc create mode 100644 centreon-broker/packaging/rpm/centreon-broker.spectemplate create mode 100755 centreon-broker/packaging/rpm/debian/centreon-broker-cbmod.postinst create mode 100644 centreon-broker/packaging/rpm/debian/centreon-broker-cbmod.triggers create mode 100755 centreon-broker/packaging/rpm/debian/centreon-broker-core.postinst create mode 100755 centreon-broker/packaging/rpm/debian/centreon-broker-core.postrm create mode 100644 centreon-broker/packaging/rpm/debian/changelog.in create mode 100644 centreon-broker/packaging/rpm/debian/compat create mode 100644 centreon-broker/packaging/rpm/debian/control create mode 100644 centreon-broker/packaging/rpm/debian/copyright create mode 100755 centreon-broker/packaging/rpm/debian/rules create mode 100644 centreon-broker/packaging/rpm/debian/source/format create mode 100755 centreon-broker/packaging/script/rpmbuild.sh create mode 100644 centreon-broker/storage/inc/com/centreon/broker/storage/exceptions/perfdata.hh rename {bbdo => centreon-broker/storage/inc/com/centreon/broker}/storage/index_mapping.hh (91%) rename {bbdo => centreon-broker/storage/inc/com/centreon/broker}/storage/metric.hh (84%) rename {bbdo => centreon-broker/storage/inc/com/centreon/broker}/storage/metric_mapping.hh (94%) create mode 100644 centreon-broker/storage/inc/com/centreon/broker/storage/parser.hh rename centreon-broker/{core/inc/com/centreon/broker/misc => storage/inc/com/centreon/broker/storage}/perfdata.hh (75%) rename {bbdo => centreon-broker/storage/inc/com/centreon/broker}/storage/rebuild.hh (90%) rename {bbdo => centreon-broker/storage/inc/com/centreon/broker}/storage/remove_graph.hh (90%) rename {bbdo => centreon-broker/storage/inc/com/centreon/broker}/storage/status.hh (91%) rename centreon-broker/{rrd/inc/com/centreon/broker/rrd/internal.hh => storage/src/exceptions/perfdata.cc} (65%) rename {bbdo/storage => centreon-broker/storage/src}/index_mapping.cc (86%) rename {bbdo/storage => centreon-broker/storage/src}/metric.cc (87%) rename {bbdo/storage => centreon-broker/storage/src}/metric_mapping.cc (90%) rename centreon-broker/{core/src/misc/parse_perfdata.cc => storage/src/parser.cc} (89%) rename centreon-broker/{core/src/misc => storage/src}/perfdata.cc (95%) rename {bbdo/storage => centreon-broker/storage/src}/rebuild.cc (92%) delete mode 100644 centreon-broker/storage/src/rebuild.proto rename {bbdo/storage => centreon-broker/storage/src}/remove_graph.cc (94%) rename {bbdo/storage => centreon-broker/storage/src}/status.cc (92%) delete mode 100644 centreon-broker/storage/test/rebuild2.cc delete mode 100644 centreon-broker/unified_sql/CMakeLists.txt delete mode 100644 centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/connector.hh delete mode 100644 centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/rebuilder.hh delete mode 100644 centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/stored_timestamp.hh delete mode 100644 centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh delete mode 100644 centreon-broker/unified_sql/src/connector.cc delete mode 100644 centreon-broker/unified_sql/src/factory.cc delete mode 100644 centreon-broker/unified_sql/src/main.cc delete mode 100644 centreon-broker/unified_sql/src/rebuild.proto delete mode 100644 centreon-broker/unified_sql/src/rebuilder.cc delete mode 100644 centreon-broker/unified_sql/src/stored_timestamp.cc delete mode 100644 centreon-broker/unified_sql/src/stream.cc delete mode 100644 centreon-broker/unified_sql/src/stream_sql.cc delete mode 100644 centreon-broker/unified_sql/src/stream_storage.cc delete mode 100644 centreon-broker/unified_sql/test/conflict_manager.cc delete mode 100644 centreon-broker/unified_sql/test/connector.cc delete mode 100644 centreon-broker/unified_sql/test/metric.cc delete mode 100644 centreon-broker/unified_sql/test/perfdata.cc delete mode 100644 centreon-broker/unified_sql/test/rebuild.cc delete mode 100644 centreon-broker/unified_sql/test/rebuild2.cc delete mode 100644 centreon-broker/unified_sql/test/remove_graph.cc delete mode 100644 centreon-broker/unified_sql/test/status-entry.cc delete mode 100644 centreon-broker/unified_sql/test/status.cc create mode 100644 centreon-clib/packaging/rpm/centreon-clib.spectemplate create mode 100644 centreon-clib/packaging/rpm/debian/centreon-clib.triggers create mode 100644 centreon-clib/packaging/rpm/debian/changelog.in create mode 100644 centreon-clib/packaging/rpm/debian/compat create mode 100644 centreon-clib/packaging/rpm/debian/control create mode 100644 centreon-clib/packaging/rpm/debian/copyright create mode 100755 centreon-clib/packaging/rpm/debian/rules create mode 100644 centreon-clib/packaging/rpm/debian/source/format create mode 100755 centreon-clib/packaging/script/rpmbuild.sh create mode 100644 centreon-connector/cmake/Findclib.cmake create mode 100644 centreon-connector/packaging/rpm/centreon-connector.spectemplate create mode 100755 centreon-connector/packaging/script/rpmbuild.sh create mode 100644 centreon-engine/packaging/rpm/centreon-engine.spectemplate rename {packaging => centreon-engine/packaging}/rpm/centreonengine_integrate_centreon_engine2centreon.sh (100%) create mode 100644 centreon-engine/packaging/rpm/debian/centreon-engine.triggers create mode 100644 centreon-engine/packaging/rpm/debian/changelog.in create mode 100644 centreon-engine/packaging/rpm/debian/compat create mode 100644 centreon-engine/packaging/rpm/debian/control create mode 100644 centreon-engine/packaging/rpm/debian/copyright create mode 100755 centreon-engine/packaging/rpm/debian/postinst create mode 100755 centreon-engine/packaging/rpm/debian/postrm create mode 100755 centreon-engine/packaging/rpm/debian/rules create mode 100644 centreon-engine/packaging/rpm/debian/source/format create mode 100755 centreon-engine/packaging/script/rpmbuild.sh create mode 100644 centreon-engine/src/command_manager_old.cc create mode 100644 centreon-tests/.eslintignore create mode 100644 centreon-tests/.eslintrc.js create mode 100644 centreon-tests/resources/BrokerDatabase.py create mode 100755 new_centreon_collect.sh delete mode 100644 packaging/rpm/centreon-collect.spec delete mode 100755 packaging/script/rpmbuild.sh diff --git a/.gitignore b/.gitignore index 161127dd293..4d4837c2902 100644 --- a/.gitignore +++ b/.gitignore @@ -53,43 +53,43 @@ workspace.* src/config/centreon-engine/*.cfg -**/.*.swp + +*.swp **/.idea/* **/.vscode/* -**/CMakeFiles/* -**/__pycache__/* **/build/* -**/engine_pb2*.py -*.swp -.idea/* -bbdo/*_accessor.hh -build/* -centreon-clib/inc/com/centreon/clib/version.hh -centreon-clib/script/* -centreon-connectors/perl/src/xs_init.cc -centreon-connectors/perl/test/connector/paths.hh -centreon-connectors/ssh/test/connector/binary.hh -centreon-engine/benchmark/centreon-engine/* -centreon-engine/benchmark/lib/* -centreon-engine/benchmark/log/* -centreon-engine/cmake-build-debug/* centreon-engine/conf/centengine.cfg centreon-engine/conf/objects/*.cfg centreon-engine/conf/resource.cfg centreon-engine/doc/_build -centreon-engine/enginerpc/engine.*pb.cc -centreon-engine/enginerpc/engine.*pb.h -centreon-engine/gtest.cbp centreon-engine/inc/com/centreon/engine/version.hh centreon-engine/inc/compatibility/common.h centreon-engine/inc/compatibility/locations.h -centreon-engine/modules/bench/passive/paths.hh centreon-engine/scripts/centengine.pc centreon-engine/scripts/centengine.sh centreon-engine/src/simumod/neb.cc centreon-engine/tags -ci/repo/* +centreon-engine/gtest.cbp +**/CMakeFiles/* +centreon-engine/cmake-build-debug/* +centreon-engine/modules/bench/passive/paths.hh +centreon-engine/enginerpc/engine.*pb.cc +centreon-engine/enginerpc/engine.*pb.h +**/__pycache__/* +**/engine_pb2*.py +centreon-engine/benchmark/centreon-engine/* +centreon-engine/benchmark/log/* +centreon-engine/benchmark/lib/* +**/.*.swp +centreon-connectors/perl/src/xs_init.cc +centreon-connectors/perl/test/connector/paths.hh +centreon-connectors/ssh/test/connector/binary.hh +build/* +.idea/* cmake-build-debug/* -log.html +centreon-clib/script/* +centreon-clib/inc/com/centreon/clib/version.hh output.xml +log.html report.html +ci/repo/* diff --git a/CMakeLists.txt b/CMakeLists.txt index 4b60bdd679f..10f0f7099a5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -20,24 +20,15 @@ # Global settings. # - # Set necessary settings. set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -cmake_minimum_required(VERSION 3.1) +cmake_minimum_required(VERSION 2.8) project("Centreon Collect" C CXX) if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND NOT CMAKE_CXX_COMPILER_ID STREQUAL "Clang") message(FATAL_ERROR "You can build broker with g++ or clang++. CMake will exit.") endif () -#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -stdlib=libc++") -#set(CMAKE_CXX_COMPILER "clang++") -add_definitions("-D_GLIBCXX_USE_CXX11_ABI=1") -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - set(ALLOW_DUPLICATE_EXECUTABLE TRUE) - -set(BUILD_ARGS "-w" "dupbuild=warn") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") # set -latomic if OS is Raspbian. if (CMAKE_SYSTEM_PROCESSOR MATCHES "arm") @@ -58,51 +49,6 @@ set(USER_BROKER centreon-broker) set(USER_ENGINE centreon-engine) ################################## -include(${CMAKE_BINARY_DIR}/conan_paths.cmake) -include(GNUInstallDirs) - -set(CMAKE_INSTALL_PREFIX "/usr") -option(WITH_TESTING "Build unit tests." OFF) -if (WITH_TESTING) - find_package(GTest REQUIRED) -endif () - -set(protobuf_MODULE_COMPATIBLE True) - -find_package(asio REQUIRED) -find_package(fmt REQUIRED) -find_package(spdlog REQUIRED) -find_package(OpenSSL REQUIRED) -find_package(c-ares REQUIRED) -find_package(ZLIB REQUIRED) -find_package(nlohmann_json REQUIRED) -find_package(Protobuf REQUIRED) -find_package(gRPC REQUIRED) - -add_definitions(${spdlog_DEFINITIONS}) - -include_directories(${nlohmann_json_INCLUDE_DIRS}) -include_directories(${fmt_INCLUDE_DIRS}) -include_directories(${spdlog_INCLUDE_DIRS}) -include_directories(${asio_INCLUDE_DIRS}) -include_directories(${protobuf_INCLUDE_DIRS}) -include_directories(${absl_INCLUDE_DIRS}) -include_directories(${gRPC_INCLUDE_DIRS}) -include_directories(${ZLIB_INCLUDE_DIRS}) -include_directories(${CMAKE_SOURCE_DIR}) - -link_directories(${nlohmann_json_LIB_DIRS}) -link_directories(${fmt_LIB_DIRS}) -link_directories(${spdlog_LIB_DIRS}) -link_directories(${protobuf_LIB_DIRS}) -link_directories(${gRPC_LIB_DIRS}) -link_directories(${c-ares_LIB_DIRS}) -link_directories(${OpenSSL_LIB_DIRS}) -link_directories(${ZLIB_LIB_DIRS}) - -set(PROTOBUF_PREFIX "${protobuf_LIB_DIRS}/..") - -add_subdirectory(bbdo) add_subdirectory(centreon-broker) add_subdirectory(centreon-clib) add_subdirectory(centreon-engine) diff --git a/README.md b/README.md index 45392064846..140772561e4 100644 --- a/README.md +++ b/README.md @@ -116,8 +116,8 @@ You'll need to download the project and launch the *cmake.sh* script to prepare the compilation environment: ```shell -git clone https://github.com/centreon/centreon-collect -cd centreon-collect +git clone https://github.com/centreon/centreon-Collect +cd centreon-Collect ./cmake.sh ``` @@ -163,11 +163,11 @@ pip3 install conan You can now prepare the compilation environment: ```shell -git clone https://github.com/centreon/centreon-collect -mkdir -p centreon-collect/build -cd centreon-collect/build +git clone https://github.com/centreon/centreon-Collect +mkdir -p centreon-Collect/build +cd centreon-Collect/build conan install .. --build=missing -cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DWITH_TESTING=On -DWITH_MODULE_SIMU=On .. +cmake -DWITH_CENTREON_CLIB_INCLUDE_DIR=../centreon-clib/inc/ -DWITH_CENTREON_CLIB_LIBRARIES=centreon-clib/libcentreon_clib.so -DCMAKE_BUILD_TYPE=Release -DWITH_PREFIX=/usr -DWITH_PREFIX_BIN=/usr/sbin -DWITH_USER_BROKER=centreon-broker -DWITH_USER_ENGINE=centreon-engine -DWITH_GROUP_BROKER=centreon-broker -DWITH_GROUP_ENGINE=centreon-engine -DWITH_TESTING=On -DWITH_PREFIX_MODULES=/usr/share/centreon/lib/centreon-broker -DWITH_PREFIX_CONF_BROKER=/etc/centreon-broker -DWITH_PREFIX_LIB_BROKER=/usr/lib64/nagios -DWITH_PREFIX_CONF_ENGINE=/etc/centreon-engine -DWITH_PREFIX_LIB_ENGINE=/usr/lib64/centreon-engine -DWITH_PREFIX_LIB_CLIB=/usr/lib/ -DWITH_RW_DIR=/var/lib/centreon-engine/rw -DWITH_VAR_DIR=/var/log/centreon-engine -DWITH_MODULE_SIMU=On .. ``` @@ -195,7 +195,7 @@ You're done! ## Bug reports / Feature requests The best way to report a bug or to request a feature is to open an issue -in GitHub's [issue tracker](https://github.com/centreon/centreon-collect/issues/). +in GitHub's [issue tracker](https://github.com/centreon/centreon-Collect/issues/). Please note that Centreon Collect follows the [same workflow as Centreon](https://github.com/centreon/centreon/issues/new/choose) diff --git a/bbdo/CMakeLists.txt b/bbdo/CMakeLists.txt deleted file mode 100644 index 0a747dd9bd3..00000000000 --- a/bbdo/CMakeLists.txt +++ /dev/null @@ -1,100 +0,0 @@ -## -## Copyright 2021 Centreon -## -## Licensed under the Apache License, Version 2.0 (the "License"); -## you may not use this file except in compliance with the License. -## You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## -## For more information : contact@centreon.com -## - -macro(get_protobuf_files name) - set(proto_file "${name}.proto") - set(full_proto_file "${CMAKE_SOURCE_DIR}/bbdo/${name}.proto") - add_custom_command(OUTPUT "${CMAKE_SOURCE_DIR}/bbdo/${name}.pb.cc" "${CMAKE_SOURCE_DIR}/bbdo/${name}.pb.h" - DEPENDS ${full_proto_file} - COMMENT "Generating interface files of the bbdo file ${proto_file}" - COMMAND ${PROTOBUF_PREFIX}/bin/protoc - ARGS --cpp_out=${CMAKE_SOURCE_DIR}/bbdo --proto_path=${CMAKE_SOURCE_DIR}/bbdo ${proto_file} - VERBATIM - ) - set_source_files_properties("${CMAKE_SOURCE_DIR}/bbdo/${name}.pb.cc" PROPERTIES GENERATED TRUE) - set_source_files_properties("${CMAKE_SOURCE_DIR}/bbdo/${name}.pb.h" PROPERTIES GENERATED TRUE) - set(proto_${name} - "${CMAKE_SOURCE_DIR}/bbdo/${name}.pb.cc" - "${CMAKE_SOURCE_DIR}/bbdo/${name}.pb.h") -endmacro() - -macro(get_protobuf_accessor name) - set(proto_file "${name}.proto") - set(full_proto_file "${CMAKE_SOURCE_DIR}/bbdo/${name}.proto") - add_custom_command(OUTPUT "${CMAKE_SOURCE_DIR}/bbdo/${name}_accessor.hh" - DEPENDS ${full_proto_file} - COMMENT "Generating accessor to protobuf message ${proto_file}" - COMMAND python3 - ARGS ${full_proto_file} - VERBATIM - ) -endmacro() - -include_directories("${CMAKE_SOURCE_DIR}/centreon-broker/core/inc") - -add_library( - bbdo_storage STATIC - "storage/index_mapping.cc" - "storage/metric_mapping.cc" - "storage/metric.cc" - "storage/rebuild.cc" - "storage/remove_graph.cc" - "storage/status.cc" - "storage/metric.hh" - "storage/rebuild.hh" - "storage/remove_graph.hh" - "storage/status.hh" - ) -set_target_properties(bbdo_storage PROPERTIES COMPILE_FLAGS "-fPIC") -add_library( - bbdo_bam STATIC - "bam/ba_duration_event.cc" - "bam/dimension_ba_bv_relation_event.hh" - "bam/dimension_kpi_event.cc" - "bam/dimension_timeperiod.hh" - "bam/kpi_status.cc" - "bam/ba_duration_event.hh" - "bam/dimension_ba_event.cc" - "bam/dimension_kpi_event.hh" - "bam/dimension_truncate_table_signal.cc" - "bam/kpi_status.hh" - "bam/ba_event.cc" - "bam/dimension_ba_event.hh" - "bam/dimension_timeperiod.cc" - "bam/dimension_truncate_table_signal.hh" - "bam/rebuild.cc" - "bam/ba_event.hh" - "bam/dimension_ba_timeperiod_relation.cc" - "bam/dimension_timeperiod_exception.cc" - "bam/inherited_downtime.cc" - "bam/rebuild.hh" - "bam/ba_status.cc" - "bam/dimension_ba_timeperiod_relation.hh" - "bam/dimension_timeperiod_exception.hh" - "bam/inherited_downtime.hh" - "bam/ba_status.hh" - "bam/dimension_bv_event.cc" - "bam/dimension_timeperiod_exclusion.cc" - "bam/kpi_event.cc" - "bam/dimension_ba_bv_relation_event.cc" - "bam/dimension_bv_event.hh" - "bam/dimension_timeperiod_exclusion.hh" - "bam/kpi_event.hh" - ) -set_target_properties(bbdo_bam PROPERTIES COMPILE_FLAGS "-fPIC") -add_dependencies(bbdo_bam table_max_size) diff --git a/bbdo/events.hh b/bbdo/events.hh deleted file mode 100644 index dcdd40feecf..00000000000 --- a/bbdo/events.hh +++ /dev/null @@ -1,128 +0,0 @@ -/* -** Copyright 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#ifndef CC_BROKER_EVENTS_HH -#define CC_BROKER_EVENTS_HH - -#include -#include - -namespace com { -namespace centreon { -namespace broker { -namespace io { -enum data_category { - neb = 1, - bbdo = 2, - storage = 3, - dumper = 5, - bam = 6, - extcmd = 7, - generator = 8, - internal = 65535 -}; -constexpr uint16_t category_id(const char* name) { - if (strncmp("neb", name, 4) == 0) - return neb; - if (strncmp("bbdo", name, 5) == 0) - return bbdo; - if (strncmp("storage", name, 8) == 0) - return storage; - if (strncmp("internal", name, 9) == 0) - return internal; - if (strncmp("bam", name, 4) == 0) - return bam; - if (strncmp("extcmd", name, 7) == 0) - return extcmd; - if (strncmp("dumper", name, 7) == 0) - return dumper; - if (strncmp("generator", name, 10) == 0) - return generator; - return 0; -} -constexpr const char* category_name(data_category cat) { - switch (cat) { - case neb: - return "neb"; - case bbdo: - return "bbdo"; - case storage: - return "storage"; - case dumper: - return "dumper"; - case bam: - return "bam"; - case extcmd: - return "extcmd"; - case generator: - return "generator"; - case internal: - return "internal"; - default: - return "unknown category"; - } -} -} // namespace io -namespace storage { -enum data_element { - de_metric = 1, - de_rebuild = 2, - de_remove_graph = 3, - de_status = 4, - de_index_mapping = 5, - de_metric_mapping = 6, - de_pb_rebuild = 7, -}; -} -namespace bam { -enum data_element { - de_ba_status = 1, - de_kpi_status, - de_meta_service_status, - de_ba_event, - de_kpi_event, - de_ba_duration_event, - de_dimension_ba_event, - de_dimension_kpi_event, - de_dimension_ba_bv_relation_event, - de_dimension_bv_event, - de_dimension_truncate_table_signal, - de_rebuild, - de_dimension_timeperiod, - de_dimension_ba_timeperiod_relation, - de_dimension_timeperiod_exception, - de_dimension_timeperiod_exclusion, - de_inherited_downtime -}; -} -constexpr uint32_t make_type(io::data_category cat, uint32_t elem) { - return (cat << 16) | elem; -} -constexpr uint16_t category_of_type(uint32_t type) { - return static_cast(type >> 16); -} -constexpr uint16_t element_of_type(uint32_t type) { - return static_cast(type); -} -constexpr uint32_t storage_pb_rebuild = - make_type(io::storage, storage::de_pb_rebuild); -} // namespace broker -} // namespace centreon -} // namespace com - -#endif /* !CC_BROKER_EVENTS_HH */ diff --git a/bbdo/generate-accessor.py b/bbdo/generate-accessor.py deleted file mode 100755 index 6ccd444400e..00000000000 --- a/bbdo/generate-accessor.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/python3 -""" -** Copyright 2021 Centreon -** -** Licensed under the Apache License, Version 2.0(the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -""" - -import sys -import re - -obj = sys.argv[1] -obj_u = obj.upper() -obj_c = obj.capitalize() - -accessors = [] -block_level = 0 -decl = re.compile(r'\s*([a-zA-Z0-9]+)\s+([a-z_0-9]+)\s*=\s*[0-9]+;') -enum = re.compile(r'\s*enum\s+([a-zA-Z]+)\s+{') -enums = [] -with open("{}.proto".format(obj), encoding='utf-8') as fp: - line = fp.readline() - while line: - if block_level == 0: - if line == "message {} {{\n".format(obj_c): - block_level += 1 - else: - if line == "}": - block_level -= 1 - else: - if block_level == 1: - m = decl.match(line) - if m: - if m.group(1) in ['bool', 'int32', 'int64', 'uint32', 'uint64', 'string'] or\ - m.group(1) in enums: - d = """ {{"{0}", [obj = this->_obj] {{ return misc::variant(obj->{0}()); }}}}""".format( - m.group(2)) - accessors.append(d) - else: - m = enum.match(line) - if m: - enums.append(m.group(1)) - line = fp.readline() - fp.close() - -acc = ",\n".join(accessors) -content = """#ifndef CC_BROKER_{0}_ACCESSOR_HH -#define CC_BROKER_{0}_ACCESSOR_HH -#include -#include "com/centreon/broker/misc/variant.hh" -#include "com/centreon/exceptions/msg_fmt.hh" -#include "bbdo/{2}.pb.h" - -namespace com {{ -namespace centreon {{ -namespace broker {{ - -class {2}_accessor {{ - {1}* const _obj; - const std::unordered_map> _get{{ -{3} - }}; - - public: - {2}_accessor({1}* obj) : _obj{{obj}} {{}} - misc::variant get(const std::string& key) {{ - auto it = _get.find(key); - if (it != _get.end()) - return it->second(); - else - throw exceptions::msg_fmt( - "Service protobuf object does not contain '{{}}' element", key); - }} -}}; - -}} // namespace broker -}} // namespace centreon -}} // namespace com - -#endif /* !CC_BROKER_{0}_ACCESSOR_HH */ -""".format(obj_u, obj_c, obj, acc) - -print(content, file=open("{}_accessor.hh".format(obj), "w")) diff --git a/bbdo/rebuild.proto b/bbdo/rebuild.proto deleted file mode 100644 index 26bea825e80..00000000000 --- a/bbdo/rebuild.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; - -package com.centreon.broker; - -message Point { - int64 ctime = 1; - double value = 2; - int32 status = 3; -} - -message Metric { - int32 value_type = 1; - uint64 metric_id = 2; -} - -message Rebuild { - oneof type { - uint64 index_id = 1; - Metric metric = 2; - } - uint32 interval = 3; - uint32 length = 4; - repeated Point data = 5; -} diff --git a/bbdo/service.proto b/bbdo/service.proto deleted file mode 100644 index f32f1302818..00000000000 --- a/bbdo/service.proto +++ /dev/null @@ -1,28 +0,0 @@ -syntax = "proto3"; - -package com.centreon.broker; - -message Service { - uint64 host_id = 1; - uint64 service_id = 2; - - enum AckType { - ACKNOWLEDGEMENT_NONE = 0; - ACKNOWLEDGEMENT_NORMAL = 1; - ACKNOWLEDGEMENT_STICKY = 2; - } - bool acknowledged = 3; - AckType acknowledgement_type = 4; - bool active_checks_enabled = 5; - string check_command = 6; - int32 check_interval = 7; - string check_period = 8; - - enum CheckType { - CHECK_ACTIVE = 0; - CHECK_PASSIVE = 1; - } - CheckType check_type = 9; - int32 current_check_attempt = 10; - -} diff --git a/centreon-broker/CMakeLists.txt b/centreon-broker/CMakeLists.txt index 15546bcf69a..8f8fea7c874 100644 --- a/centreon-broker/CMakeLists.txt +++ b/centreon-broker/CMakeLists.txt @@ -21,7 +21,13 @@ # # Set necessary settings. +cmake_minimum_required(VERSION 2.8) project("Centreon Broker" C CXX) +if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND NOT CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + message(FATAL_ERROR "You can build broker with g++ or clang++. CMake will exit.") +endif () + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") # set -latomic if OS is Raspbian. if (CMAKE_SYSTEM_PROCESSOR MATCHES "arm") @@ -71,14 +77,42 @@ add_custom_target(table_max_size DEPENDS ${INC_DIR}/database/table_max_size.hh) set_source_files_properties(${INC_DIR}/database/table_max_size.hh PROPERTIES GENERATED TRUE) +set(protobuf_MODULE_COMPATIBLE True) +find_package(nlohmann_json REQUIRED) +find_package(fmt REQUIRED) +find_package(spdlog REQUIRED) +find_package(asio REQUIRED) +find_package(Protobuf REQUIRED) +find_package(gRPC REQUIRED) +find_package(OpenSSL REQUIRED) +find_package(c-ares REQUIRED) +find_package(ZLIB REQUIRED) find_package(mariadb-connector-c REQUIRED) add_definitions(${spdlog_DEFINITIONS} ${mariadb-connector-c_DEFINITIONS}) +include_directories(${nlohmann_json_INCLUDE_DIRS}) +include_directories(${fmt_INCLUDE_DIRS}) +include_directories(${spdlog_INCLUDE_DIRS}) +include_directories(${asio_INCLUDE_DIRS}) +include_directories(${protobuf_INCLUDE_DIRS}) +include_directories(${absl_INCLUDE_DIRS}) +include_directories(${gRPC_INCLUDE_DIRS}) +include_directories(${ZLIB_INCLUDE_DIRS}) +include_directories(${OpenSSL_INCLUDE_DIRS}) include_directories(${mariadb-connector-c_INCLUDE_DIRS}) +link_directories(${nlohmann_json_LIB_DIRS}) +link_directories(${fmt_LIB_DIRS}) +link_directories(${spdlog_LIB_DIRS}) +link_directories(${protobuf_LIB_DIRS}) +link_directories(${gRPC_LIB_DIRS}) +link_directories(${c-ares_LIB_DIRS}) +link_directories(${OpenSSL_LIB_DIRS}) +link_directories(${ZLIB_LIB_DIRS}) link_directories(${mariadb-connector-c_LIB_DIRS}) +set(PROTOBUF_PREFIX "${protobuf_LIB_DIRS}/..") message(STATUS "${PROTOBUF_PREFIX}/bin/protoc") set(GRPC_PREFIX "${gRPC_LIB_DIRS}/..") @@ -110,12 +144,15 @@ target_link_libraries(berpc ${protobuf_LIBS}) set_target_properties(berpc PROPERTIES COMPILE_FLAGS "-fPIC") # Version. +set(CENTREON_BROKER_MAJOR 21) +set(CENTREON_BROKER_MINOR 10) +set(CENTREON_BROKER_PATCH 0) if (CENTREON_BROKER_PRERELEASE) - set(CENTREON_BROKER_VERSION "${COLLECT_MAJOR}.${COLLECT_MINOR}.${COLLECT_PATCH}-${CENTREON_BROKER_PRERELEASE}") + set(CENTREON_BROKER_VERSION "${CENTREON_BROKER_MAJOR}.${CENTREON_BROKER_MINOR}.${CENTREON_BROKER_PATCH}-${CENTREON_BROKER_PRERELEASE}") else () - set(CENTREON_BROKER_VERSION "${COLLECT_MAJOR}.${COLLECT_MINOR}.${COLLECT_PATCH}") + set(CENTREON_BROKER_VERSION "${CENTREON_BROKER_MAJOR}.${CENTREON_BROKER_MINOR}.${CENTREON_BROKER_PATCH}") endif () -add_definitions(-DCENTREON_BROKER_VERSION=\"${CENTREON_BROKER_VERSION}\" -DCENTREON_BROKER_PATCH=${COLLECT_PATCH}) +add_definitions(-DCENTREON_BROKER_VERSION=\"${CENTREON_BROKER_VERSION}\" -DCENTREON_BROKER_PATCH=${CENTREON_BROKER_PATCH}) configure_file( ${INC_DIR}/version.hh.in ${INC_DIR}/version.hh @@ -157,15 +194,52 @@ endif () # Options. # -set(PREFIX_BROKER_CONF ${CMAKE_INSTALL_FULL_SYSCONFDIR}/centreon-broker) +# Main directory. +if (WITH_PREFIX) + set(CMAKE_INSTALL_PREFIX "${WITH_PREFIX}") +endif () + +# Executable directory. +if (WITH_PREFIX_BIN) + set(PREFIX_BIN "${WITH_PREFIX_BIN}") +else () + set(PREFIX_BIN "${CMAKE_INSTALL_PREFIX}/bin") +endif () -# Modules directories. -set(PREFIX_MODULES "${CMAKE_INSTALL_FULL_DATADIR}/centreon/lib/centreon-broker") -set(PREFIX_CBMOD "${CMAKE_INSTALL_PREFIX}/lib64/nagios") +# Configuration directory. +if (WITH_PREFIX_CONF_BROKER) + set(PREFIX_CONF "${WITH_PREFIX_CONF_BROKER}") +else () + set(PREFIX_CONF "${CMAKE_INSTALL_PREFIX}/etc") +endif () -# var directories. -set(BROKER_VAR_LOG_DIR "${CMAKE_INSTALL_FULL_LOCALSTATEDIR}/log/centreon-broker") -set(BROKER_VAR_LIB_DIR "${CMAKE_INSTALL_FULL_LOCALSTATEDIR}/lib/centreon-broker") +# Library directory. +if (WITH_PREFIX_LIB_BROKER) + set(PREFIX_LIB "${WITH_PREFIX_LIB_BROKER}") +else () + set(PREFIX_LIB "${CMAKE_INSTALL_PREFIX}/lib") +endif () + +# Modules directory. +if (WITH_PREFIX_MODULES) + set(PREFIX_MODULES "${WITH_PREFIX_MODULES}") +else () + set(PREFIX_MODULES "${PREFIX_LIB}/centreon-broker") +endif () + +# var directory. +if (WITH_PREFIX_VAR) + set(PREFIX_VAR "${WITH_PREFIX_VAR}") +else () + set(PREFIX_VAR "${CMAKE_INSTALL_PREFIX}/var") +endif () + +# Development headers directory. +if (WITH_PREFIX_INC) + set(PREFIX_INC "${WITH_PREFIX_INC}") +else () + set(PREFIX_INC "${CMAKE_INSTALL_PREFIX}/include/centreon-broker") +endif () # User. if (WITH_USER_BROKER) @@ -245,14 +319,14 @@ if (WITH_DAEMONS) foreach (DAEMON_NAME IN LISTS WITH_DAEMONS) set(DAEMONS_CONFIGURATION - "${DAEMONS_CONFIGURATION} \"cbd\": [ { \"name\": \"${DAEMON_NAME}\", \"configuration_file\": \"${PREFIX_BROKER_CONF}/${DAEMON_NAME}.json\", \"run\": true, \"reload\": true } ],\n") + "${DAEMONS_CONFIGURATION} \"cbd\": [ { \"name\": \"${DAEMON_NAME}\", \"configuration_file\": \"${PREFIX_CONF}/${DAEMON_NAME}.json\", \"run\": true, \"reload\": true } ],\n") endforeach () configure_file("${PROJECT_SOURCE_DIR}/script/watchdog.json.in" "${PROJECT_SOURCE_DIR}/script/watchdog.json" @ONLY) install(FILES "${PROJECT_SOURCE_DIR}/script/watchdog.json" - DESTINATION "${PREFIX_BROKER_CONF}") + DESTINATION "${PREFIX_CONF}") if (WITH_STARTUP_SCRIPT STREQUAL "sysv") install(PROGRAMS "${PROJECT_SOURCE_DIR}/script/cbd.init" DESTINATION "${STARTUP_DIR}" @@ -272,11 +346,11 @@ if (WITH_CONFIG_FILES) @ONLY) install(FILES "${PROJECT_SOURCE_DIR}/config/poller-module.json" - DESTINATION "${PREFIX_BROKER_CONF}") + DESTINATION "${PREFIX_CONF}") install(FILES "${PROJECT_SOURCE_DIR}/config/central-rrd.json" - DESTINATION "${PREFIX_BROKER_CONF}") + DESTINATION "${PREFIX_CONF}") install(FILES "${PROJECT_SOURCE_DIR}/config/central-broker.json" - DESTINATION "${PREFIX_BROKER_CONF}") + DESTINATION "${PREFIX_CONF}") endif () # Monitoring engine (for testing). @@ -348,9 +422,8 @@ set(LIBROKER_SOURCES ${SRC_DIR}/mapping/entry.cc ${SRC_DIR}/misc/diagnostic.cc ${SRC_DIR}/misc/filesystem.cc + ${SRC_DIR}/misc/global_lock.cc ${SRC_DIR}/misc/misc.cc - ${SRC_DIR}/misc/parse_perfdata.cc - ${SRC_DIR}/misc/perfdata.cc ${SRC_DIR}/misc/processing_speed_computer.cc ${SRC_DIR}/misc/string.cc ${SRC_DIR}/misc/stringifier.cc @@ -359,6 +432,7 @@ set(LIBROKER_SOURCES ${SRC_DIR}/misc/variant.cc ${SRC_DIR}/modules/handle.cc ${SRC_DIR}/multiplexing/engine.cc + ${SRC_DIR}/multiplexing/hooker.cc ${SRC_DIR}/multiplexing/muxer.cc ${SRC_DIR}/multiplexing/publisher.cc ${SRC_DIR}/mysql.cc @@ -433,9 +507,9 @@ set(LIBROKER_SOURCES ${INC_DIR}/mapping/source.hh ${INC_DIR}/misc/diagnostic.hh ${INC_DIR}/misc/filesystem.hh + ${INC_DIR}/misc/global_lock.hh ${INC_DIR}/misc/misc.hh ${INC_DIR}/misc/pair.hh - ${INC_DIR}/misc/perfdata.hh ${INC_DIR}/misc/processing_speed_computer.hh ${INC_DIR}/misc/shared_mutex.hh ${INC_DIR}/misc/string.hh @@ -444,6 +518,7 @@ set(LIBROKER_SOURCES ${INC_DIR}/misc/variant.hh ${INC_DIR}/modules/handle.hh ${INC_DIR}/multiplexing/engine.hh + ${INC_DIR}/multiplexing/hooker.hh ${INC_DIR}/multiplexing/muxer.hh ${INC_DIR}/multiplexing/publisher.hh ${INC_DIR}/multiplexing/subscriber.hh @@ -511,7 +586,6 @@ add_broker_module(STATS ON) add_broker_module(NEB ON) add_broker_module(NOTIFICATION OFF) add_broker_module(RRD ON) -add_broker_module(UNIFIED_SQL ON) add_broker_module(SQL ON) add_broker_module(STORAGE ON) add_broker_module(INFLUXDB ON) @@ -581,11 +655,13 @@ install(CODE " endif () endfunction() - mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_BROKER_CONF}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${CMAKE_INSTALL_PREFIX}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_BIN}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_LIB}\") mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_MODULES}\") - mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CBMOD}\") - mkdir_chown(\"${USER}\" \"${GROUP}\" \"${BROKER_VAR_LOG_DIR}\") - mkdir_chown(\"${USER}\" \"${GROUP}\" \"${BROKER_VAR_LIB_DIR}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_INC}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_VAR}\") if (WITH_STARTUP_SCRIPT STREQUAL \"sysv\") mkdir_chown(\"${USER}\" \"${GROUP}\" \"${STARTUP_DIR}\") endif () @@ -593,13 +669,13 @@ install(CODE " # Install rule. install(TARGETS "${DAEMON}" - RUNTIME DESTINATION "${CMAKE_INSTALL_FULL_SBINDIR}" + RUNTIME DESTINATION "${PREFIX_BIN}" ) # Install header files for development. install(DIRECTORY "${INC_DIR}/../../../" - DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}/centreon-broker" + DESTINATION "${PREFIX_INC}/" COMPONENT "development" FILES_MATCHING PATTERN "*.hh" PATTERN "*.h" ) @@ -666,11 +742,11 @@ message(STATUS " - Module ${MODULE_LIST}") message(STATUS "") message(STATUS " Install") message(STATUS " - Prefix ${CMAKE_INSTALL_PREFIX}") -#message(STATUS " - Binary prefix ${CMAKE_INSTALL_SBINDIR}") -#message(STATUS " - Library prefix ${PREFIX_LIB}") +message(STATUS " - Binary prefix ${PREFIX_BIN}") +message(STATUS " - Library prefix ${PREFIX_LIB}") message(STATUS " - Modules prefix ${PREFIX_MODULES}") -message(STATUS " - Include prefix ${CMAKE_INSTALL_INCLUDEDIR}/centreon-broker") -message(STATUS " - Configuration prefix ${PREFIX_BROKER_CONF}") +message(STATUS " - Include prefix ${PREFIX_INC}") +message(STATUS " - Configuration prefix ${PREFIX_CONF}") if (NOT WITH_STARTUP_SCRIPT STREQUAL "no") message(STATUS " - Startup dir ${STARTUP_DIR}") endif () diff --git a/centreon-broker/bam/CMakeLists.txt b/centreon-broker/bam/CMakeLists.txt index e0c164fab0a..25bd6f748ff 100644 --- a/centreon-broker/bam/CMakeLists.txt +++ b/centreon-broker/bam/CMakeLists.txt @@ -22,6 +22,7 @@ set(SRC_DIR "${PROJECT_SOURCE_DIR}/bam/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/bam/test") include_directories("${INC_DIR}" ${PROJECT_SOURCE_DIR}/core/inc) include_directories("${PROJECT_SOURCE_DIR}/neb/inc") +include_directories("${PROJECT_SOURCE_DIR}/storage/inc") set(INC_DIR "${INC_DIR}/com/centreon/broker/bam") # BAM module. @@ -32,7 +33,10 @@ add_library("${BAM}" SHARED "${SRC_DIR}/availability_builder.cc" "${SRC_DIR}/availability_thread.cc" "${SRC_DIR}/ba.cc" + "${SRC_DIR}/ba_status.cc" "${SRC_DIR}/ba_svc_mapping.cc" + "${SRC_DIR}/ba_event.cc" + "${SRC_DIR}/ba_duration_event.cc" "${SRC_DIR}/bool_aggregate.cc" "${SRC_DIR}/bool_and.cc" "${SRC_DIR}/bool_binary_operator.cc" @@ -61,6 +65,15 @@ add_library("${BAM}" SHARED "${SRC_DIR}/configuration/reader_v2.cc" "${SRC_DIR}/configuration/state.cc" "${SRC_DIR}/connector.cc" + "${SRC_DIR}/dimension_ba_event.cc" + "${SRC_DIR}/dimension_kpi_event.cc" + "${SRC_DIR}/dimension_ba_bv_relation_event.cc" + "${SRC_DIR}/dimension_bv_event.cc" + "${SRC_DIR}/dimension_timeperiod.cc" + "${SRC_DIR}/dimension_timeperiod_exception.cc" + "${SRC_DIR}/dimension_timeperiod_exclusion.cc" + "${SRC_DIR}/dimension_ba_timeperiod_relation.cc" + "${SRC_DIR}/dimension_truncate_table_signal.cc" "${SRC_DIR}/exp_builder.cc" "${SRC_DIR}/exp_parser.cc" "${SRC_DIR}/exp_tokenizer.cc" @@ -68,14 +81,18 @@ add_library("${BAM}" SHARED "${SRC_DIR}/event_cache_visitor.cc" "${SRC_DIR}/hst_svc_mapping.cc" "${SRC_DIR}/impact_values.cc" + "${SRC_DIR}/inherited_downtime.cc" "${SRC_DIR}/kpi.cc" "${SRC_DIR}/kpi_ba.cc" "${SRC_DIR}/kpi_boolexp.cc" + "${SRC_DIR}/kpi_event.cc" "${SRC_DIR}/kpi_service.cc" + "${SRC_DIR}/kpi_status.cc" "${SRC_DIR}/main.cc" "${SRC_DIR}/metric_book.cc" "${SRC_DIR}/metric_listener.cc" "${SRC_DIR}/monitoring_stream.cc" + "${SRC_DIR}/rebuild.cc" "${SRC_DIR}/reporting_stream.cc" "${SRC_DIR}/service_book.cc" "${SRC_DIR}/service_listener.cc" @@ -84,7 +101,10 @@ add_library("${BAM}" SHARED "${INC_DIR}/availability_builder.hh" "${INC_DIR}/availability_thread.hh" "${INC_DIR}/ba.hh" + "${INC_DIR}/ba_status.hh" "${INC_DIR}/ba_svc_mapping.hh" + "${INC_DIR}/ba_event.hh" + "${INC_DIR}/ba_duration_event.hh" "${INC_DIR}/bool_aggregate.hh" "${INC_DIR}/bool_and.hh" "${INC_DIR}/bool_binary_operator.hh" @@ -114,6 +134,15 @@ add_library("${BAM}" SHARED "${INC_DIR}/configuration/reader_v2.hh" "${INC_DIR}/configuration/state.hh" "${INC_DIR}/connector.hh" + "${INC_DIR}/dimension_ba_event.hh" + "${INC_DIR}/dimension_kpi_event.hh" + "${INC_DIR}/dimension_ba_bv_relation_event.hh" + "${INC_DIR}/dimension_bv_event.hh" + "${INC_DIR}/dimension_timeperiod.hh" + "${INC_DIR}/dimension_timeperiod_exception.hh" + "${INC_DIR}/dimension_timeperiod_exclusion.hh" + "${INC_DIR}/dimension_ba_timeperiod_relation.hh" + "${INC_DIR}/dimension_truncate_table_signal.hh" "${INC_DIR}/events.hh" "${INC_DIR}/event_cache_visitor.hh" "${INC_DIR}/exp_builder.hh" @@ -122,30 +151,33 @@ add_library("${BAM}" SHARED "${INC_DIR}/factory.hh" "${INC_DIR}/hst_svc_mapping.hh" "${INC_DIR}/impact_values.hh" + "${INC_DIR}/internal.hh" + "${INC_DIR}/inherited_downtime.hh" "${INC_DIR}/kpi.hh" "${INC_DIR}/kpi_ba.hh" "${INC_DIR}/kpi_boolexp.hh" + "${INC_DIR}/kpi_event.hh" "${INC_DIR}/kpi_service.hh" + "${INC_DIR}/kpi_status.hh" "${INC_DIR}/metric_book.hh" "${INC_DIR}/metric_listener.hh" "${INC_DIR}/monitoring_stream.hh" + "${INC_DIR}/rebuild.hh" "${INC_DIR}/reporting_stream.hh" "${INC_DIR}/service_book.hh" "${INC_DIR}/service_listener.hh" "${INC_DIR}/timeperiod_map.hh" ) -target_link_libraries("${BAM}" bbdo_storage bbdo_bam) set_target_properties("${BAM}" PROPERTIES PREFIX "") # Testing. -if (WITH_TESTING ) - if (WITH_SQL_TESTS) - set(TESTS_SOURCES ${TESTS_SOURCES} ${TEST_DIR}/monitoring_stream.cc) - set(TESTS_SOURCES ${TESTS_SOURCES} ${TEST_DIR}/reporting_stream.cc) - endif (WITH_SQL_TESTS) +if (WITH_SQL_TESTS) + set(TESTS_SOURCES ${TESTS_SOURCES} ${TEST_DIR}/monitoring_stream.cc) + set(TESTS_SOURCES ${TESTS_SOURCES} ${TEST_DIR}/reporting_stream.cc) +endif (WITH_SQL_TESTS) - # Testing. +if (WITH_TESTING ) set( TESTS_SOURCES ${TESTS_SOURCES} diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/ba.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/ba.hh index 81d2e9f3104..f4554201ffc 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/ba.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/ba.hh @@ -24,13 +24,12 @@ #include #include -#include "bbdo/bam/ba_duration_event.hh" -#include "bbdo/bam/ba_event.hh" -#include "bbdo/bam/inherited_downtime.hh" -#include "bbdo/bam/state.hh" +#include "com/centreon/broker/bam/ba_duration_event.hh" +#include "com/centreon/broker/bam/ba_event.hh" #include "com/centreon/broker/bam/computable.hh" #include "com/centreon/broker/bam/configuration/ba.hh" #include "com/centreon/broker/bam/impact_values.hh" +#include "com/centreon/broker/bam/inherited_downtime.hh" #include "com/centreon/broker/bam/service_listener.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/namespace.hh" @@ -57,6 +56,8 @@ class ba : public computable, public service_listener { const bool _generate_virtual_status; public: + typedef impact_values::state state; + struct impact_info { std::shared_ptr kpi_ptr; impact_values hard_impact; @@ -73,8 +74,8 @@ class ba : public computable, public service_listener { void _unapply_impact(kpi* kpi_ptr, impact_info& impact); void _compute_inherited_downtime(io::stream* visitor); - state _computed_soft_state; - state _computed_hard_state; + ba::state _computed_soft_state; + ba::state _computed_hard_state; float _num_soft_critical_childs; float _num_hard_critical_childs; double _acknowledgement_hard; @@ -124,8 +125,8 @@ class ba : public computable, public service_listener { std::string const& get_name() const; std::string get_output() const; std::string get_perfdata() const; - state get_state_hard(); - state get_state_soft(); + ba::state get_state_hard(); + ba::state get_state_soft(); configuration::ba::state_source get_state_source() const; void remove_impact(std::shared_ptr const& impact); void set_level_critical(double level); diff --git a/bbdo/bam/ba_duration_event.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/ba_duration_event.hh similarity index 92% rename from bbdo/bam/ba_duration_event.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/ba_duration_event.hh index 569c4723b64..e14058971e9 100644 --- a/bbdo/bam/ba_duration_event.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/ba_duration_event.hh @@ -19,7 +19,7 @@ #ifndef CCB_BAM_BA_DURATION_EVENT_HH #define CCB_BAM_BA_DURATION_EVENT_HH -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -44,7 +44,8 @@ class ba_duration_event : public io::data { ba_duration_event& operator=(ba_duration_event const& other); bool operator==(ba_duration_event const& other) const; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t ba_id; diff --git a/bbdo/bam/ba_event.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/ba_event.hh similarity index 93% rename from bbdo/bam/ba_event.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/ba_event.hh index 76051a2aa94..291fa03b11f 100644 --- a/bbdo/bam/ba_event.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/ba_event.hh @@ -19,7 +19,7 @@ #ifndef CCB_BAM_BA_EVENT_HH #define CCB_BAM_BA_EVENT_HH -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -43,7 +43,7 @@ class ba_event : public io::data { ba_event& operator=(ba_event const& other); bool operator==(ba_event const& other) const; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t ba_id; double first_level; diff --git a/bbdo/bam/ba_status.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/ba_status.hh similarity index 93% rename from bbdo/bam/ba_status.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/ba_status.hh index bac6613e301..32a994ebd97 100644 --- a/bbdo/bam/ba_status.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/ba_status.hh @@ -19,7 +19,7 @@ #ifndef CCB_BAM_BA_STATUS_HH #define CCB_BAM_BA_STATUS_HH -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -43,7 +43,7 @@ class ba_status : public io::data { ~ba_status(); ba_status& operator=(ba_status const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t ba_id; diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/bool_expression.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/bool_expression.hh index 148176b01c4..f77a0e723b4 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/bool_expression.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/bool_expression.hh @@ -19,7 +19,6 @@ #ifndef CCB_BAM_BOOL_EXPRESSION_HH #define CCB_BAM_BOOL_EXPRESSION_HH -#include "bbdo/bam/state.hh" #include "com/centreon/broker/bam/computable.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/namespace.hh" @@ -40,6 +39,9 @@ class bool_value; * operations and evaluate them to match the kpi interface. */ class bool_expression : public computable { + public: + typedef impact_values::state state; + private: uint32_t _id; std::shared_ptr _expression; @@ -51,7 +53,7 @@ class bool_expression : public computable { ~bool_expression() noexcept = default; bool_expression& operator=(bool_expression const& other) = delete; bool child_has_update(computable* child, io::stream* visitor = NULL); - state get_state() const; + impact_values::state get_state() const; bool state_known() const; void set_expression(std::shared_ptr const& expression); std::shared_ptr get_expression() const; diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/ba.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/ba.hh index 0f93d193b58..b74938c3a20 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/ba.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/ba.hh @@ -22,7 +22,7 @@ #include #include -#include "bbdo/bam/ba_event.hh" +#include "com/centreon/broker/bam/ba_event.hh" #include "com/centreon/broker/namespace.hh" CCB_BEGIN() diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/bool_expression.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/bool_expression.hh index 3569c0d0adf..7f8d81fb899 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/bool_expression.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/bool_expression.hh @@ -21,7 +21,7 @@ #include #include -#include "bbdo/bam/kpi_event.hh" +#include "com/centreon/broker/bam/kpi_event.hh" #include "com/centreon/broker/namespace.hh" CCB_BEGIN() diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/kpi.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/kpi.hh index 355febdf203..13d72b3372c 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/kpi.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/configuration/kpi.hh @@ -19,7 +19,7 @@ #ifndef CCB_BAM_CONFIGURATION_KPI_HH #define CCB_BAM_CONFIGURATION_KPI_HH -#include "bbdo/bam/kpi_event.hh" +#include "com/centreon/broker/bam/kpi_event.hh" #include "com/centreon/broker/namespace.hh" CCB_BEGIN() @@ -35,26 +35,8 @@ namespace configuration { * impact, which service/BA it targets, ... */ class kpi { - uint32_t _id; - int16_t _state_type; - uint32_t _host_id; - uint32_t _service_id; - uint32_t _ba_id; - uint32_t _indicator_ba_id; - uint32_t _meta_id; - uint32_t _boolexp_id; - short _status; - short _last_level; - bool _downtimed; - bool _acknowledged; - bool _ignore_downtime; - bool _ignore_acknowledgement; - double _impact_warning; - double _impact_critical; - double _impact_unknown; - bam::kpi_event _event; - public: + typedef impact_values::state state; kpi(uint32_t id = 0, short state_type = 0, uint32_t host_id = 0, @@ -119,6 +101,26 @@ class kpi { void set_impact_critical(double impact); void set_impact_unknown(double impact); void set_opened_event(bam::kpi_event const& kpi_event); + + private: + uint32_t _id; + short _state_type; + uint32_t _host_id; + uint32_t _service_id; + uint32_t _ba_id; + uint32_t _indicator_ba_id; + uint32_t _meta_id; + uint32_t _boolexp_id; + short _status; + short _last_level; + bool _downtimed; + bool _acknowledged; + bool _ignore_downtime; + bool _ignore_acknowledgement; + double _impact_warning; + double _impact_critical; + double _impact_unknown; + bam::kpi_event _event; }; } // namespace configuration } // namespace bam diff --git a/bbdo/bam/dimension_ba_bv_relation_event.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_ba_bv_relation_event.hh similarity index 95% rename from bbdo/bam/dimension_ba_bv_relation_event.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/dimension_ba_bv_relation_event.hh index 22b8fd8b97c..ef573f58fd8 100644 --- a/bbdo/bam/dimension_ba_bv_relation_event.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_ba_bv_relation_event.hh @@ -19,7 +19,7 @@ #ifndef CCB_BAM_DIMENSION_BA_BV_RELATION_EVENT_HH #define CCB_BAM_DIMENSION_BA_BV_RELATION_EVENT_HH -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -45,7 +45,7 @@ class dimension_ba_bv_relation_event : public io::data { dimension_ba_bv_relation_event const& other); bool operator==(dimension_ba_bv_relation_event const& other) const; constexpr static uint32_t static_type() { - return io::events::data_type::value; } diff --git a/bbdo/bam/dimension_ba_event.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_ba_event.hh similarity index 92% rename from bbdo/bam/dimension_ba_event.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/dimension_ba_event.hh index 440f3995ac0..37733efd861 100644 --- a/bbdo/bam/dimension_ba_event.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_ba_event.hh @@ -21,7 +21,7 @@ #include -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -46,7 +46,8 @@ class dimension_ba_event : public io::data { dimension_ba_event& operator=(dimension_ba_event const& other); bool operator==(dimension_ba_event const& other) const; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t ba_id; diff --git a/bbdo/bam/dimension_ba_timeperiod_relation.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_ba_timeperiod_relation.hh similarity index 94% rename from bbdo/bam/dimension_ba_timeperiod_relation.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/dimension_ba_timeperiod_relation.hh index 54438ff88cd..f17276d9e76 100644 --- a/bbdo/bam/dimension_ba_timeperiod_relation.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_ba_timeperiod_relation.hh @@ -22,7 +22,7 @@ #include #include -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -48,7 +48,7 @@ class dimension_ba_timeperiod_relation : public io::data { bool operator==(dimension_ba_timeperiod_relation const& other) const; constexpr static uint32_t static_type() { return io::events::data_type< - io::bam, bam::de_dimension_ba_timeperiod_relation>::value; + io::events::bam, bam::de_dimension_ba_timeperiod_relation>::value; } uint32_t ba_id; diff --git a/bbdo/bam/dimension_bv_event.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_bv_event.hh similarity index 91% rename from bbdo/bam/dimension_bv_event.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/dimension_bv_event.hh index c83e0cb5c90..9f55271e060 100644 --- a/bbdo/bam/dimension_bv_event.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_bv_event.hh @@ -21,7 +21,7 @@ #include -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -46,7 +46,8 @@ class dimension_bv_event : public io::data { dimension_bv_event& operator=(dimension_bv_event const& other); bool operator==(dimension_bv_event const& other) const; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t bv_id; diff --git a/bbdo/bam/dimension_kpi_event.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_kpi_event.hh similarity index 92% rename from bbdo/bam/dimension_kpi_event.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/dimension_kpi_event.hh index 8ccc0c42a3b..84cfc416760 100644 --- a/bbdo/bam/dimension_kpi_event.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_kpi_event.hh @@ -21,7 +21,7 @@ #include -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -63,7 +63,8 @@ class dimension_kpi_event : public io::data { dimension_kpi_event& operator=(dimension_kpi_event const&) = delete; bool operator==(dimension_kpi_event const& other) const; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/bbdo/bam/dimension_timeperiod.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_timeperiod.hh similarity index 92% rename from bbdo/bam/dimension_timeperiod.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/dimension_timeperiod.hh index 8ceb385a367..50532909b27 100644 --- a/bbdo/bam/dimension_timeperiod.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_timeperiod.hh @@ -21,7 +21,7 @@ #include -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -55,7 +55,8 @@ class dimension_timeperiod : public io::data { dimension_timeperiod& operator=(const dimension_timeperiod&) = delete; bool operator==(const dimension_timeperiod&) const = delete; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/bbdo/bam/dimension_timeperiod_exception.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_timeperiod_exception.hh similarity index 95% rename from bbdo/bam/dimension_timeperiod_exception.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/dimension_timeperiod_exception.hh index 68dca6110a4..913118925bd 100644 --- a/bbdo/bam/dimension_timeperiod_exception.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_timeperiod_exception.hh @@ -21,7 +21,7 @@ #include -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -46,7 +46,7 @@ class dimension_timeperiod_exception : public io::data { dimension_timeperiod_exception& operator=( dimension_timeperiod_exception const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; } diff --git a/bbdo/bam/dimension_timeperiod_exclusion.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_timeperiod_exclusion.hh similarity index 95% rename from bbdo/bam/dimension_timeperiod_exclusion.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/dimension_timeperiod_exclusion.hh index cba125cb8f7..4d1ed3c6ff5 100644 --- a/bbdo/bam/dimension_timeperiod_exclusion.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_timeperiod_exclusion.hh @@ -19,7 +19,7 @@ #ifndef CCB_BAM_DIMENSION_TIMEPERIOD_EXCLUSION_HH #define CCB_BAM_DIMENSION_TIMEPERIOD_EXCLUSION_HH -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -44,7 +44,7 @@ class dimension_timeperiod_exclusion : public io::data { dimension_timeperiod_exclusion& operator=( dimension_timeperiod_exclusion const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; } diff --git a/bbdo/bam/dimension_truncate_table_signal.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_truncate_table_signal.hh similarity index 94% rename from bbdo/bam/dimension_truncate_table_signal.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/dimension_truncate_table_signal.hh index 003504f1e90..72e5337c242 100644 --- a/bbdo/bam/dimension_truncate_table_signal.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/dimension_truncate_table_signal.hh @@ -19,7 +19,7 @@ #ifndef CCB_BAM_DIMENSION_TRUNCATE_TABLE_SIGNAL_HH #define CCB_BAM_DIMENSION_TRUNCATE_TABLE_SIGNAL_HH -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -51,7 +51,7 @@ class dimension_truncate_table_signal : public io::data { bool operator==(const dimension_truncate_table_signal&) const = delete; constexpr static uint32_t static_type() { return io::events::data_type< - io::bam, bam::de_dimension_truncate_table_signal>::value; + io::events::bam, bam::de_dimension_truncate_table_signal>::value; } static mapping::entry const entries[]; diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/impact_values.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/impact_values.hh index b2075e90da4..30964286774 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/impact_values.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/impact_values.hh @@ -19,7 +19,6 @@ #ifndef CCB_BAM_IMPACT_VALUES_HH #define CCB_BAM_IMPACT_VALUES_HH -#include "bbdo/bam/state.hh" #include "com/centreon/broker/namespace.hh" CCB_BEGIN() @@ -34,17 +33,25 @@ namespace bam { * downtime impact, acknowledgement impact. */ class impact_values { + public: + typedef enum { + state_ok, + state_warning, + state_critical, + state_unknown, + } state; + private: double _acknowledgement; double _downtime; double _nominal; - state _state; + impact_values::state _state; public: impact_values(double nominal = 0.0, double acknowledgement = 0.0, double downtime = 0.0, - state state = state_ok); + impact_values::state state = impact_values::state_ok); impact_values(impact_values const& other) = delete; ~impact_values(); impact_values& operator=(impact_values const& other); @@ -52,11 +59,11 @@ class impact_values { double get_acknowledgement() const; double get_downtime() const; double get_nominal() const; - state get_state() const; + impact_values::state get_state() const; void set_acknowledgement(double acknowledgement); void set_downtime(double downtime); void set_nominal(double nominal); - void set_state(state state); + void set_state(impact_values::state state); }; } // namespace bam diff --git a/bbdo/bam/inherited_downtime.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/inherited_downtime.hh similarity index 91% rename from bbdo/bam/inherited_downtime.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/inherited_downtime.hh index 0b4e79fa965..2b230e4f713 100644 --- a/bbdo/bam/inherited_downtime.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/inherited_downtime.hh @@ -19,7 +19,7 @@ #ifndef CCB_BAM_INHERITED_DOWNTIME_HH #define CCB_BAM_INHERITED_DOWNTIME_HH -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -46,7 +46,8 @@ class inherited_downtime : public io::data { ~inherited_downtime(); inherited_downtime& operator=(inherited_downtime const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/internal.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/internal.hh new file mode 100644 index 00000000000..fcc082ac8d5 --- /dev/null +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/internal.hh @@ -0,0 +1,51 @@ +/* +** Copyright 2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_BAM_INTERNAL_HH +#define CCB_BAM_INTERNAL_HH + +#include "com/centreon/broker/namespace.hh" + +CCB_BEGIN() + +namespace bam { +// Data elements. +enum data_element { + de_ba_status = 1, + de_kpi_status, + de_meta_service_status, + de_ba_event, + de_kpi_event, + de_ba_duration_event, + de_dimension_ba_event, + de_dimension_kpi_event, + de_dimension_ba_bv_relation_event, + de_dimension_bv_event, + de_dimension_truncate_table_signal, + de_rebuild, + de_dimension_timeperiod, + de_dimension_ba_timeperiod_relation, + de_dimension_timeperiod_exception, + de_dimension_timeperiod_exclusion, + de_inherited_downtime +}; +} // namespace bam + +CCB_END() + +#endif // !CCB_BAM_INTERNAL_HH diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/kpi.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi.hh index e830e5d1260..340ef899109 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/kpi.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi.hh @@ -22,8 +22,8 @@ #include #include -#include "bbdo/bam/kpi_event.hh" #include "com/centreon/broker/bam/computable.hh" +#include "com/centreon/broker/bam/kpi_event.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/namespace.hh" diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_ba.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_ba.hh index 2ef627d15e4..7318e749795 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_ba.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_ba.hh @@ -1,5 +1,5 @@ /* -** Copyright 2014, 2021 Centreon +** 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. @@ -21,10 +21,8 @@ #include -#include "bbdo/bam/kpi_event.hh" -#include "bbdo/bam/state.hh" -#include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/kpi.hh" +#include "com/centreon/broker/bam/kpi_event.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/namespace.hh" @@ -43,6 +41,9 @@ class computable; * BA. */ class kpi_ba : public kpi { + public: + typedef impact_values::state state; + private: std::shared_ptr _ba; double _impact_critical; @@ -50,12 +51,12 @@ class kpi_ba : public kpi { double _impact_unknown; void _fill_impact(impact_values& impact, - state state, + kpi_ba::state state, double acknowledgement, double downtime); void _open_new_event(io::stream* visitor, int impact, - state ba_state, + kpi_ba::state ba_state, timestamp event_start_time); public: diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_boolexp.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_boolexp.hh index 20c55d9612c..c59813e0e0f 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_boolexp.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_boolexp.hh @@ -1,5 +1,5 @@ /* -** Copyright 2014, 2021 Centreon +** 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. @@ -21,7 +21,6 @@ #include -#include "bbdo/bam/state.hh" #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/namespace.hh" @@ -42,13 +41,18 @@ class computable; * bool_expression) as a KPI for a BA. */ class kpi_boolexp : public kpi { + public: + typedef impact_values::state state; + private: - state _get_state() const; + kpi_boolexp::state _get_state() const; std::shared_ptr _boolexp; double _impact; void _fill_impact(impact_values& impact); - void _open_new_event(io::stream* visitor, int impact, state state); + void _open_new_event(io::stream* visitor, + int impact, + kpi_boolexp::state state); public: kpi_boolexp(uint32_t kpi_id, uint32_t ba_id); diff --git a/bbdo/bam/kpi_event.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_event.hh similarity index 87% rename from bbdo/bam/kpi_event.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/kpi_event.hh index e4f06f93f05..844ae0c6ba6 100644 --- a/bbdo/bam/kpi_event.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_event.hh @@ -1,5 +1,5 @@ /* -** Copyright 2014, 2021 Centreon +** 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. @@ -21,13 +21,14 @@ #include -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/namespace.hh" #include "com/centreon/broker/timestamp.hh" +#include "impact_values.hh" CCB_BEGIN() @@ -39,14 +40,18 @@ namespace bam { * This is the base KPI event that will fill the kpi_events table. */ class kpi_event : public io::data { + private: + void _internal_copy(kpi_event const& other); + public: + typedef impact_values::state state; kpi_event(uint32_t kpi_id, uint32_t ba_id, time_t start_time); kpi_event(const kpi_event& other); ~kpi_event() noexcept = default; kpi_event& operator=(const kpi_event& other); bool operator==(const kpi_event& other) const; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } timestamp end_time; diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_service.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_service.hh index 09791b2aefb..ecd70910c64 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_service.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_service.hh @@ -20,10 +20,8 @@ #define CCB_BAM_KPI_SERVICE_HH #include -#include "bbdo/bam/kpi_event.hh" -#include "bbdo/bam/state.hh" -#include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/kpi.hh" +#include "com/centreon/broker/bam/kpi_event.hh" #include "com/centreon/broker/bam/service_listener.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/namespace.hh" @@ -42,8 +40,11 @@ class kpi_service : public service_listener, public kpi { const uint32_t _host_id; const uint32_t _service_id; + public: + typedef impact_values::state state; + private: - void _fill_impact(impact_values& impact, state state); + void _fill_impact(impact_values& impact, kpi_service::state state); void _internal_copy(kpi_service const& right); void _open_new_event(io::stream* visitor, impact_values const& impacts); @@ -53,15 +54,12 @@ class kpi_service : public service_listener, public kpi { timestamp _last_check; std::string _output; std::string _perfdata; - state _state_hard; - state _state_soft; + kpi_service::state _state_hard; + kpi_service::state _state_soft; short _state_type; public: - kpi_service(uint32_t kpi_id, - uint32_t ba_id, - uint32_t host_id, - uint32_t service_id); + kpi_service(uint32_t kpi_id, uint32_t ba_id, uint32_t host_id, uint32_t service_id); ~kpi_service() noexcept = default; kpi_service(const kpi_service&) = delete; kpi_service& operator=(const kpi_service&) = delete; @@ -71,8 +69,8 @@ class kpi_service : public service_listener, public kpi { double get_impact_unknown() const; double get_impact_warning() const; uint32_t get_service_id() const; - state get_state_hard() const; - state get_state_soft() const; + kpi_service::state get_state_hard() const; + kpi_service::state get_state_soft() const; short get_state_type() const; void impact_hard(impact_values& impact); void impact_soft(impact_values& impact); @@ -89,8 +87,8 @@ class kpi_service : public service_listener, public kpi { void set_impact_critical(double impact); void set_impact_unknown(double impact); void set_impact_warning(double impact); - void set_state_hard(state state); - void set_state_soft(state state); + void set_state_hard(kpi_service::state state); + void set_state_soft(kpi_service::state state); void set_state_type(short type); void visit(io::stream* visitor); virtual void set_initial_event(kpi_event const& e); diff --git a/bbdo/bam/kpi_status.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_status.hh similarity index 94% rename from bbdo/bam/kpi_status.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/kpi_status.hh index 9a82a831388..136ca92bc3a 100644 --- a/bbdo/bam/kpi_status.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/kpi_status.hh @@ -19,7 +19,7 @@ #ifndef CCB_BAM_KPI_STATUS_HH #define CCB_BAM_KPI_STATUS_HH -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -43,7 +43,7 @@ class kpi_status : public io::data { kpi_status(const kpi_status&) = delete; kpi_status& operator=(const kpi_status&) = delete; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t kpi_id; diff --git a/bbdo/bam/rebuild.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/rebuild.hh similarity index 92% rename from bbdo/bam/rebuild.hh rename to centreon-broker/bam/inc/com/centreon/broker/bam/rebuild.hh index 20c24878c95..f1b5c3db9e1 100644 --- a/bbdo/bam/rebuild.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/rebuild.hh @@ -21,7 +21,7 @@ #include -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" #include "com/centreon/broker/io/events.hh" @@ -46,7 +46,7 @@ class rebuild : public io::data { rebuild& operator=(rebuild const&) = delete; bool operator==(rebuild const& other) const; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } std::string bas_to_rebuild; diff --git a/centreon-broker/bam/inc/com/centreon/broker/bam/reporting_stream.hh b/centreon-broker/bam/inc/com/centreon/broker/bam/reporting_stream.hh index b4cf22d12ef..201613f9e65 100644 --- a/centreon-broker/bam/inc/com/centreon/broker/bam/reporting_stream.hh +++ b/centreon-broker/bam/inc/com/centreon/broker/bam/reporting_stream.hh @@ -25,8 +25,8 @@ #include #include -#include "bbdo/bam/ba_event.hh" #include "com/centreon/broker/bam/availability_thread.hh" +#include "com/centreon/broker/bam/ba_event.hh" #include "com/centreon/broker/bam/timeperiod_map.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/namespace.hh" diff --git a/centreon-broker/bam/src/availability_thread.cc b/centreon-broker/bam/src/availability_thread.cc index 59a3ea981ad..b6e2e9ae543 100644 --- a/centreon-broker/bam/src/availability_thread.cc +++ b/centreon-broker/bam/src/availability_thread.cc @@ -22,6 +22,7 @@ #include "com/centreon/broker/database/mysql_error.hh" #include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/misc/global_lock.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; diff --git a/centreon-broker/bam/src/ba.cc b/centreon-broker/bam/src/ba.cc index 76471a0f0f5..d37832c7517 100644 --- a/centreon-broker/bam/src/ba.cc +++ b/centreon-broker/bam/src/ba.cc @@ -21,7 +21,7 @@ #include #include -#include "bbdo/bam/ba_status.hh" +#include "com/centreon/broker/bam/ba_status.hh" #include "com/centreon/broker/bam/impact_values.hh" #include "com/centreon/broker/bam/kpi.hh" #include "com/centreon/broker/log_v2.hh" @@ -72,12 +72,10 @@ ba::ba(uint32_t id, _host_id(host_id), _service_id(service_id), _generate_virtual_status(generate_virtual_status), - _computed_soft_state(source == configuration::ba::state_source_best - ? state_critical - : state_ok), - _computed_hard_state(source == configuration::ba::state_source_best - ? state_critical - : state_ok), + _computed_soft_state(source == configuration::ba::state_source_best ? + ba::state::state_critical : ba::state::state_ok), + _computed_hard_state(source == configuration::ba::state_source_best ? + ba::state::state_critical : ba::state::state_ok), _num_soft_critical_childs{0.f}, _num_hard_critical_childs{0.f}, _acknowledgement_hard(0.0), @@ -299,34 +297,34 @@ std::string ba::get_perfdata() const { * * @return BA hard state. */ -state ba::get_state_hard() { - bam::state state; +ba::state ba::get_state_hard() { + ba::state state; auto update_state = [&](float num_critical, float level_crit, - float level_warning) -> bam::state { + float level_warning) -> ba::state { if (num_critical >= level_crit) - return state_critical; + return ba::state::state_critical; else if (num_critical >= level_warning) - return state_warning; - return state_ok; + return ba::state::state_warning; + return ba::state::state_ok; }; switch (_state_source) { case configuration::ba::state_source_impact: if (!_valid) - state = state_unknown; + state = ba::state::state_unknown; else if (_level_hard <= _level_critical) - state = state_critical; + state = ba::state::state_critical; else if (_level_hard <= _level_warning) - state = state_warning; + state = ba::state::state_warning; else - state = state_ok; + state = ba::state::state_ok; break; case configuration::ba::state_source_best: case configuration::ba::state_source_worst: if (_dt_behaviour == configuration::ba::dt_ignore_kpi && _every_kpi_in_dt(_impacts)) - state = state_ok; + state = impact_values::state_ok; else state = _computed_hard_state; break; @@ -339,8 +337,8 @@ state ba::get_state_hard() { _level_critical, _level_warning); break; default: - state = state_unknown; // unknown _state_source so unknown - // state... + state = ba::state::state_unknown; // unknown _state_source so unknown + // state... } return state; } @@ -350,27 +348,27 @@ state ba::get_state_hard() { * * @return BA soft state. */ -state ba::get_state_soft() { - bam::state state; +ba::state ba::get_state_soft() { + ba::state state; auto update_state = [&](float num_critical, float level_crit, - float level_warning) -> bam::state { + float level_warning) -> ba::state { if (num_critical >= level_crit) - return state_critical; + return ba::state::state_critical; else if (num_critical >= level_warning) - return state_warning; - return state_ok; + return ba::state::state_warning; + return ba::state::state_ok; }; if (_state_source == configuration::ba::state_source_impact) if (!_valid) - state = state_unknown; + state = ba::state::state_unknown; else if (_level_soft <= _level_critical) - state = state_critical; + state = ba::state::state_critical; else if (_level_soft <= _level_warning) - state = state_warning; + state = ba::state::state_warning; else - state = state_ok; + state = ba::state::state_ok; else if (_state_source == configuration::ba::state_source_best || _state_source == configuration::ba::state_source_worst) state = _computed_soft_state; @@ -381,8 +379,8 @@ state ba::get_state_soft() { state = update_state((_num_soft_critical_childs / _impacts.size()) * 100, _level_critical, _level_warning); else - state = state_unknown; // unknown _state_source so unknown - // state...*/ + state = ba::state::state_unknown; // unknown _state_source so unknown + // state...*/ return state; } @@ -680,20 +678,24 @@ void ba::_apply_impact(kpi* kpi_ptr __attribute__((unused)), if (_state_source == configuration::ba::state_source_best) { if (is_state_better(_computed_soft_state, impact.soft_impact.get_state())) - _computed_soft_state = impact.soft_impact.get_state(); + _computed_soft_state = + static_cast(impact.soft_impact.get_state()); if (is_state_better(_computed_hard_state, impact.hard_impact.get_state())) - _computed_hard_state = impact.hard_impact.get_state(); + _computed_hard_state = + static_cast(impact.hard_impact.get_state()); } else if (_state_source == configuration::ba::state_source_worst) { if (is_state_worse(_computed_soft_state, impact.soft_impact.get_state())) - _computed_soft_state = impact.soft_impact.get_state(); + _computed_soft_state = + static_cast(impact.soft_impact.get_state()); if (is_state_worse(_computed_hard_state, impact.hard_impact.get_state())) - _computed_hard_state = impact.hard_impact.get_state(); + _computed_hard_state = + static_cast(impact.hard_impact.get_state()); } else if (_state_source == configuration::ba::state_source_ratio_number || _state_source == configuration::ba::state_source_ratio_percent) { - if (impact.soft_impact.get_state() == state_critical) + if (impact.soft_impact.get_state() == ba::state::state_critical) _num_soft_critical_childs++; - if (impact.hard_impact.get_state() == state_critical) + if (impact.hard_impact.get_state() == ba::state::state_critical) _num_hard_critical_childs++; } } @@ -766,10 +768,10 @@ void ba::_unapply_impact(kpi* kpi_ptr, ba::impact_info& impact) { return; break; case configuration::ba::state_source_best: - _computed_soft_state = _computed_hard_state = state_critical; + _computed_soft_state = _computed_hard_state = ba::state::state_critical; break; case configuration::ba::state_source_worst: - _computed_soft_state = _computed_hard_state = state_ok; + _computed_soft_state = _computed_hard_state = ba::state::state_ok; break; case configuration::ba::state_source_ratio_number: case configuration::ba::state_source_ratio_percent: @@ -827,8 +829,8 @@ void ba::_compute_inherited_downtime(io::stream* visitor) { // Case 1: state not ok, every child in downtime, no actual downtime. // Put the BA in downtime. - bool s_ok{get_state_hard() == state_ok}; - if (!s_ok && every_kpi_in_downtime && !_inherited_downtime) { + bool state_ok{get_state_hard() == ba::state::state_ok}; + if (!state_ok && every_kpi_in_downtime && !_inherited_downtime) { _inherited_downtime.reset(new inherited_downtime); _inherited_downtime->ba_id = _id; _inherited_downtime->in_downtime = true; @@ -840,7 +842,7 @@ void ba::_compute_inherited_downtime(io::stream* visitor) { } // Case 2: state ok or not every kpi in downtime, actual downtime. // Remove the downtime. - else if ((s_ok || !every_kpi_in_downtime) && _inherited_downtime) { + else if ((state_ok || !every_kpi_in_downtime) && _inherited_downtime) { _inherited_downtime->in_downtime = false; _in_downtime = false; diff --git a/bbdo/bam/ba_duration_event.cc b/centreon-broker/bam/src/ba_duration_event.cc similarity index 97% rename from bbdo/bam/ba_duration_event.cc rename to centreon-broker/bam/src/ba_duration_event.cc index b1b47888230..16b30454939 100644 --- a/bbdo/bam/ba_duration_event.cc +++ b/centreon-broker/bam/src/ba_duration_event.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/ba_duration_event.hh" +#include "com/centreon/broker/bam/ba_duration_event.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -123,4 +123,4 @@ static io::data* new_ba_duration_event() { return new ba_duration_event; } io::event_info::event_operations const ba_duration_event::operations = { - &new_ba_duration_event, nullptr, nullptr}; + &new_ba_duration_event}; diff --git a/bbdo/bam/ba_event.cc b/centreon-broker/bam/src/ba_event.cc similarity index 90% rename from bbdo/bam/ba_event.cc rename to centreon-broker/bam/src/ba_event.cc index 77fc8379d9a..c142a15be55 100644 --- a/bbdo/bam/ba_event.cc +++ b/centreon-broker/bam/src/ba_event.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/ba_event.hh" +#include "com/centreon/broker/bam/ba_event.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -64,8 +64,8 @@ ba_event& ba_event::operator=(ba_event const& other) { */ bool ba_event::operator==(ba_event const& other) const { return ba_id == other.ba_id && first_level == other.first_level && - end_time == other.end_time && in_downtime == other.in_downtime && - start_time == other.start_time && status == other.status; + end_time == other.end_time && in_downtime == other.in_downtime && + start_time == other.start_time && status == other.status; } /** @@ -98,5 +98,4 @@ mapping::entry const ba_event::entries[] = { static io::data* new_ba_event() { return new ba_event; } -io::event_info::event_operations const ba_event::operations = { - &new_ba_event, nullptr, nullptr}; +io::event_info::event_operations const ba_event::operations = {&new_ba_event}; diff --git a/bbdo/bam/ba_status.cc b/centreon-broker/bam/src/ba_status.cc similarity index 97% rename from bbdo/bam/ba_status.cc rename to centreon-broker/bam/src/ba_status.cc index 9d587d535cd..264b745216e 100644 --- a/bbdo/bam/ba_status.cc +++ b/centreon-broker/bam/src/ba_status.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/ba_status.hh" +#include "com/centreon/broker/bam/ba_status.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -104,5 +104,4 @@ mapping::entry const ba_status::entries[] = { static io::data* new_ba_status() { return new ba_status; } -io::event_info::event_operations const ba_status::operations = { - &new_ba_status, nullptr, nullptr}; +io::event_info::event_operations const ba_status::operations = {&new_ba_status}; diff --git a/centreon-broker/bam/src/bool_expression.cc b/centreon-broker/bam/src/bool_expression.cc index 4c2e660d929..266c9850576 100644 --- a/centreon-broker/bam/src/bool_expression.cc +++ b/centreon-broker/bam/src/bool_expression.cc @@ -32,6 +32,7 @@ using namespace com::centreon::broker; */ bool_expression::bool_expression() : _id(0), _impact_if(true) {} + /** * Base boolean expression got updated. * @@ -46,8 +47,7 @@ bool bool_expression::child_has_update(computable* child, io::stream* visitor) { // class, as the bool_* classes already cache most of them. if (child == _expression.get()) { // Logging. - log_v2::bam()->debug( - "BAM: boolean expression {} is getting notified of child update", _id); + log_v2::bam()->debug("BAM: boolean expression {} is getting notified of child update", _id); } return true; } @@ -57,8 +57,10 @@ bool bool_expression::child_has_update(computable* child, io::stream* visitor) { * * @return Either OK (0) or CRITICAL (2). */ -state bool_expression::get_state() const { - return (_expression->value_hard() == _impact_if) ? state_critical : state_ok; +impact_values::state bool_expression::get_state() const { + return (_expression->value_hard() == _impact_if) + ? bool_expression::state::state_critical + : bool_expression::state::state_ok; } /** diff --git a/centreon-broker/bam/src/bool_metric.cc b/centreon-broker/bam/src/bool_metric.cc index f2a076b9b54..a2c978bf485 100644 --- a/centreon-broker/bam/src/bool_metric.cc +++ b/centreon-broker/bam/src/bool_metric.cc @@ -18,8 +18,8 @@ #include "com/centreon/broker/bam/bool_metric.hh" -#include "bbdo/storage/metric.hh" #include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/storage/metric.hh" using namespace com::centreon::broker::bam; diff --git a/centreon-broker/bam/src/configuration/applier/kpi.cc b/centreon-broker/bam/src/configuration/applier/kpi.cc index 3bd405f3ef6..bf17f45aff2 100644 --- a/centreon-broker/bam/src/configuration/applier/kpi.cc +++ b/centreon-broker/bam/src/configuration/applier/kpi.cc @@ -17,13 +17,13 @@ */ #include "com/centreon/broker/bam/configuration/applier/kpi.hh" -#include "bbdo/bam/kpi_status.hh" #include "com/centreon/broker/bam/bool_expression.hh" #include "com/centreon/broker/bam/configuration/applier/ba.hh" #include "com/centreon/broker/bam/configuration/applier/bool_expression.hh" #include "com/centreon/broker/bam/kpi_ba.hh" #include "com/centreon/broker/bam/kpi_boolexp.hh" #include "com/centreon/broker/bam/kpi_service.hh" +#include "com/centreon/broker/bam/kpi_status.hh" #include "com/centreon/broker/bam/service_book.hh" #include "com/centreon/broker/exceptions/config.hh" #include "com/centreon/broker/log_v2.hh" @@ -275,7 +275,7 @@ std::shared_ptr applier::kpi::_new_kpi( obj->set_impact_critical(cfg.get_impact_critical()); obj->set_impact_unknown(cfg.get_impact_unknown()); obj->set_impact_warning(cfg.get_impact_warning()); - obj->set_state_hard(static_cast(cfg.get_status())); + obj->set_state_hard(static_cast(cfg.get_status())); obj->set_state_type(cfg.get_state_type()); _book->listen(cfg.get_host_id(), cfg.get_service_id(), obj.get()); my_kpi = std::static_pointer_cast(obj); diff --git a/centreon-broker/bam/src/configuration/kpi.cc b/centreon-broker/bam/src/configuration/kpi.cc index 7774977f284..94a92c5c0fb 100644 --- a/centreon-broker/bam/src/configuration/kpi.cc +++ b/centreon-broker/bam/src/configuration/kpi.cc @@ -129,17 +129,19 @@ kpi& kpi::operator=(kpi const& other) { */ bool kpi::operator==(kpi const& other) const { return _id == other._id && _state_type == other._state_type && - _host_id == other._host_id && _service_id == other._service_id && - _ba_id == other._ba_id && _indicator_ba_id == other._indicator_ba_id && - _meta_id == other._meta_id && _boolexp_id == other._boolexp_id && - _status == other._status && _last_level == other._last_level && - _downtimed == other._downtimed && - _acknowledged == other._acknowledged && - _ignore_downtime == other._ignore_downtime && - _ignore_acknowledgement == other._ignore_acknowledgement && - _impact_warning == other._impact_warning && - _impact_critical == other._impact_critical && - _impact_unknown == other._impact_unknown && _event == other._event; + _host_id == other._host_id && _service_id == other._service_id && + _ba_id == other._ba_id && + _indicator_ba_id == other._indicator_ba_id && + _meta_id == other._meta_id && _boolexp_id == other._boolexp_id && + _status == other._status && _last_level == other._last_level && + _downtimed == other._downtimed && + _acknowledged == other._acknowledged && + _ignore_downtime == other._ignore_downtime && + _ignore_acknowledgement == other._ignore_acknowledgement && + _impact_warning == other._impact_warning && + _impact_critical == other._impact_critical && + _impact_unknown == other._impact_unknown && + _event == other._event; } /** diff --git a/centreon-broker/bam/src/configuration/reader_v2.cc b/centreon-broker/bam/src/configuration/reader_v2.cc index 0ab9e6faf2c..eb0cea6b2f9 100644 --- a/centreon-broker/bam/src/configuration/reader_v2.cc +++ b/centreon-broker/bam/src/configuration/reader_v2.cc @@ -23,15 +23,15 @@ #include #include -#include "bbdo/bam/dimension_ba_bv_relation_event.hh" -#include "bbdo/bam/dimension_ba_event.hh" -#include "bbdo/bam/dimension_ba_timeperiod_relation.hh" -#include "bbdo/bam/dimension_bv_event.hh" -#include "bbdo/bam/dimension_kpi_event.hh" -#include "bbdo/bam/dimension_timeperiod.hh" -#include "bbdo/bam/dimension_truncate_table_signal.hh" #include "com/centreon/broker/bam/configuration/reader_exception.hh" #include "com/centreon/broker/bam/configuration/state.hh" +#include "com/centreon/broker/bam/dimension_ba_bv_relation_event.hh" +#include "com/centreon/broker/bam/dimension_ba_event.hh" +#include "com/centreon/broker/bam/dimension_ba_timeperiod_relation.hh" +#include "com/centreon/broker/bam/dimension_bv_event.hh" +#include "com/centreon/broker/bam/dimension_kpi_event.hh" +#include "com/centreon/broker/bam/dimension_timeperiod.hh" +#include "com/centreon/broker/bam/dimension_truncate_table_signal.hh" #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/log_v2.hh" diff --git a/bbdo/bam/dimension_ba_bv_relation_event.cc b/centreon-broker/bam/src/dimension_ba_bv_relation_event.cc similarity index 89% rename from bbdo/bam/dimension_ba_bv_relation_event.cc rename to centreon-broker/bam/src/dimension_ba_bv_relation_event.cc index 48e9b7eaccc..02aa063a3ec 100644 --- a/bbdo/bam/dimension_ba_bv_relation_event.cc +++ b/centreon-broker/bam/src/dimension_ba_bv_relation_event.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/dimension_ba_bv_relation_event.hh" +#include "com/centreon/broker/bam/dimension_ba_bv_relation_event.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -84,6 +84,12 @@ void dimension_ba_bv_relation_event::_internal_copy( bv_id = other.bv_id; } +/************************************** + * * + * Static Objects * + * * + **************************************/ + // Mapping. mapping::entry const dimension_ba_bv_relation_event::entries[] = { mapping::entry(&bam::dimension_ba_bv_relation_event::ba_id, @@ -100,4 +106,4 @@ static io::data* new_dimension_ba_bv_relation_event() { } io::event_info::event_operations const dimension_ba_bv_relation_event::operations = { - &new_dimension_ba_bv_relation_event, nullptr, nullptr}; + &new_dimension_ba_bv_relation_event}; diff --git a/bbdo/bam/dimension_ba_event.cc b/centreon-broker/bam/src/dimension_ba_event.cc similarity index 97% rename from bbdo/bam/dimension_ba_event.cc rename to centreon-broker/bam/src/dimension_ba_event.cc index 7324c0afc22..a8def97ae1d 100644 --- a/bbdo/bam/dimension_ba_event.cc +++ b/centreon-broker/bam/src/dimension_ba_event.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/dimension_ba_event.hh" +#include "com/centreon/broker/bam/dimension_ba_event.hh" #include "com/centreon/broker/database/table_max_size.hh" @@ -125,4 +125,4 @@ static io::data* new_dimension_ba_event() { return new dimension_ba_event; } io::event_info::event_operations const dimension_ba_event::operations = { - &new_dimension_ba_event, nullptr, nullptr}; + &new_dimension_ba_event}; diff --git a/bbdo/bam/dimension_ba_timeperiod_relation.cc b/centreon-broker/bam/src/dimension_ba_timeperiod_relation.cc similarity index 96% rename from bbdo/bam/dimension_ba_timeperiod_relation.cc rename to centreon-broker/bam/src/dimension_ba_timeperiod_relation.cc index 82f19ab6dfe..0873b352e04 100644 --- a/bbdo/bam/dimension_ba_timeperiod_relation.cc +++ b/centreon-broker/bam/src/dimension_ba_timeperiod_relation.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/dimension_ba_timeperiod_relation.hh" +#include "com/centreon/broker/bam/dimension_ba_timeperiod_relation.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -109,7 +109,6 @@ mapping::entry const dimension_ba_timeperiod_relation::entries[] = { static io::data* new_dimension_ba_timeperiod_relation() { return new dimension_ba_timeperiod_relation; } - io::event_info::event_operations const dimension_ba_timeperiod_relation::operations = { - &new_dimension_ba_timeperiod_relation, nullptr, nullptr}; + &new_dimension_ba_timeperiod_relation}; diff --git a/bbdo/bam/dimension_bv_event.cc b/centreon-broker/bam/src/dimension_bv_event.cc similarity index 97% rename from bbdo/bam/dimension_bv_event.cc rename to centreon-broker/bam/src/dimension_bv_event.cc index 300d85d48a9..4e60553d2c0 100644 --- a/bbdo/bam/dimension_bv_event.cc +++ b/centreon-broker/bam/src/dimension_bv_event.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/dimension_bv_event.hh" +#include "com/centreon/broker/bam/dimension_bv_event.hh" #include "com/centreon/broker/database/table_max_size.hh" @@ -109,4 +109,4 @@ static io::data* new_dimension_bv_event() { return new dimension_bv_event; } io::event_info::event_operations const dimension_bv_event::operations = { - &new_dimension_bv_event, nullptr, nullptr}; + &new_dimension_bv_event}; diff --git a/bbdo/bam/dimension_kpi_event.cc b/centreon-broker/bam/src/dimension_kpi_event.cc similarity index 98% rename from bbdo/bam/dimension_kpi_event.cc rename to centreon-broker/bam/src/dimension_kpi_event.cc index b91304f44a0..32eb23d5929 100644 --- a/bbdo/bam/dimension_kpi_event.cc +++ b/centreon-broker/bam/src/dimension_kpi_event.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/dimension_kpi_event.hh" +#include "com/centreon/broker/bam/dimension_kpi_event.hh" #include "com/centreon/broker/database/table_max_size.hh" @@ -145,4 +145,4 @@ static io::data* new_dimension_kpi_event() { return new dimension_kpi_event(0); } io::event_info::event_operations const dimension_kpi_event::operations = { - &new_dimension_kpi_event, nullptr, nullptr}; + &new_dimension_kpi_event}; diff --git a/bbdo/bam/dimension_timeperiod.cc b/centreon-broker/bam/src/dimension_timeperiod.cc similarity index 97% rename from bbdo/bam/dimension_timeperiod.cc rename to centreon-broker/bam/src/dimension_timeperiod.cc index bd67ad38630..655ac09b9de 100644 --- a/bbdo/bam/dimension_timeperiod.cc +++ b/centreon-broker/bam/src/dimension_timeperiod.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/dimension_timeperiod.hh" +#include "com/centreon/broker/bam/dimension_timeperiod.hh" #include "com/centreon/broker/database/table_max_size.hh" @@ -73,4 +73,4 @@ static io::data* new_dimension_timeperiod() { return new dimension_timeperiod(0, ""); } io::event_info::event_operations const dimension_timeperiod::operations = { - &new_dimension_timeperiod, nullptr, nullptr}; + &new_dimension_timeperiod}; diff --git a/bbdo/bam/dimension_timeperiod_exception.cc b/centreon-broker/bam/src/dimension_timeperiod_exception.cc similarity index 96% rename from bbdo/bam/dimension_timeperiod_exception.cc rename to centreon-broker/bam/src/dimension_timeperiod_exception.cc index 37d1a0d0a53..bc89f237375 100644 --- a/bbdo/bam/dimension_timeperiod_exception.cc +++ b/centreon-broker/bam/src/dimension_timeperiod_exception.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/dimension_timeperiod_exception.hh" +#include "com/centreon/broker/bam/dimension_timeperiod_exception.hh" #include "com/centreon/broker/database/table_max_size.hh" @@ -101,4 +101,4 @@ static io::data* new_dimension_timeperiod_exception() { } io::event_info::event_operations const dimension_timeperiod_exception::operations = { - &new_dimension_timeperiod_exception, nullptr, nullptr}; + &new_dimension_timeperiod_exception}; diff --git a/bbdo/bam/dimension_timeperiod_exclusion.cc b/centreon-broker/bam/src/dimension_timeperiod_exclusion.cc similarity index 95% rename from bbdo/bam/dimension_timeperiod_exclusion.cc rename to centreon-broker/bam/src/dimension_timeperiod_exclusion.cc index 6853b02ba0e..b44e39941aa 100644 --- a/bbdo/bam/dimension_timeperiod_exclusion.cc +++ b/centreon-broker/bam/src/dimension_timeperiod_exclusion.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/dimension_timeperiod_exclusion.hh" +#include "com/centreon/broker/bam/dimension_timeperiod_exclusion.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -94,4 +94,4 @@ static io::data* new_dimension_timeperiod_exclusion() { } io::event_info::event_operations const dimension_timeperiod_exclusion::operations = { - &new_dimension_timeperiod_exclusion, nullptr, nullptr}; + &new_dimension_timeperiod_exclusion}; diff --git a/bbdo/bam/dimension_truncate_table_signal.cc b/centreon-broker/bam/src/dimension_truncate_table_signal.cc similarity index 91% rename from bbdo/bam/dimension_truncate_table_signal.cc rename to centreon-broker/bam/src/dimension_truncate_table_signal.cc index 4f79afe6a57..6306e0e951e 100644 --- a/bbdo/bam/dimension_truncate_table_signal.cc +++ b/centreon-broker/bam/src/dimension_truncate_table_signal.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/dimension_truncate_table_signal.hh" +#include "com/centreon/broker/bam/dimension_truncate_table_signal.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -40,4 +40,4 @@ static io::data* new_dimension_truncate_table_signal() { } io::event_info::event_operations const dimension_truncate_table_signal::operations = { - &new_dimension_truncate_table_signal, nullptr, nullptr}; + &new_dimension_truncate_table_signal}; diff --git a/centreon-broker/bam/src/event_cache_visitor.cc b/centreon-broker/bam/src/event_cache_visitor.cc index 6242ad6bc4f..c91c6c1707c 100644 --- a/centreon-broker/bam/src/event_cache_visitor.cc +++ b/centreon-broker/bam/src/event_cache_visitor.cc @@ -18,7 +18,7 @@ #include "com/centreon/broker/bam/event_cache_visitor.hh" -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/internal.hh" #include "com/centreon/broker/io/events.hh" using namespace com::centreon::broker; @@ -72,10 +72,11 @@ int event_cache_visitor::write(std::shared_ptr const& d) { if (!validate(d, get_name())) return 1; - if (d->type() == io::events::data_type::value) + if (d->type() == + io::events::data_type::value) _ba_events.push_back(d); else if (d->type() == - io::events::data_type::value) + io::events::data_type::value) _kpi_events.push_back(d); else _others.push_back(d); diff --git a/centreon-broker/bam/src/exp_parser.cc b/centreon-broker/bam/src/exp_parser.cc index 319b8577092..d3bfe652a95 100644 --- a/centreon-broker/bam/src/exp_parser.cc +++ b/centreon-broker/bam/src/exp_parser.cc @@ -23,8 +23,8 @@ #include #include "com/centreon/broker/bam/exp_tokenizer.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/exceptions/msg_fmt.hh" +#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; diff --git a/centreon-broker/bam/src/impact_values.cc b/centreon-broker/bam/src/impact_values.cc index 845ab986569..f6fa268014c 100644 --- a/centreon-broker/bam/src/impact_values.cc +++ b/centreon-broker/bam/src/impact_values.cc @@ -31,11 +31,11 @@ using namespace com::centreon::broker::bam; impact_values::impact_values(double nominal, double acknowledgement, double downtime, - state state) + impact_values::state state) : _acknowledgement(acknowledgement), _downtime(downtime), _nominal(nominal), - _state{state} {} + _state(state) {} /** * Destructor. @@ -106,8 +106,8 @@ double impact_values::get_nominal() const { * * @return State impact. */ -state impact_values::get_state() const { - return _state; +impact_values::state impact_values::get_state() const { + return (_state); } /** @@ -145,6 +145,7 @@ void impact_values::set_nominal(double nominal) { * * @param[in] state State impact. */ -void impact_values::set_state(state state) { +void impact_values::set_state(impact_values::state state) { _state = state; -} + return; +} \ No newline at end of file diff --git a/bbdo/bam/inherited_downtime.cc b/centreon-broker/bam/src/inherited_downtime.cc similarity index 88% rename from bbdo/bam/inherited_downtime.cc rename to centreon-broker/bam/src/inherited_downtime.cc index 3aa997c1811..06a752a7749 100644 --- a/bbdo/bam/inherited_downtime.cc +++ b/centreon-broker/bam/src/inherited_downtime.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/inherited_downtime.hh" +#include "com/centreon/broker/bam/inherited_downtime.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -70,6 +70,12 @@ void inherited_downtime::_internal_copy(inherited_downtime const& other) { in_downtime = other.in_downtime; } +/************************************** + * * + * Static Objects * + * * + **************************************/ + // Mapping. mapping::entry const inherited_downtime::entries[] = { mapping::entry(&bam::inherited_downtime::ba_id, @@ -83,4 +89,4 @@ static io::data* new_inherited_downtime() { return new inherited_downtime; } io::event_info::event_operations const inherited_downtime::operations = { - &new_inherited_downtime, nullptr, nullptr}; + &new_inherited_downtime}; diff --git a/centreon-broker/bam/src/kpi_ba.cc b/centreon-broker/bam/src/kpi_ba.cc index 5f2198d4cdb..b59c08d95c0 100644 --- a/centreon-broker/bam/src/kpi_ba.cc +++ b/centreon-broker/bam/src/kpi_ba.cc @@ -18,8 +18,8 @@ #include "com/centreon/broker/bam/kpi_ba.hh" -#include "bbdo/bam/kpi_status.hh" #include "com/centreon/broker/bam/ba.hh" +#include "com/centreon/broker/bam/kpi_status.hh" #include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker; @@ -157,8 +157,8 @@ void kpi_ba::visit(io::stream* visitor) { { // BA event state. ba_event* bae(_ba->get_ba_event()); - bam::state ba_state = - bae ? static_cast(bae->status) : state_ok; + kpi_ba::state ba_state(bae ? static_cast(bae->status) + : kpi_ba::state::state_ok); timestamp last_ba_update(bae ? bae->start_time : timestamp(time(nullptr))); @@ -208,19 +208,19 @@ void kpi_ba::visit(io::stream* visitor) { * @param[in] downtime Downtime impact of the BA. */ void kpi_ba::_fill_impact(impact_values& impact, - state state, + kpi_ba::state state, double acknowledgement, double downtime) { // Get nominal impact from state. double nominal; switch (state) { - case state_ok: + case 0: nominal = 0.0; break; - case state_warning: + case 1: nominal = _impact_warning; break; - case state_critical: + case 2: nominal = _impact_critical; break; default: @@ -256,7 +256,7 @@ void kpi_ba::_fill_impact(impact_values& impact, */ void kpi_ba::_open_new_event(io::stream* visitor, int impact, - state ba_state, + kpi_ba::state ba_state, timestamp event_start_time) { _event = std::make_shared(_id, _ba_id, event_start_time); _event->impact_level = impact; diff --git a/centreon-broker/bam/src/kpi_boolexp.cc b/centreon-broker/bam/src/kpi_boolexp.cc index f988d7b2da9..07c555cc531 100644 --- a/centreon-broker/bam/src/kpi_boolexp.cc +++ b/centreon-broker/bam/src/kpi_boolexp.cc @@ -17,9 +17,9 @@ */ #include "com/centreon/broker/bam/kpi_boolexp.hh" -#include "bbdo/bam/kpi_status.hh" #include "com/centreon/broker/bam/bool_expression.hh" #include "com/centreon/broker/bam/impact_values.hh" +#include "com/centreon/broker/bam/kpi_status.hh" #include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker; @@ -131,7 +131,7 @@ void kpi_boolexp::visit(io::stream* visitor) { // Get information (HARD and SOFT values are the same). impact_values values; impact_hard(values); - state state = _get_state(); + kpi_boolexp::state state(_get_state()); // Generate BI events. { @@ -173,9 +173,9 @@ void kpi_boolexp::visit(io::stream* visitor) { */ void kpi_boolexp::_fill_impact(impact_values& impact) { // Get nominal impact from state. - bam::state state = _get_state(); + kpi_boolexp::state state(_get_state()); double nominal; - if (state_ok == state) + if (0 == state) nominal = 0.0; else nominal = _impact; @@ -194,7 +194,7 @@ void kpi_boolexp::_fill_impact(impact_values& impact) { */ void kpi_boolexp::_open_new_event(io::stream* visitor, int impact, - state state) { + kpi_boolexp::state state) { _event = std::make_shared(_id, _ba_id, ::time(nullptr)); _event->impact_level = impact; _event->in_downtime = false; @@ -215,12 +215,12 @@ void kpi_boolexp::_open_new_event(io::stream* visitor, * * @return The current state of the boolexp. */ -state kpi_boolexp::_get_state() const { +kpi_boolexp::state kpi_boolexp::_get_state() const { if (_boolexp->state_known()) return _boolexp->get_state(); else { if (_event) - return static_cast(_event->status); + return static_cast(_event->status); else return _boolexp->get_state(); } diff --git a/bbdo/bam/kpi_event.cc b/centreon-broker/bam/src/kpi_event.cc similarity index 96% rename from bbdo/bam/kpi_event.cc rename to centreon-broker/bam/src/kpi_event.cc index 9b9258ef46b..e6227d1e89c 100644 --- a/bbdo/bam/kpi_event.cc +++ b/centreon-broker/bam/src/kpi_event.cc @@ -16,9 +16,8 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/kpi_event.hh" +#include "com/centreon/broker/bam/kpi_event.hh" -#include "bbdo/bam/state.hh" #include "com/centreon/broker/database/table_max_size.hh" using namespace com::centreon::broker; @@ -33,7 +32,7 @@ kpi_event::kpi_event(uint32_t kpi_id, uint32_t ba_id, time_t start_time) impact_level(0), in_downtime(false), start_time(start_time), - status(state_unknown), + status(kpi_event::state::state_unknown), ba_id(ba_id) {} /** @@ -116,5 +115,4 @@ static io::data* new_kpi_event() { return new kpi_event(0, 0, 0); } -io::event_info::event_operations const kpi_event::operations = { - &new_kpi_event, nullptr, nullptr}; +io::event_info::event_operations const kpi_event::operations = {&new_kpi_event}; diff --git a/centreon-broker/bam/src/kpi_service.cc b/centreon-broker/bam/src/kpi_service.cc index 9627afcc932..983a698fb46 100644 --- a/centreon-broker/bam/src/kpi_service.cc +++ b/centreon-broker/bam/src/kpi_service.cc @@ -21,8 +21,8 @@ #include #include -#include "bbdo/bam/kpi_status.hh" #include "com/centreon/broker/bam/impact_values.hh" +#include "com/centreon/broker/bam/kpi_status.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/neb/acknowledgement.hh" #include "com/centreon/broker/neb/downtime.hh" @@ -47,8 +47,8 @@ kpi_service::kpi_service(uint32_t kpi_id, _downtimed(false), _impacts{0.0}, _last_check(0), - _state_hard{state_ok}, - _state_soft{state_ok}, + _state_hard(kpi_service::state::state_ok), + _state_soft(kpi_service::state::state_ok), _state_type(0) { assert(_host_id); } @@ -117,7 +117,7 @@ uint32_t kpi_service::get_service_id() const { * * @return Hard state of the service. */ -state kpi_service::get_state_hard() const { +kpi_service::state kpi_service::get_state_hard() const { return _state_hard; } @@ -126,7 +126,7 @@ state kpi_service::get_state_hard() const { * * @return Soft state of the service. */ -state kpi_service::get_state_soft() const { +kpi_service::state kpi_service::get_state_soft() const { return _state_soft; } @@ -207,8 +207,8 @@ void kpi_service::service_update( } _output = status->output; _perfdata = status->perf_data; - _state_hard = static_cast(status->last_hard_state); - _state_soft = static_cast(status->current_state); + _state_hard = static_cast(status->last_hard_state); + _state_soft = static_cast(status->current_state); _state_type = status->state_type; // Generate status event. @@ -328,7 +328,7 @@ void kpi_service::set_impact_warning(double impact) { * * @param[in] state Service hard state. */ -void kpi_service::set_state_hard(state state) { +void kpi_service::set_state_hard(kpi_service::state state) { _state_hard = state; } @@ -337,7 +337,7 @@ void kpi_service::set_state_hard(state state) { * * @param[in] state Service soft state. */ -void kpi_service::set_state_soft(state state) { +void kpi_service::set_state_soft(kpi_service::state state) { _state_soft = state; } @@ -414,7 +414,8 @@ void kpi_service::visit(io::stream* visitor) { * @param[out] impact Impacts of the state. * @param[in] state Service state. */ -void kpi_service::_fill_impact(impact_values& impact, state state) { +void kpi_service::_fill_impact(impact_values& impact, + kpi_service::state state) { if (state < 0 || static_cast(state) >= _impacts.size()) throw msg_fmt("BAM: could not get impact introduced by state {}", state); double nominal{_impacts[state]}; diff --git a/bbdo/bam/kpi_status.cc b/centreon-broker/bam/src/kpi_status.cc similarity index 97% rename from bbdo/bam/kpi_status.cc rename to centreon-broker/bam/src/kpi_status.cc index 3771469e1e8..e7854634d33 100644 --- a/bbdo/bam/kpi_status.cc +++ b/centreon-broker/bam/src/kpi_status.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/kpi_status.hh" +#include "com/centreon/broker/bam/kpi_status.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -68,4 +68,4 @@ static io::data* new_kpi_status() { return new kpi_status(0); } io::event_info::event_operations const kpi_status::operations = { - &new_kpi_status, nullptr, nullptr}; + &new_kpi_status}; diff --git a/centreon-broker/bam/src/main.cc b/centreon-broker/bam/src/main.cc index e9f96860647..19a781b51ae 100644 --- a/centreon-broker/bam/src/main.cc +++ b/centreon-broker/bam/src/main.cc @@ -15,28 +15,24 @@ ** ** For more information : contact@centreon.com */ -#include "bbdo/bam/ba_duration_event.hh" -#include "bbdo/bam/ba_event.hh" -#include "bbdo/bam/ba_status.hh" -#include "bbdo/bam/dimension_ba_bv_relation_event.hh" -#include "bbdo/bam/dimension_ba_event.hh" -#include "bbdo/bam/dimension_ba_timeperiod_relation.hh" -#include "bbdo/bam/dimension_bv_event.hh" -#include "bbdo/bam/dimension_kpi_event.hh" -#include "bbdo/bam/dimension_timeperiod.hh" -#include "bbdo/bam/dimension_timeperiod_exception.hh" -#include "bbdo/bam/dimension_timeperiod_exclusion.hh" -#include "bbdo/bam/dimension_truncate_table_signal.hh" -#include "bbdo/bam/inherited_downtime.hh" -#include "bbdo/bam/kpi_event.hh" -#include "bbdo/bam/kpi_status.hh" -#include "bbdo/bam/rebuild.hh" -#include "bbdo/events.hh" -#include "bbdo/storage/index_mapping.hh" -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/metric_mapping.hh" -#include "bbdo/storage/status.hh" +#include "com/centreon/broker/bam/ba_duration_event.hh" +#include "com/centreon/broker/bam/ba_event.hh" +#include "com/centreon/broker/bam/ba_status.hh" +#include "com/centreon/broker/bam/dimension_ba_bv_relation_event.hh" +#include "com/centreon/broker/bam/dimension_ba_event.hh" +#include "com/centreon/broker/bam/dimension_ba_timeperiod_relation.hh" +#include "com/centreon/broker/bam/dimension_bv_event.hh" +#include "com/centreon/broker/bam/dimension_kpi_event.hh" +#include "com/centreon/broker/bam/dimension_timeperiod.hh" +#include "com/centreon/broker/bam/dimension_timeperiod_exception.hh" +#include "com/centreon/broker/bam/dimension_timeperiod_exclusion.hh" +#include "com/centreon/broker/bam/dimension_truncate_table_signal.hh" #include "com/centreon/broker/bam/factory.hh" +#include "com/centreon/broker/bam/inherited_downtime.hh" +#include "com/centreon/broker/bam/internal.hh" +#include "com/centreon/broker/bam/kpi_event.hh" +#include "com/centreon/broker/bam/kpi_status.hh" +#include "com/centreon/broker/bam/rebuild.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" @@ -53,7 +49,7 @@ char const* bam_module("bam"); template void register_bam_event(io::events& e, bam::data_element de, const char* name) { - e.register_event(make_type(io::bam, de), name, &T::operations, T::entries); + e.register_event(io::events::bam, de, name, &T::operations, T::entries); } extern "C" { @@ -68,7 +64,7 @@ const char* broker_module_version = CENTREON_BROKER_VERSION; * @return An array of const char* */ const char* const* broker_module_parents() { - constexpr static const char* retval[]{"10-neb.so", nullptr}; + constexpr static const char* retval[]{"10-neb.so", "20-storage.so", nullptr}; return retval; } @@ -78,9 +74,10 @@ const char* const* broker_module_parents() { void broker_module_deinit() { // Decrement instance number. if (!--instances) { + // Deregister storage layer. io::protocols::instance().unreg(bam_module); // Deregister bam events. - io::events::instance().unregister_category(io::bam); + io::events::instance().unregister_category(io::events::bam); } } @@ -98,25 +95,26 @@ void broker_module_init(void const* arg) { log_v2::bam()->info("BAM: module for Centreon Broker {} ", CENTREON_BROKER_VERSION); + // Register storage layer. io::protocols::instance().reg(bam_module, std::make_shared(), 1, 7); io::events& e(io::events::instance()); - // Register events. - { - e.register_event(make_type(io::storage, storage::de_metric), "metric", - &storage::metric::operations, storage::metric::entries, - "rt_metrics"); - e.register_event(make_type(io::storage, storage::de_status), "status", - &storage::status::operations, storage::status::entries); - e.register_event(make_type(io::storage, storage::de_index_mapping), - "index_mapping", &storage::index_mapping::operations, - storage::index_mapping::entries); - e.register_event(make_type(io::storage, storage::de_metric_mapping), - "metric_mapping", &storage::metric_mapping::operations, - storage::metric_mapping::entries); + // Register category. + int bam_category(e.register_category("bam", io::events::bam)); + if (bam_category != io::events::bam) { + e.unregister_category(bam_category); + --instances; + throw msg_fmt( + "bam: category {}" + " is already registered whereas it should be " + "reserved for the bam module", + io::events::bam); + } + // Register bam events. + { register_bam_event(e, bam::de_ba_status, "ba_status"); register_bam_event(e, bam::de_kpi_status, "kpi_status"); register_bam_event(e, bam::de_ba_event, "ba_event"); diff --git a/centreon-broker/bam/src/metric_book.cc b/centreon-broker/bam/src/metric_book.cc index 44bf9142301..5baffa88ffc 100644 --- a/centreon-broker/bam/src/metric_book.cc +++ b/centreon-broker/bam/src/metric_book.cc @@ -18,8 +18,8 @@ #include "com/centreon/broker/bam/metric_book.hh" -#include "bbdo/storage/metric.hh" #include "com/centreon/broker/bam/metric_listener.hh" +#include "com/centreon/broker/storage/metric.hh" using namespace com::centreon::broker::bam; diff --git a/centreon-broker/bam/src/monitoring_stream.cc b/centreon-broker/bam/src/monitoring_stream.cc index 5cf65dc71da..9f62da6bf6f 100644 --- a/centreon-broker/bam/src/monitoring_stream.cc +++ b/centreon-broker/bam/src/monitoring_stream.cc @@ -23,24 +23,26 @@ #include #include -#include "bbdo/bam/ba_status.hh" -#include "bbdo/bam/kpi_status.hh" -#include "bbdo/bam/rebuild.hh" -#include "bbdo/events.hh" -#include "bbdo/storage/metric.hh" +#include "com/centreon/broker/bam/ba_status.hh" #include "com/centreon/broker/bam/configuration/reader_v2.hh" #include "com/centreon/broker/bam/configuration/state.hh" #include "com/centreon/broker/bam/event_cache_visitor.hh" +#include "com/centreon/broker/bam/internal.hh" +#include "com/centreon/broker/bam/kpi_status.hh" +#include "com/centreon/broker/bam/rebuild.hh" #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/misc/global_lock.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/acknowledgement.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/broker/neb/service.hh" #include "com/centreon/broker/neb/service_status.hh" +#include "com/centreon/broker/storage/internal.hh" +#include "com/centreon/broker/storage/metric.hh" #include "com/centreon/broker/timestamp.hh" #include "com/centreon/exceptions/msg_fmt.hh" @@ -198,8 +200,7 @@ int monitoring_stream::write(std::shared_ptr const& data) { std::shared_ptr ss( std::static_pointer_cast(data)); log_v2::bam()->trace( - "BAM: processing service status (host: {}, service: {}, hard state " - "{}, " + "BAM: processing service status (host: {}, service: {}, hard state {}, " "current state {})", ss->host_id, ss->service_id, ss->last_hard_state, ss->current_state); multiplexing::publisher pblshr; diff --git a/bbdo/bam/rebuild.cc b/centreon-broker/bam/src/rebuild.cc similarity index 93% rename from bbdo/bam/rebuild.cc rename to centreon-broker/bam/src/rebuild.cc index 1ba21101857..6b3e0f56820 100644 --- a/bbdo/bam/rebuild.cc +++ b/centreon-broker/bam/src/rebuild.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/bam/rebuild.hh" +#include "com/centreon/broker/bam/rebuild.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam; @@ -63,5 +63,4 @@ mapping::entry const rebuild::entries[] = { static io::data* new_rebuild() { return new rebuild; } -io::event_info::event_operations const rebuild::operations = {&new_rebuild, - nullptr, nullptr}; +io::event_info::event_operations const rebuild::operations = {&new_rebuild}; diff --git a/centreon-broker/bam/src/reporting_stream.cc b/centreon-broker/bam/src/reporting_stream.cc index c0e828ccb72..d2722e0a31d 100644 --- a/centreon-broker/bam/src/reporting_stream.cc +++ b/centreon-broker/bam/src/reporting_stream.cc @@ -20,24 +20,25 @@ #include -#include "bbdo/bam/ba_duration_event.hh" -#include "bbdo/bam/ba_event.hh" -#include "bbdo/bam/dimension_ba_bv_relation_event.hh" -#include "bbdo/bam/dimension_ba_event.hh" -#include "bbdo/bam/dimension_ba_timeperiod_relation.hh" -#include "bbdo/bam/dimension_bv_event.hh" -#include "bbdo/bam/dimension_kpi_event.hh" -#include "bbdo/bam/dimension_timeperiod.hh" -#include "bbdo/bam/dimension_timeperiod_exception.hh" -#include "bbdo/bam/dimension_timeperiod_exclusion.hh" -#include "bbdo/bam/dimension_truncate_table_signal.hh" -#include "bbdo/bam/kpi_event.hh" -#include "bbdo/bam/rebuild.hh" -#include "bbdo/events.hh" +#include "com/centreon/broker/bam/ba_duration_event.hh" +#include "com/centreon/broker/bam/ba_event.hh" +#include "com/centreon/broker/bam/dimension_ba_bv_relation_event.hh" +#include "com/centreon/broker/bam/dimension_ba_event.hh" +#include "com/centreon/broker/bam/dimension_ba_timeperiod_relation.hh" +#include "com/centreon/broker/bam/dimension_bv_event.hh" +#include "com/centreon/broker/bam/dimension_kpi_event.hh" +#include "com/centreon/broker/bam/dimension_timeperiod.hh" +#include "com/centreon/broker/bam/dimension_timeperiod_exception.hh" +#include "com/centreon/broker/bam/dimension_timeperiod_exclusion.hh" +#include "com/centreon/broker/bam/dimension_truncate_table_signal.hh" +#include "com/centreon/broker/bam/internal.hh" +#include "com/centreon/broker/bam/kpi_event.hh" +#include "com/centreon/broker/bam/rebuild.hh" #include "com/centreon/broker/database/table_max_size.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/misc/global_lock.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/time/timezone_manager.hh" #include "com/centreon/exceptions/msg_fmt.hh" @@ -155,34 +156,39 @@ int reporting_stream::write(std::shared_ptr const& data) { data->type()); switch (data->type()) { - case io::events::data_type::value: + case io::events::data_type::value: _process_kpi_event(data); break; - case io::events::data_type::value: + case io::events::data_type::value: _process_ba_event(data); break; - case io::events::data_type::value: + case io::events::data_type::value: _process_ba_duration_event(data); break; - case io::events::data_type::value: _process_dimension_truncate_signal(data); break; - case io::events::data_type::value: - case io::events::data_type::value: - case io::events::data_type::value: + case io::events::data_type::value: + case io::events::data_type::value: - case io::events::data_type::value: - case io::events::data_type::value: - case io::events::data_type::value: + case io::events::data_type::value: + case io::events::data_type::value: - case io::events::data_type::value: - case io::events::data_type::value: _process_dimension(data); break; - case io::events::data_type::value: + case io::events::data_type::value: _process_rebuild(data); break; default: @@ -881,20 +887,22 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { if (_processing_dimensions) { // Cache the event until the end of the dimensions dump. switch (e->type()) { - case io::events::data_type::value: { + case io::events::data_type::value: { bam::dimension_ba_event const& dba = *std::static_pointer_cast(e); log_v2::bam()->debug("BAM-BI: preparing ba dimension {} ('{}' '{}')", dba.ba_id, dba.ba_name, dba.ba_description); } break; - case io::events::data_type::value: { + case io::events::data_type::value: { bam::dimension_bv_event const& dbv = *std::static_pointer_cast(e); log_v2::bam()->debug("BAM-BI: preparing bv dimension {} ('{}')", dbv.bv_id, dbv.bv_name); } break; case io::events::data_type< - io::bam, bam::de_dimension_ba_bv_relation_event>::value: { + io::events::bam, bam::de_dimension_ba_bv_relation_event>::value: { bam::dimension_ba_bv_relation_event const& dbabv = *std::static_pointer_cast< bam::dimension_ba_bv_relation_event const>(e); @@ -902,7 +910,8 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { "BAM-BI: preparing relation between ba {} and bv {}", dbabv.ba_id, dbabv.bv_id); } break; - case io::events::data_type::value: { + case io::events::data_type::value: { bam::dimension_kpi_event const& dk{ *std::static_pointer_cast(e)}; std::string kpi_name; @@ -918,7 +927,7 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { log_v2::bam()->debug("BAM-BI: preparing declaration of kpi {} ('{}')", dk.kpi_id, kpi_name); } break; - case io::events::data_type::value: { bam::dimension_timeperiod const& tp = *std::static_pointer_cast(e); @@ -927,7 +936,7 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { tp.name); } break; case io::events::data_type< - io::bam, bam::de_dimension_timeperiod_exception>::value: { + io::events::bam, bam::de_dimension_timeperiod_exception>::value: { bam::dimension_timeperiod_exception const& tpe = *std::static_pointer_cast< bam::dimension_timeperiod_exception const>(e); @@ -935,7 +944,7 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { tpe.timeperiod_id); } break; case io::events::data_type< - io::bam, bam::de_dimension_timeperiod_exclusion>::value: { + io::events::bam, bam::de_dimension_timeperiod_exclusion>::value: { bam::dimension_timeperiod_exclusion const& tpe = *std::static_pointer_cast< bam::dimension_timeperiod_exclusion const>(e); @@ -944,7 +953,7 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { tpe.excluded_timeperiod_id, tpe.timeperiod_id); } break; case io::events::data_type< - io::bam, bam::de_dimension_ba_timeperiod_relation>::value: { + io::events::bam, bam::de_dimension_ba_timeperiod_relation>::value: { bam::dimension_ba_timeperiod_relation const& r = *std::static_pointer_cast< bam::dimension_ba_timeperiod_relation const>(e); @@ -973,31 +982,35 @@ void reporting_stream::_process_dimension(const std::shared_ptr& e) { void reporting_stream::_dimension_dispatch( std::shared_ptr const& data) { switch (data->type()) { - case io::events::data_type::value: + case io::events::data_type::value: _process_dimension_ba(data); break; - case io::events::data_type::value: + case io::events::data_type::value: _process_dimension_bv(data); break; - case io::events::data_type::value: _process_dimension_ba_bv_relation(data); break; - case io::events::data_type::value: + case io::events::data_type::value: _process_dimension_kpi(data); break; - case io::events::data_type::value: + case io::events::data_type::value: _process_dimension_timeperiod(data); break; - case io::events::data_type::value: _process_dimension_timeperiod_exception(data); break; - case io::events::data_type::value: _process_dimension_timeperiod_exclusion(data); break; - case io::events::data_type::value: _process_dimension_ba_timeperiod_relation(data); break; diff --git a/centreon-broker/bam/test/ba/kpi_ba.cc b/centreon-broker/bam/test/ba/kpi_ba.cc index b5d0dbf10d0..cc71d4a38f3 100644 --- a/centreon-broker/bam/test/ba/kpi_ba.cc +++ b/centreon-broker/bam/test/ba/kpi_ba.cc @@ -90,7 +90,7 @@ TEST_F(KpiBA, KpiBa) { s->set_impact_critical(100); s->set_impact_unknown(0); s->set_impact_warning(75); - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); s->set_state_type(1); // test_ba_child->add_impact(s); @@ -197,7 +197,7 @@ TEST_F(KpiBA, KpiBaDt) { s->set_impact_critical(100); s->set_impact_unknown(0); s->set_impact_warning(75); - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); s->set_state_type(1); // test_ba_child->add_impact(s); @@ -312,7 +312,7 @@ TEST_F(KpiBA, KpiBaDtOff) { s->set_impact_critical(100); s->set_impact_unknown(0); s->set_impact_warning(75); - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); s->set_state_type(1); // test_ba_child->add_impact(s); @@ -437,7 +437,7 @@ TEST_F(KpiBA, KpiBaOkDtOff) { s->set_impact_critical(100); s->set_impact_unknown(0); s->set_impact_warning(75); - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); s->set_state_type(1); // test_ba_child->add_impact(s); @@ -546,7 +546,7 @@ TEST_F(KpiBA, KpiBaWorstImpact) { s->set_impact_critical(100); s->set_impact_unknown(0); s->set_impact_warning(75); - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); s->set_state_type(1); kpis.push_back(s); @@ -602,7 +602,7 @@ TEST_F(KpiBA, KpiBaWorstImpact) { _visitor->print_events(); std::cout << "ba state: " << test_ba->get_state_hard() << std::endl; - std::cout << "ba hard impact: " << test_ba->get_downtime_impact_hard() - << std::endl; + std::cout << "ba hard impact: " << test_ba->get_downtime_impact_hard() << std::endl; std::cout << "ba perfdata: " << test_ba->get_perfdata() << std::endl; + } diff --git a/centreon-broker/bam/test/ba/kpi_service.cc b/centreon-broker/bam/test/ba/kpi_service.cc index 8b8c2c4236c..f6b982d041a 100644 --- a/centreon-broker/bam/test/ba/kpi_service.cc +++ b/centreon-broker/bam/test/ba/kpi_service.cc @@ -23,7 +23,6 @@ #include #include #include -#include "bbdo/bam/state.hh" #include "com/centreon/broker/bam/ba.hh" #include "com/centreon/broker/bam/configuration/applier/state.hh" #include "com/centreon/broker/bam/kpi_ba.hh" @@ -70,7 +69,7 @@ TEST_F(BamBA, KpiServiceRecompute) { std::make_shared(1, 1, 1, 1)}; kpi->set_impact_critical(100.0); - kpi->set_state_hard(bam::state_ok); + kpi->set_state_hard(bam::kpi_service::state::state_ok); kpi->set_state_soft(kpi->get_state_hard()); test_ba->add_impact(kpi); kpi->add_parent(test_ba); @@ -118,7 +117,7 @@ TEST_F(BamBA, KpiServiceImpactState) { auto s = std::make_shared(i + 1, 1, i + 1, 1); s->set_impact_warning(10); s->set_impact_critical(20); - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -217,7 +216,7 @@ TEST_F(BamBA, KpiServiceBestState) { for (size_t i = 0; i < 3; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -275,7 +274,7 @@ TEST_F(BamBA, KpiServiceWorstState) { auto s = std::make_shared(i + 1, 1, i + 1, 1); s->set_impact_warning(10); s->set_impact_critical(20); - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -377,7 +376,7 @@ TEST_F(BamBA, KpiServiceRatioNum) { for (int i = 0; i < 4; i++) { std::shared_ptr s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -437,7 +436,7 @@ TEST_F(BamBA, KpiServiceRatioPercent) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -483,7 +482,7 @@ TEST_F(BamBA, KpiServiceDtInheritAllCritical) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -536,9 +535,9 @@ TEST_F(BamBA, KpiServiceDtInheritOneOK) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); if (i == 0) - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); else - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -598,7 +597,7 @@ TEST_F(BamBA, KpiServiceIgnoreDt) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -650,7 +649,7 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpi) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -703,9 +702,9 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiImpact) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); if (i == 3) - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); else - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); s->set_state_soft(s->get_state_hard()); s->set_impact_critical(25); test_ba->add_impact(s); @@ -762,13 +761,13 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiBest) { switch (i) { case 0: case 1: - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); break; case 2: - s->set_state_hard(bam::state_warning); + s->set_state_hard(bam::kpi_service::state::state_warning); break; case 3: - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); break; } s->set_state_soft(s->get_state_hard()); @@ -823,13 +822,13 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiWorst) { switch (i) { case 0: case 1: - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); break; case 2: - s->set_state_hard(bam::state_warning); + s->set_state_hard(bam::kpi_service::state::state_warning); break; case 3: - s->set_state_hard(bam::state_ok); + s->set_state_hard(bam::kpi_service::state::state_ok); break; } s->set_state_soft(s->get_state_hard()); @@ -883,7 +882,7 @@ TEST_F(BamBA, KpiServiceDtIgnoreKpiRatio) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -930,7 +929,7 @@ TEST_F(BamBA, KpiServiceDt) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -1090,7 +1089,7 @@ TEST_F(BamBA, KpiServiceDtInherited_set) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -1148,7 +1147,7 @@ TEST_F(BamBA, KpiServiceDtInherited_unset) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); @@ -1193,7 +1192,7 @@ TEST_F(BamBA, KpiServiceAcknowledgement) { for (int i = 0; i < 4; i++) { auto s = std::make_shared(i + 1, 1, i + 1, 1); - s->set_state_hard(bam::state_critical); + s->set_state_hard(bam::kpi_service::state::state_critical); s->set_state_soft(s->get_state_hard()); test_ba->add_impact(s); s->add_parent(test_ba); diff --git a/centreon-broker/bam/test/exp_builder/availability_builder.cc b/centreon-broker/bam/test/exp_builder/availability_builder.cc index 40900acccef..2e9ca12a288 100644 --- a/centreon-broker/bam/test/exp_builder/availability_builder.cc +++ b/centreon-broker/bam/test/exp_builder/availability_builder.cc @@ -42,7 +42,7 @@ TEST(BamAvailabilityBuilder, Simple) { ASSERT_EQ(builder.get_available(), 3300); } -// TEST(BamAvailabilityBuilder, SummerTime) { +//TEST(BamAvailabilityBuilder, SummerTime) { // /* sun. 27 mars 2021 15:59:18 CEST */ // time_t end_time = 1616939958u; // /* sun. 28 mars 2021 14:59:18 CEST */ @@ -59,6 +59,6 @@ TEST(BamAvailabilityBuilder, Simple) { // // builder.add_event(0, start_time, end_time, false, period); // -// /* The availability here is the duration from start_time to end_time: 3300 -// */ ASSERT_EQ(builder.get_available(), 3600); +// /* The availability here is the duration from start_time to end_time: 3300 */ +// ASSERT_EQ(builder.get_available(), 3600); //} diff --git a/centreon-broker/bam/test/test-visitor.hh b/centreon-broker/bam/test/test-visitor.hh index a163d7b84b4..8d1359041a0 100644 --- a/centreon-broker/bam/test/test-visitor.hh +++ b/centreon-broker/bam/test/test-visitor.hh @@ -52,9 +52,9 @@ class test_visitor : public io::stream { status{b.status}, in_downtime{b.in_downtime} {} test_event(const bam::inherited_downtime& idt) - : typ{test_event::idt}, - ba_id{idt.ba_id}, - in_downtime{idt.in_downtime} {} + : typ{test_event::idt}, + ba_id{idt.ba_id}, + in_downtime{idt.in_downtime} {} }; private: @@ -80,8 +80,7 @@ class test_visitor : public io::stream { _queue.emplace_back(*std::static_pointer_cast(d)); break; case 393233: - _queue.emplace_back( - *std::static_pointer_cast(d)); + _queue.emplace_back(*std::static_pointer_cast(d)); break; default: break; @@ -98,14 +97,13 @@ class test_visitor : public io::stream { switch (e.typ) { case test_visitor::test_event::kpi: std::cout << fmt::format( - "[{};{}] : KPI_EVENT - kpi {} ba {} status {} downtime {}\n", - e.start_time, e.end_time, e.kpi_id, e.ba_id, e.status, - e.in_downtime); + "[{};{}] : KPI_EVENT - kpi {} ba {} status {} downtime {}\n", e.start_time, + e.end_time, e.kpi_id, e.ba_id, e.status, e.in_downtime); break; case test_visitor::test_event::ba: - std::cout << fmt::format( - "[{};{}] : BA_EVENT - ba {} status {} downtime {}\n", - e.start_time, e.end_time, e.ba_id, e.status, e.in_downtime); + std::cout << fmt::format("[{};{}] : BA_EVENT - ba {} status {} downtime {}\n", + e.start_time, e.end_time, e.ba_id, e.status, + e.in_downtime); break; case test_visitor::test_event::idt: std::cout << fmt::format("====> INHERITED_DT - ba {} downtime {}\n", diff --git a/centreon-broker/cmake/package.cmake b/centreon-broker/cmake/package.cmake index e960c0adc27..2f62af7b63d 100644 --- a/centreon-broker/cmake/package.cmake +++ b/centreon-broker/cmake/package.cmake @@ -31,9 +31,9 @@ if (WITH_PACKAGE_SH OR WITH_PACKAGE_NSIS) # Default settings. set(CPACK_PACKAGE_VENDOR "Centreon") - set(CPACK_PACKAGE_VERSION_MAJOR "${COLLECT_MAJOR}") - set(CPACK_PACKAGE_VERSION_MINOR "${COLLECT_MINOR}") - set(CPACK_PACKAGE_VERSION_PATCH "${COLLECT_PATCH}") + set(CPACK_PACKAGE_VERSION_MAJOR "${CENTREON_BROKER_MAJOR}") + set(CPACK_PACKAGE_VERSION_MINOR "${CENTREON_BROKER_MINOR}") + set(CPACK_PACKAGE_VERSION_PATCH "${CENTREON_BROKER_PATCH}") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Centreon Broker is a monitoring addon fully compatible with Nagios and Centreon Engine.") set(CPACK_PACKAGE_FILE_NAME diff --git a/centreon-broker/cmake/tool.cmake b/centreon-broker/cmake/tool.cmake index 89777a77f68..95372a75779 100644 --- a/centreon-broker/cmake/tool.cmake +++ b/centreon-broker/cmake/tool.cmake @@ -25,5 +25,4 @@ function(add_broker_module name activate) set(TESTS_SOURCES ${TESTS_SOURCES} PARENT_SCOPE) set(TESTS_LIBRARIES ${TESTS_LIBRARIES} PARENT_SCOPE) endif (WITH_MODULE_${name}) -endfunction(add_broker_module name activate) - +endfunction(add_broker_module name activate) \ No newline at end of file diff --git a/centreon-broker/config/central-broker.json.in b/centreon-broker/config/central-broker.json.in index 6050460d0fe..ac16660f088 100644 --- a/centreon-broker/config/central-broker.json.in +++ b/centreon-broker/config/central-broker.json.in @@ -8,8 +8,8 @@ "log_timestamp": true, "log_thread_id": false, "event_queue_max_size": 100000, - "command_file": "@BROKER_VAR_LIB@/central-broker.cmd", - "cache_directory": "@BROKER_VAR_LIB_DIR@", + "command_file": "@PREFIX_VAR@/central-broker.cmd", + "cache_directory": "@PREFIX_VAR@", "input": [ { "name": "central-broker-input", @@ -83,8 +83,8 @@ { "type": "stats", "name": "central-broker-stats", - "json_fifo": "@BROKER_VAR_LIB@/central-broker-stats.json" + "json_fifo": "@PREFIX_VAR@/central-broker-stats.json" } ] } -} +} \ No newline at end of file diff --git a/centreon-broker/core/inc/com/centreon/broker/bbdo/ack.hh b/centreon-broker/core/inc/com/centreon/broker/bbdo/ack.hh index b8f7f734495..4330fb6afb6 100644 --- a/centreon-broker/core/inc/com/centreon/broker/bbdo/ack.hh +++ b/centreon-broker/core/inc/com/centreon/broker/bbdo/ack.hh @@ -19,7 +19,6 @@ #ifndef CCB_BBDO_ACK_HH #define CCB_BBDO_ACK_HH -#include "bbdo/events.hh" #include "com/centreon/broker/bbdo/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" @@ -50,7 +49,7 @@ class ack : public io::data { * @return The event type. */ constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t acknowledged_events; diff --git a/centreon-broker/core/inc/com/centreon/broker/bbdo/stop.hh b/centreon-broker/core/inc/com/centreon/broker/bbdo/stop.hh index ee6ea4b5af5..f8875c91238 100644 --- a/centreon-broker/core/inc/com/centreon/broker/bbdo/stop.hh +++ b/centreon-broker/core/inc/com/centreon/broker/bbdo/stop.hh @@ -19,7 +19,6 @@ #ifndef CCB_BBDO_STOP_HH #define CCB_BBDO_STOP_HH -#include "bbdo/events.hh" #include "com/centreon/broker/bbdo/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" @@ -51,7 +50,7 @@ class stop : public io::data { * @return The event type. */ constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/centreon-broker/core/inc/com/centreon/broker/bbdo/stream.hh b/centreon-broker/core/inc/com/centreon/broker/bbdo/stream.hh index d0f150f7781..90bb24a9642 100644 --- a/centreon-broker/core/inc/com/centreon/broker/bbdo/stream.hh +++ b/centreon-broker/core/inc/com/centreon/broker/bbdo/stream.hh @@ -36,24 +36,19 @@ namespace bbdo { * * It is a little tricky around acknowledgements. * This steam is able to read, to write and to flush. - * - * * write() serializes an event and writes it to the substream. It returns how - * many events can be acknowledged. But this count is not directly accessible, - * it comes from the ack message sent by the peer. So we do not have to count - * how many events are serialized, sometimes, we get an ack message and here is - * the value. - * * read() gets some buffer from the substream and unserializes it to create - * an event. The internal buffer is probably not empty after a call to read - * since buffers are not synchronous with events. + * + * * write() serializes an event and writes it to the substream. It returns how many events can be acknowledged. + * But this count is not directly accessible, it comes from the ack message sent by the peer. So we do not have + * to count how many events are serialized, sometimes, we get an ack message and here is the value. + * * read() gets some buffer from the substream and unserializes it to create an event. The internal buffer + * is probably not empty after a call to read since buffers are not synchronous with events. * * * There are also three variables to manage acknowledgements: - * * _events_received_since_last_ack: It is incremented each time a data is - * read. If this value is equal to the _ack_limit, an ack message is sent to the - * peer and this value is reset to 0. When the peer receives this ack message, - * it releases the corresponding events. - * * _acknowledged_events: represents the number of events correctly received - * by the peer after calls to write(). + * * _events_received_since_last_ack: It is incremented each time a data is read. If this value is equal to + * the _ack_limit, an ack message is sent to the peer and this value is reset to 0. When the peer receives + * this ack message, it releases the corresponding events. + * * _acknowledged_events: represents the number of events correctly received by the peer after calls to write(). */ class stream : public io::stream { class buffer { @@ -144,7 +139,6 @@ class stream : public io::stream { * their configuration. */ std::list> _extensions; - const std::tuple _bbdo_version; void _write(std::shared_ptr const& d); bool _read_any(std::shared_ptr& d, time_t deadline); diff --git a/centreon-broker/core/inc/com/centreon/broker/bbdo/version_response.hh b/centreon-broker/core/inc/com/centreon/broker/bbdo/version_response.hh index 5c6fe1e2274..4e71222a7d9 100644 --- a/centreon-broker/core/inc/com/centreon/broker/bbdo/version_response.hh +++ b/centreon-broker/core/inc/com/centreon/broker/bbdo/version_response.hh @@ -21,7 +21,6 @@ #include -#include "bbdo/events.hh" #include "com/centreon/broker/bbdo/internal.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/event_info.hh" @@ -47,8 +46,7 @@ class version_response : public io::data { std::string extensions; version_response(); - version_response(const std::tuple& bbdo_version, - std::string extensions); + version_response(std::string extensions); version_response(const version_response&) = delete; ~version_response() noexcept = default; version_response& operator=(const version_response&) = delete; @@ -59,7 +57,8 @@ class version_response : public io::data { * @return The event type. */ constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/centreon-broker/core/inc/com/centreon/broker/config/applier/state.hh b/centreon-broker/core/inc/com/centreon/broker/config/applier/state.hh index 01df698ba41..0446d1a0594 100644 --- a/centreon-broker/core/inc/com/centreon/broker/config/applier/state.hh +++ b/centreon-broker/core/inc/com/centreon/broker/config/applier/state.hh @@ -19,8 +19,10 @@ #ifndef CCB_CONFIG_APPLIER_STATE_HH #define CCB_CONFIG_APPLIER_STATE_HH +#include #include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/config/state.hh" +#include "com/centreon/broker/namespace.hh" CCB_BEGIN() @@ -36,7 +38,6 @@ class state { std::string _cache_dir; uint32_t _poller_id; uint32_t _rpc_port; - std::tuple _bbdo_version; std::string _poller_name; size_t _pool_size; modules _modules; @@ -55,7 +56,6 @@ class state { void apply(const config::state& s, bool run_mux = true); const std::string& cache_dir() const noexcept; uint32_t rpc_port() const noexcept; - std::tuple bbdo_version() const noexcept; uint32_t poller_id() const noexcept; size_t pool_size() const noexcept; const std::string& poller_name() const noexcept; diff --git a/centreon-broker/core/inc/com/centreon/broker/config/endpoint.hh b/centreon-broker/core/inc/com/centreon/broker/config/endpoint.hh index 1007e3cadf0..c8fb9817ef9 100644 --- a/centreon-broker/core/inc/com/centreon/broker/config/endpoint.hh +++ b/centreon-broker/core/inc/com/centreon/broker/config/endpoint.hh @@ -20,9 +20,9 @@ #define CCB_CONFIG_ENDPOINT_HH #include +#include #include #include -#include #include #include @@ -49,11 +49,13 @@ class endpoint { private: const io_type _type; + void _internal_copy(endpoint const& other); + public: endpoint() = delete; endpoint(io_type way); endpoint(endpoint const& other); - ~endpoint() noexcept; + ~endpoint() = default; endpoint& operator=(endpoint const& other); bool operator==(endpoint const& other) const; bool operator!=(endpoint const& other) const; diff --git a/centreon-broker/core/inc/com/centreon/broker/config/state.hh b/centreon-broker/core/inc/com/centreon/broker/config/state.hh index 9d437b3b08f..bde6fabe72a 100644 --- a/centreon-broker/core/inc/com/centreon/broker/config/state.hh +++ b/centreon-broker/core/inc/com/centreon/broker/config/state.hh @@ -20,9 +20,13 @@ #define CCB_CONFIG_STATE_HH #include +#include +#include +#include #include #include "com/centreon/broker/config/endpoint.hh" +#include "com/centreon/broker/namespace.hh" CCB_BEGIN() @@ -39,7 +43,6 @@ class state { int _broker_id; uint16_t _rpc_port; std::string _broker_name; - std::tuple _bbdo_version; std::string _cache_directory; std::string _command_file; std::string _command_protocol; @@ -67,15 +70,13 @@ class state { state(); state(state const& other); ~state(); - state& operator=(state const& other); + state& operator=(state const&); void broker_id(int id) noexcept; int broker_id() const noexcept; void rpc_port(uint16_t port) noexcept; uint16_t rpc_port(void) const noexcept; void broker_name(std::string const& name); const std::string& broker_name() const noexcept; - void bbdo_version(std::tuple&& v); - const std::tuple& bbdo_version() const noexcept; void cache_directory(std::string const& dir); std::string const& cache_directory() const noexcept; void command_file(std::string const& file); diff --git a/centreon-broker/core/inc/com/centreon/broker/instance_broadcast.hh b/centreon-broker/core/inc/com/centreon/broker/instance_broadcast.hh index 921b3727e25..dc869d59e53 100644 --- a/centreon-broker/core/inc/com/centreon/broker/instance_broadcast.hh +++ b/centreon-broker/core/inc/com/centreon/broker/instance_broadcast.hh @@ -47,7 +47,7 @@ class instance_broadcast : public io::data { * @return The event type. */ constexpr static uint32_t static_type() { - return io::events::data_type::value; } diff --git a/centreon-broker/core/inc/com/centreon/broker/io/event_info.hh b/centreon-broker/core/inc/com/centreon/broker/io/event_info.hh index 1c3b5b32048..269084dc212 100644 --- a/centreon-broker/core/inc/com/centreon/broker/io/event_info.hh +++ b/centreon-broker/core/inc/com/centreon/broker/io/event_info.hh @@ -47,8 +47,6 @@ class event_info { public: struct event_operations { io::data* (*constructor)(); - std::string (*serialize)(const io::data& e); - io::data* (*unserialize)(const char* buffer, size_t size); }; private: @@ -76,7 +74,7 @@ class event_info { * * @param[in] other Object to copy. */ - event_info(const event_info& other) + event_info(event_info const& other) : _mapping(other._mapping), _name(other._name), _ops(other._ops), diff --git a/centreon-broker/core/inc/com/centreon/broker/io/events.hh b/centreon-broker/core/inc/com/centreon/broker/io/events.hh index b5ea9930247..123386ccdce 100644 --- a/centreon-broker/core/inc/com/centreon/broker/io/events.hh +++ b/centreon-broker/core/inc/com/centreon/broker/io/events.hh @@ -1,5 +1,5 @@ /* -** Copyright 2013-2021 Centreon +** Copyright 2013-2017 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ #include -#include "bbdo/events.hh" #include "com/centreon/broker/io/event_info.hh" CCB_BEGIN() @@ -35,7 +34,25 @@ namespace io { */ class events { public: - using events_container = std::unordered_map; + typedef std::unordered_map events_container; + struct category_info { + std::string name; + events_container events; + }; + typedef std::unordered_map categories_container; + // Reserved categories, for reference. + // Their values are very important to maintain the bbdo protocol retro + // compatible. + enum data_category { + neb = 1, + bbdo = 2, + storage = 3, + dumper = 5, + bam = 6, + extcmd = 7, + generator = 8, + internal = 65535 + }; // Internal events used by the core. enum internal_event_category { de_raw = 1, de_instance_broadcast, de_buffer }; // Extcmd events used by the core. @@ -55,17 +72,33 @@ class events { static void unload(); // Category. + uint16_t register_category(std::string const& name, uint16_t hint); void unregister_category(uint16_t category_id); // Events. - uint32_t register_event(uint32_t type_id, + uint32_t register_event(uint16_t category_id, + uint16_t event_id, std::string const& name = std::string(), event_info::event_operations const* ops = nullptr, mapping::entry const* entries = nullptr, std::string const& table_v2 = std::string()); void unregister_event(uint32_t type_id); + // ID manipulations. + static uint16_t category_of_type(uint32_t type) noexcept { + return static_cast(type >> 16); + } + static uint16_t element_of_type(uint32_t type) noexcept { + return static_cast(type); + } + static uint32_t make_type(uint16_t category_id, + uint16_t element_id) noexcept { + return (static_cast(category_id) << 16) | element_id; + } + // Event browsing. + categories_container::const_iterator begin() const; + categories_container::const_iterator end() const; events_container get_events_by_category_name(std::string const& name) const; event_info const* get_event_info(uint32_t type); events_container get_matching_events(std::string const& name) const; @@ -76,7 +109,7 @@ class events { ~events(); events& operator=(events const& other); - events_container _elements; + categories_container _elements; }; } // namespace io diff --git a/centreon-broker/core/inc/com/centreon/broker/io/protobuf.hh b/centreon-broker/core/inc/com/centreon/broker/io/protobuf.hh deleted file mode 100644 index 2228c088f6d..00000000000 --- a/centreon-broker/core/inc/com/centreon/broker/io/protobuf.hh +++ /dev/null @@ -1,114 +0,0 @@ -/* -** Copyright 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#ifndef CCB_IO_PROTOBUF_HH -#define CCB_IO_PROTOBUF_HH - -#include "com/centreon/broker/io/data.hh" -#include "com/centreon/broker/io/event_info.hh" -#include "com/centreon/exceptions/msg_fmt.hh" - -CCB_BEGIN() - -namespace io { -/** - * @class data data.hh "com/centreon/broker/io/data.hh" - * @brief Data abstraction. - * - * Data is the core element that is transmitted through Centreon - * Broker. It is an interface that is implemented by all specific - * module data that wish to be transmitted by the multiplexing - * engine. - */ -template -class protobuf : public data { - public: - T obj; - - /** - * @brief Default constructor - */ - protobuf() : data(Typ) {} - protobuf(protobuf const&) = delete; - ~protobuf() noexcept = default; - protobuf& operator=(const protobuf&) = delete; - - /** - * Get the type of this event. - * - * @return The event type. - */ - constexpr static uint32_t static_type() { return Typ; } - - /** - * @brief A static operator to instantiate an instance of this class. - * - * @return A new instance of this class. - */ - static io::data* new_proto() { return new protobuf(); } - - /** - * @brief Serialization function of this object. Here we encapsulate a - * protobuf message, so this method calls the protobuf mechanism. - * - * @param e The object to serialize. - * - * @return A string with the serialized object. - */ - static std::string serialize(const io::data& e) { - std::string retval; - auto r = static_cast*>(&e); - if (!r->obj.SerializeToString(&retval)) - throw com::centreon::exceptions::msg_fmt( - "Unable to serialize {:x} protobuf object", Typ); - return retval; - } - - /** - * @brief Unserialization function of this object. Here from a const char* - * pointer, we create an instance of this class. - * - * @param buffer The pointer to the char* array - * @param size The size of the array. - * - * @return a pointer to the new object. - */ - static io::data* unserialize(const char* buffer, size_t size) { - std::unique_ptr> retval = - std::make_unique>(); - if (!retval->obj.ParseFromArray(buffer, size)) - throw com::centreon::exceptions::msg_fmt( - "Unable to unserialize protobuf object"); - return retval.release(); - } - - /** - * @brief An internal BBDO object used to access to the constructor, - * serialization and unserialization functions. - */ - const static io::event_info::event_operations operations; -}; - -template -const io::event_info::event_operations protobuf::operations{ - &new_proto, &serialize, &unserialize}; -} // namespace io - -CCB_END() - -#endif // !CCB_IO_PROTOBUF_HH diff --git a/centreon-broker/core/inc/com/centreon/broker/io/protocols.hh b/centreon-broker/core/inc/com/centreon/broker/io/protocols.hh index 26dbd5cdc80..575a2af03b8 100644 --- a/centreon-broker/core/inc/com/centreon/broker/io/protocols.hh +++ b/centreon-broker/core/inc/com/centreon/broker/io/protocols.hh @@ -48,12 +48,12 @@ class protocols { std::map::const_iterator end() const; static protocols& instance(); static void load(); - void reg(const std::string& name, + void reg(std::string const& name, std::shared_ptr fac, unsigned short osi_from, unsigned short osi_to); static void unload(); - void unreg(const std::string& name); + void unreg(std::string const& name); private: protocols(); diff --git a/centreon-broker/core/inc/com/centreon/broker/io/raw.hh b/centreon-broker/core/inc/com/centreon/broker/io/raw.hh index 5434f47582d..63c2012cc5e 100644 --- a/centreon-broker/core/inc/com/centreon/broker/io/raw.hh +++ b/centreon-broker/core/inc/com/centreon/broker/io/raw.hh @@ -1,5 +1,5 @@ /* -** Copyright 2011-2013, 2021 Centreon +** Copyright 2011-2013 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ #include #include -#include "bbdo/events.hh" #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/namespace.hh" @@ -48,7 +47,7 @@ class raw : public data { ~raw(); raw& operator=(raw const& r); constexpr static uint32_t static_type() { - return events::data_type::value; + return events::data_type::value; } void resize(size_t s); char* data(); diff --git a/centreon-broker/core/inc/com/centreon/broker/io/stream.hh b/centreon-broker/core/inc/com/centreon/broker/io/stream.hh index 204aba875e3..e95698e1afb 100644 --- a/centreon-broker/core/inc/com/centreon/broker/io/stream.hh +++ b/centreon-broker/core/inc/com/centreon/broker/io/stream.hh @@ -1,5 +1,5 @@ /* -** Copyright 2011-2013,2015,2017-2021 Centreon +** Copyright 2011-2013,2015,2017 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. diff --git a/centreon-broker/core/inc/com/centreon/broker/misc/filesystem.hh b/centreon-broker/core/inc/com/centreon/broker/misc/filesystem.hh index 26dcbf560a5..650e21923ac 100644 --- a/centreon-broker/core/inc/com/centreon/broker/misc/filesystem.hh +++ b/centreon-broker/core/inc/com/centreon/broker/misc/filesystem.hh @@ -34,8 +34,6 @@ bool file_exists(std::string const& path); bool dir_exists(std::string const& path); bool mkpath(std::string const& path); int64_t file_size(std::string const& path); -bool writable(const std::string& name); -bool readable(const std::string& name); } // namespace filesystem } // namespace misc diff --git a/bbdo/bam/state.hh b/centreon-broker/core/inc/com/centreon/broker/misc/global_lock.hh similarity index 75% rename from bbdo/bam/state.hh rename to centreon-broker/core/inc/com/centreon/broker/misc/global_lock.hh index 30c0ea85a2a..46ad7dee4d5 100644 --- a/bbdo/bam/state.hh +++ b/centreon-broker/core/inc/com/centreon/broker/misc/global_lock.hh @@ -1,5 +1,5 @@ /* -** Copyright 2021 Centreon +** Copyright 2009-2011 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -16,22 +16,18 @@ ** For more information : contact@centreon.com */ -#ifndef CCB_BAM_STATE_HH -#define CCB_BAM_STATE_HH +#ifndef CCB_MISC_GLOBAL_LOCK_HH_ +#define CCB_MISC_GLOBAL_LOCK_HH_ +#include #include "com/centreon/broker/namespace.hh" CCB_BEGIN() -namespace bam { -enum state { - state_ok = 0, - state_warning = 1, - state_critical = 2, - state_unknown = 3, -}; +namespace misc { +extern std::mutex global_lock; } CCB_END() -#endif // !CCB_BAM_STATE_HH +#endif // !CCB_MISC_GLOBAL_LOCK_HH_ diff --git a/centreon-broker/core/inc/com/centreon/broker/misc/misc.hh b/centreon-broker/core/inc/com/centreon/broker/misc/misc.hh index 7586f58e64c..f7c373dfb26 100644 --- a/centreon-broker/core/inc/com/centreon/broker/misc/misc.hh +++ b/centreon-broker/core/inc/com/centreon/broker/misc/misc.hh @@ -23,7 +23,6 @@ #include #include #include -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/namespace.hh" CCB_BEGIN() @@ -36,9 +35,6 @@ std::string exec(std::string const& cmd); int32_t exec_process(char const** argv, bool wait_for_completion); std::vector from_hex(std::string const& str); std::string dump_filters(std::unordered_set const& filters); -std::list parse_perfdata(uint32_t host_id, - uint32_t service_id, - const char* str); } // namespace misc CCB_END() diff --git a/centreon-broker/core/inc/com/centreon/broker/multiplexing/engine.hh b/centreon-broker/core/inc/com/centreon/broker/multiplexing/engine.hh index 25ef7916360..edd9d06c45b 100644 --- a/centreon-broker/core/inc/com/centreon/broker/multiplexing/engine.hh +++ b/centreon-broker/core/inc/com/centreon/broker/multiplexing/engine.hh @@ -19,11 +19,12 @@ #ifndef CCB_MULTIPLEXING_ENGINE_HH #define CCB_MULTIPLEXING_ENGINE_HH -#include #include #include #include +#include +#include "com/centreon/broker/multiplexing/hooker.hh" #include "com/centreon/broker/namespace.hh" #include "com/centreon/broker/persistent_cache.hh" #include "com/centreon/broker/stats/center.hh" @@ -67,30 +68,37 @@ class muxer; * @see muxer */ class engine { - static std::mutex _load_m; static engine* _instance; + std::unique_ptr _cache_file; - enum state { not_started, running, stopped }; + // Data queue. + std::queue> _kiew; - state _state; - std::unique_ptr _cache_file; + // Hooks + std::vector> _hooks; + std::vector>::iterator _hooks_begin; + std::vector>::iterator _hooks_end; // Mutex to lock _kiew and _hooks std::mutex _engine_m; - // Data queue. - std::deque> _kiew; - // Subscriber. std::vector _muxers; + std::mutex _muxers_m; // Statistics. EngineStats* _stats; uint32_t _unprocessed_events; + static std::mutex _load_m; + engine(); std::string _cache_file_path() const; + void _nop(std::shared_ptr const& d); void _send_to_subscribers(); + void _write(std::shared_ptr const& d); + void _write_to_cache_file(std::shared_ptr const& d); + void _publish(std::shared_ptr const& d); void (engine::*_write_func)(std::shared_ptr const&); @@ -102,12 +110,13 @@ class engine { engine(const engine&) = delete; engine& operator=(const engine&) = delete; ~engine() noexcept = default; - void clear(); void publish(const std::shared_ptr& d); void publish(const std::list>& to_publish); void start(); void stop(); + void hook(hooker& h, bool with_data = true); + void unhook(hooker& h); void subscribe(muxer* subscriber); void unsubscribe(muxer* subscriber); }; diff --git a/centreon-broker/core/inc/com/centreon/broker/multiplexing/hooker.hh b/centreon-broker/core/inc/com/centreon/broker/multiplexing/hooker.hh new file mode 100644 index 00000000000..65d473dda6f --- /dev/null +++ b/centreon-broker/core/inc/com/centreon/broker/multiplexing/hooker.hh @@ -0,0 +1,51 @@ +/* +** Copyright 2011 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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_MULTIPLEXING_HOOKER_HH +#define CCB_MULTIPLEXING_HOOKER_HH + +#include "com/centreon/broker/io/stream.hh" +#include "com/centreon/broker/namespace.hh" + +CCB_BEGIN() + +namespace multiplexing { +/** + * @class hooker hooker.hh "com/centreon/broker/multiplexing/hooker.hh" + * @brief Hook object. + * + * Place a hook on the multiplexing engine. + */ +class hooker : public io::stream { + protected: + bool _registered; + + public: + hooker(); + hooker(hooker const& other) = delete; + hooker& operator=(hooker const& other) = delete; + virtual ~hooker() noexcept; + void hook(bool should_hook); + virtual void starting() = 0; + virtual void stopping() = 0; +}; +} // namespace multiplexing + +CCB_END() + +#endif // !CCB_MULTIPLEXING_HOOKER_HH diff --git a/centreon-broker/core/inc/com/centreon/broker/multiplexing/muxer.hh b/centreon-broker/core/inc/com/centreon/broker/multiplexing/muxer.hh index 94782f1d76e..ea7758bdf13 100644 --- a/centreon-broker/core/inc/com/centreon/broker/multiplexing/muxer.hh +++ b/centreon-broker/core/inc/com/centreon/broker/multiplexing/muxer.hh @@ -1,5 +1,5 @@ /* -** Copyright 2009-2017-2021 Centreon +** Copyright 2009-2017 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -21,8 +21,13 @@ #include #include +#include +#include +#include +#include #include +#include "com/centreon/broker/namespace.hh" #include "com/centreon/broker/persistent_file.hh" CCB_BEGIN() @@ -41,7 +46,7 @@ namespace multiplexing { */ class muxer : public io::stream { public: - using filters = std::unordered_set; + typedef std::unordered_set filters; private: std::condition_variable _cv; @@ -74,10 +79,10 @@ class muxer : public io::stream { static uint32_t event_queue_max_size() noexcept; void publish(std::shared_ptr const event); bool read(std::shared_ptr& event, time_t deadline) override; - void set_read_filters(const filters& fltrs); - void set_write_filters(const filters& fltrs); - const filters& get_read_filters() const; - const filters& get_write_filters() const; + void set_read_filters(filters const& fltrs); + void set_write_filters(filters const& fltrs); + filters const& get_read_filters() const; + filters const& get_write_filters() const; const std::string& get_read_filters_str() const; const std::string& get_write_filters_str() const; uint32_t get_event_queue_size() const; @@ -87,7 +92,6 @@ class muxer : public io::stream { void wake(); int32_t write(std::shared_ptr const& d) override; int32_t stop() override; - const std::string& name() const; static std::string memory_file(std::string const& name); static std::string queue_file(std::string const& name); diff --git a/centreon-broker/core/inc/com/centreon/broker/mysql_connection.hh b/centreon-broker/core/inc/com/centreon/broker/mysql_connection.hh index ea0f597b8c2..465e0eb2342 100644 --- a/centreon-broker/core/inc/com/centreon/broker/mysql_connection.hh +++ b/centreon-broker/core/inc/com/centreon/broker/mysql_connection.hh @@ -74,7 +74,6 @@ class mysql_connection { std::list> _tasks_list; std::atomic_int _tasks_count; bool _need_commit; - std::time_t _last_access; std::unordered_map _stmt; std::unordered_map _stmt_query; diff --git a/centreon-broker/core/inc/com/centreon/broker/processing/stat_visitable.hh b/centreon-broker/core/inc/com/centreon/broker/processing/stat_visitable.hh index a52392d8186..a9a6d728fde 100644 --- a/centreon-broker/core/inc/com/centreon/broker/processing/stat_visitable.hh +++ b/centreon-broker/core/inc/com/centreon/broker/processing/stat_visitable.hh @@ -20,8 +20,8 @@ #define CCB_PROCESSING_STAT_VISITABLE_HH #include -#include #include +#include #include #include diff --git a/centreon-broker/core/inc/com/centreon/broker/stats/center.hh b/centreon-broker/core/inc/com/centreon/broker/stats/center.hh index 6d07a6f82e2..fb8a0b9f111 100644 --- a/centreon-broker/core/inc/com/centreon/broker/stats/center.hh +++ b/centreon-broker/core/inc/com/centreon/broker/stats/center.hh @@ -82,7 +82,7 @@ class center { // bool unregister_endpoint(const std::string& name); // bool unregister_feeder(EndpointStats* ep_stats, const std::string& name); // bool unregister_mysql_manager(void); - + int get_json_stats_file_creation(void); void get_stats(const StatsQuery* request, BrokerStats* response); void get_sql_connection_size(GenericSize* response); diff --git a/centreon-broker/core/inc/com/centreon/broker/version.hh.in b/centreon-broker/core/inc/com/centreon/broker/version.hh.in index 6227f813bca..1c15b55c1f9 100644 --- a/centreon-broker/core/inc/com/centreon/broker/version.hh.in +++ b/centreon-broker/core/inc/com/centreon/broker/version.hh.in @@ -15,9 +15,9 @@ CCB_BEGIN() namespace version { // Compile-time values. - unsigned int const major = @COLLECT_MAJOR@; - unsigned int const minor = @COLLECT_MINOR@; - unsigned int const patch = @COLLECT_PATCH@; + unsigned int const major = @CENTREON_BROKER_MAJOR@; + unsigned int const minor = @CENTREON_BROKER_MINOR@; + unsigned int const patch = @CENTREON_BROKER_PATCH@; char const* const string = "@CENTREON_BROKER_VERSION@"; } diff --git a/centreon-broker/core/src/bbdo/ack.cc b/centreon-broker/core/src/bbdo/ack.cc index d218ac699b4..2e1280e3c4c 100644 --- a/centreon-broker/core/src/bbdo/ack.cc +++ b/centreon-broker/core/src/bbdo/ack.cc @@ -43,5 +43,4 @@ mapping::entry const ack::entries[]{ static io::data* new_ack() { return new ack; } -io::event_info::event_operations const ack::operations = {&new_ack, nullptr, - nullptr}; +io::event_info::event_operations const ack::operations = {&new_ack}; diff --git a/centreon-broker/core/src/bbdo/connector.cc b/centreon-broker/core/src/bbdo/connector.cc index e588d940e93..0002a326717 100644 --- a/centreon-broker/core/src/bbdo/connector.cc +++ b/centreon-broker/core/src/bbdo/connector.cc @@ -56,7 +56,7 @@ connector::connector(bool negotiate, // FIXME DBR: why this trick? _timeout(timeout == -1 || timeout == 0 ? 3 : timeout), _ack_limit{ack_limit}, - _extensions{std::move(extensions)} {} + _extensions{extensions} {} /** * Open the connector. diff --git a/centreon-broker/core/src/bbdo/internal.cc b/centreon-broker/core/src/bbdo/internal.cc index 69177201722..4c473ed624a 100644 --- a/centreon-broker/core/src/bbdo/internal.cc +++ b/centreon-broker/core/src/bbdo/internal.cc @@ -39,15 +39,28 @@ using namespace com::centreon::broker::bbdo; void bbdo::load() { // Register BBDO category. io::events& e(io::events::instance()); + int bbdo_category(e.register_category("bbdo", io::events::bbdo)); + if (bbdo_category != io::events::bbdo) { + e.unregister_category(bbdo_category); + log_v2::bbdo()->error( + "BBDO: category {} is already registered whereas it should be reserved " + "for the BBDO core", + io::events::bbdo); + throw msg_fmt( + "BBDO: category {} " + " is already registered whereas it should be " + "reserved for the BBDO core", + io::events::bbdo); + } // Register BBDO events. - e.register_event(make_type(io::bbdo, bbdo::de_version_response), + e.register_event(io::events::bbdo, bbdo::de_version_response, "version_response", &version_response::operations, version_response::entries); - e.register_event(make_type(io::bbdo, bbdo::de_ack), "ack", &ack::operations, + e.register_event(io::events::bbdo, bbdo::de_ack, "ack", &ack::operations, ack::entries); - e.register_event(make_type(io::bbdo, bbdo::de_stop), "stop", - &stop::operations, stop::entries); + e.register_event(io::events::bbdo, bbdo::de_stop, "stop", &stop::operations, + stop::entries); // Register BBDO protocol. io::protocols::instance().reg("BBDO", std::make_shared(), 7, @@ -63,6 +76,6 @@ void bbdo::unload() { // Unregister protocol. io::protocols::instance().unreg("BBDO"); - // Unregister category - io::events::instance().unregister_category(io::bbdo); + // Unregister category. + io::events::instance().unregister_category(io::events::bbdo); } diff --git a/centreon-broker/core/src/bbdo/stop.cc b/centreon-broker/core/src/bbdo/stop.cc index ce2533d71c3..b7b7e4f4de5 100644 --- a/centreon-broker/core/src/bbdo/stop.cc +++ b/centreon-broker/core/src/bbdo/stop.cc @@ -33,5 +33,4 @@ mapping::entry const stop::entries[]{mapping::entry()}; static io::data* new_stop() { return new stop; } -io::event_info::event_operations const stop::operations = {&new_stop, nullptr, - nullptr}; +io::event_info::event_operations const stop::operations = {&new_stop}; diff --git a/centreon-broker/core/src/bbdo/stream.cc b/centreon-broker/core/src/bbdo/stream.cc index 48e2c61effd..1f0e2a009b3 100644 --- a/centreon-broker/core/src/bbdo/stream.cc +++ b/centreon-broker/core/src/bbdo/stream.cc @@ -27,7 +27,6 @@ #include "com/centreon/broker/bbdo/internal.hh" #include "com/centreon/broker/bbdo/stop.hh" #include "com/centreon/broker/bbdo/version_response.hh" -#include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/exceptions/timeout.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/io/raw.hh" @@ -229,93 +228,72 @@ static uint32_t set_ulong(io::data& t, static io::data* unserialize(uint32_t event_type, uint32_t source_id, uint32_t destination_id, - const char* buffer, + char const* buffer, uint32_t size) { // Get event info (operations and mapping). io::event_info const* info(io::events::instance().get_event_info(event_type)); if (info) { // Create object. - if (info->get_mapping()) { - std::unique_ptr t(info->get_operations().constructor()); - if (t) { - t->source_id = source_id; - t->destination_id = destination_id; - // Browse all mapping to unserialize the object. - for (const mapping::entry* current_entry = info->get_mapping(); - !current_entry->is_null(); ++current_entry) - // Skip entries that should not be serialized. - if (current_entry->get_serialize()) { - uint32_t rb; - switch (current_entry->get_type()) { - case mapping::source::BOOL: - rb = set_boolean(*t, *current_entry, buffer, size); - break; - case mapping::source::DOUBLE: - rb = set_double(*t, *current_entry, buffer, size); - break; - case mapping::source::INT: - rb = set_integer(*t, *current_entry, buffer, size); - break; - case mapping::source::SHORT: - rb = set_short(*t, *current_entry, buffer, size); - break; - case mapping::source::STRING: - rb = set_string(*t, *current_entry, buffer, size); - break; - case mapping::source::TIME: - rb = set_timestamp(*t, *current_entry, buffer, size); - break; - case mapping::source::UINT: - rb = set_uint(*t, *current_entry, buffer, size); - break; - case mapping::source::ULONG: - rb = set_ulong(*t, *current_entry, buffer, size); - break; - - default: - log_v2::bbdo()->error( - "BBDO: invalid mapping for object of type '{0}': {1} is " - "not " - "a known type ID", - info->get_name(), current_entry->get_type()); - throw msg_fmt( - "BBDO: invalid mapping for " - "object of type '{}" - "': {}" - " is not a known type ID", - info->get_name(), current_entry->get_type()); - } - buffer += rb; - size -= rb; + std::unique_ptr t(info->get_operations().constructor()); + if (t) { + t->source_id = source_id; + t->destination_id = destination_id; + // Browse all mapping to unserialize the object. + for (const mapping::entry* current_entry = info->get_mapping(); + !current_entry->is_null(); ++current_entry) + // Skip entries that should not be serialized. + if (current_entry->get_serialize()) { + uint32_t rb; + switch (current_entry->get_type()) { + case mapping::source::BOOL: + rb = set_boolean(*t, *current_entry, buffer, size); + break; + case mapping::source::DOUBLE: + rb = set_double(*t, *current_entry, buffer, size); + break; + case mapping::source::INT: + rb = set_integer(*t, *current_entry, buffer, size); + break; + case mapping::source::SHORT: + rb = set_short(*t, *current_entry, buffer, size); + break; + case mapping::source::STRING: + rb = set_string(*t, *current_entry, buffer, size); + break; + case mapping::source::TIME: + rb = set_timestamp(*t, *current_entry, buffer, size); + break; + case mapping::source::UINT: + rb = set_uint(*t, *current_entry, buffer, size); + break; + case mapping::source::ULONG: + rb = set_ulong(*t, *current_entry, buffer, size); + break; + + default: + log_v2::bbdo()->error( + "BBDO: invalid mapping for object of type '{0}': {1} is not " + "a known type ID", + info->get_name(), current_entry->get_type()); + throw msg_fmt( + "BBDO: invalid mapping for " + "object of type '{}" + "': {}" + " is not a known type ID", + info->get_name(), current_entry->get_type()); } - return t.release(); - } else { - log_v2::bbdo()->error( - "BBDO: cannot create object of ID {} whereas it has been " - "registered", - event_type); - throw msg_fmt( - "BBDO: cannot create object of ID {}" - " whereas it has been registered", - event_type); - } - } else { - std::unique_ptr t( - info->get_operations().unserialize(buffer, size)); - if (t) { - t->source_id = source_id; - t->destination_id = destination_id; - } else { - log_v2::bbdo()->error( - "BBDO: cannot create object of ID {} whereas it has been " - "registered", - event_type); - throw msg_fmt( - "BBDO: cannot create object of ID {} whereas it has been " - "registered", - event_type); - } + buffer += rb; + size -= rb; + } return t.release(); + } else { + log_v2::bbdo()->error( + "BBDO: cannot create object of ID {} whereas it has been registered", + event_type); + throw msg_fmt( + "BBDO: cannot create object of ID {}" + " whereas it has been registered", + event_type); } } else { log_v2::bbdo()->info( @@ -437,136 +415,93 @@ static io::raw* serialize(const io::data& e) { // Get event info (mapping). const io::event_info* info = io::events::instance().get_event_info(e.type()); if (info) { - // Serialize properties of the object. - const mapping::entry* current_entry = info->get_mapping(); - if (current_entry) { - // Serialization buffer. - queue.emplace_back(std::vector()); - auto* header = &queue.back(); - header->resize(BBDO_HEADER_SIZE); - queue.emplace_back(std::vector()); - auto* content = &queue.back(); - - for (mapping::entry const* current_entry(info->get_mapping()); - !current_entry->is_null(); ++current_entry) { - // Skip entries that should not be serialized. - if (current_entry->get_serialize()) - switch (current_entry->get_type()) { - case mapping::source::BOOL: - get_boolean(e, *current_entry, *content); - break; - case mapping::source::DOUBLE: - get_double(e, *current_entry, *content); - break; - case mapping::source::INT: - get_integer(e, *current_entry, *content); - break; - case mapping::source::SHORT: - get_short(e, *current_entry, *content); - break; - case mapping::source::STRING: - get_string(e, *current_entry, *content); - break; - case mapping::source::TIME: - get_timestamp(e, *current_entry, *content); - break; - case mapping::source::UINT: - get_uint(e, *current_entry, *content); - break; - case mapping::source::ULONG: - get_ulong(e, *current_entry, *content); - break; - default: - log_v2::bbdo()->error( - "BBDO: invalid mapping for object of type '{}': {} is not a " - "known type ID", - info->get_name(), current_entry->get_type()); - throw msg_fmt( - "BBDO: invalid mapping for object" - " of type '{}" - "': {}" - " is not a known type ID", - info->get_name(), current_entry->get_type()); - } + // Serialization buffer. + queue.emplace_back(std::vector()); + auto* header = &queue.back(); + header->resize(BBDO_HEADER_SIZE); + queue.emplace_back(std::vector()); + auto* content = &queue.back(); - // Packet splitting. - while (content->size() >= 0xffff) { - queue.emplace_back(std::vector()); - auto* new_header = &queue.back(); - new_header->resize(BBDO_HEADER_SIZE); - queue.emplace_back(content->begin() + 0xffff, content->end()); - content->resize(0xffff); - auto* new_content = &queue.back(); - *(reinterpret_cast(header->data() + 2)) = 0xffff; - *(reinterpret_cast(header->data() + 4)) = htonl(e.type()); - *(reinterpret_cast(header->data() + 8)) = - htonl(e.source_id); - *(reinterpret_cast(header->data() + 12)) = - htonl(e.destination_id); - - *(reinterpret_cast(header->data())) = htons( - misc::crc16_ccitt(header->data() + 2, BBDO_HEADER_SIZE - 2)); - content = new_content; - header = new_header; + // Serialize properties of the object. + for (mapping::entry const* current_entry(info->get_mapping()); + !current_entry->is_null(); ++current_entry) { + // Skip entries that should not be serialized. + if (current_entry->get_serialize()) + switch (current_entry->get_type()) { + case mapping::source::BOOL: + get_boolean(e, *current_entry, *content); + break; + case mapping::source::DOUBLE: + get_double(e, *current_entry, *content); + break; + case mapping::source::INT: + get_integer(e, *current_entry, *content); + break; + case mapping::source::SHORT: + get_short(e, *current_entry, *content); + break; + case mapping::source::STRING: + get_string(e, *current_entry, *content); + break; + case mapping::source::TIME: + get_timestamp(e, *current_entry, *content); + break; + case mapping::source::UINT: + get_uint(e, *current_entry, *content); + break; + case mapping::source::ULONG: + get_ulong(e, *current_entry, *content); + break; + default: + log_v2::bbdo()->error( + "BBDO: invalid mapping for object of type '{}': {} is not a " + "known type ID", + info->get_name(), current_entry->get_type()); + throw msg_fmt( + "BBDO: invalid mapping for object" + " of type '{}" + "': {}" + " is not a known type ID", + info->get_name(), current_entry->get_type()); } - } - - *(reinterpret_cast(header->data() + 2)) = - htons(content->size()); - *(reinterpret_cast(header->data() + 4)) = htonl(e.type()); - *(reinterpret_cast(header->data() + 8)) = htonl(e.source_id); - *(reinterpret_cast(header->data() + 12)) = - htonl(e.destination_id); - *(reinterpret_cast(header->data())) = - htons(misc::crc16_ccitt(header->data() + 2, BBDO_HEADER_SIZE - 2)); - - } else { - /* Here is the protobuf case: no mapping */ - std::string r{info->get_operations().serialize(e)}; - size_t size = r.size(); - auto it = r.begin(); - while (size > 0) { - // Serialization buffer. + // Packet splitting. + while (content->size() >= 0xffff) { queue.emplace_back(std::vector()); - auto* content = &queue.back(); - content->resize(BBDO_HEADER_SIZE); - if (size < 0xffff) { - content->insert(content->end(), it, r.end()); - *(reinterpret_cast(content->data() + 2)) = htons(size); - *(reinterpret_cast(content->data() + 4)) = htonl(e.type()); - *(reinterpret_cast(content->data() + 8)) = - htonl(e.source_id); - *(reinterpret_cast(content->data() + 12)) = - htonl(e.destination_id); - - *(reinterpret_cast(content->data())) = htons( - misc::crc16_ccitt(content->data() + 2, BBDO_HEADER_SIZE - 2)); - break; - } else { - content->insert(content->end(), it, it + 0xffff); - *(reinterpret_cast(content->data() + 2)) = 0xffff; - *(reinterpret_cast(content->data() + 4)) = htonl(e.type()); - *(reinterpret_cast(content->data() + 8)) = - htonl(e.source_id); - *(reinterpret_cast(content->data() + 12)) = - htonl(e.destination_id); - - *(reinterpret_cast(content->data())) = htons( - misc::crc16_ccitt(content->data() + 2, BBDO_HEADER_SIZE - 2)); - size -= 0xffff; - it += 0xffff; - } + auto* new_header = &queue.back(); + new_header->resize(BBDO_HEADER_SIZE); + queue.emplace_back(content->begin() + 0xffff, content->end()); + content->resize(0xffff); + auto* new_content = &queue.back(); + *(reinterpret_cast(header->data() + 2)) = 0xffff; + *(reinterpret_cast(header->data() + 4)) = htonl(e.type()); + *(reinterpret_cast(header->data() + 8)) = htonl(e.source_id); + *(reinterpret_cast(header->data() + 12)) = + htonl(e.destination_id); + + *(reinterpret_cast(header->data())) = + htons(misc::crc16_ccitt(header->data() + 2, BBDO_HEADER_SIZE - 2)); + content = new_content; + header = new_header; } } + *(reinterpret_cast(header->data() + 2)) = htons(content->size()); + *(reinterpret_cast(header->data() + 4)) = htonl(e.type()); + *(reinterpret_cast(header->data() + 8)) = htonl(e.source_id); + *(reinterpret_cast(header->data() + 12)) = + htonl(e.destination_id); + + *(reinterpret_cast(header->data())) = + htons(misc::crc16_ccitt(header->data() + 2, BBDO_HEADER_SIZE - 2)); + // Finalization: concatenation of all the vectors in the queue. size_t size = 0; for (auto& v : queue) size += v.size(); // Serialization buffer. - std::unique_ptr buffer(std::make_unique()); + std::unique_ptr buffer(new io::raw); std::vector& data(buffer->get_buffer()); data.reserve(size); for (auto& v : queue) @@ -598,8 +533,7 @@ stream::stream(bool is_input, _acknowledged_events{0}, _ack_limit(1000), _events_received_since_last_ack(0), - _extensions{extensions}, - _bbdo_version{config::applier::state::instance().bbdo_version()} {} + _extensions{extensions} {} /** * @brief All the mecanism behind this stream is stopped once this method is @@ -729,7 +663,7 @@ void stream::negotiate(stream::negotiation_type neg) { /* if _negotiate, we send all the extensions we would like to have, * otherwise we only send the mandatory extensions */ std::shared_ptr welcome_packet( - std::make_shared(_bbdo_version, extensions)); + std::make_shared(extensions)); _write(welcome_packet); } @@ -758,25 +692,26 @@ void stream::negotiate(stream::negotiation_type neg) { throw msg_fmt(msg); } + // Handle protocol version. std::shared_ptr v( std::static_pointer_cast(d)); - if (v->bbdo_major != std::get<0>(_bbdo_version)) { + if (v->bbdo_major != BBDO_VERSION_MAJOR) { log_v2::bbdo()->error( "BBDO: peer is using protocol version {}.{}.{} whereas we're using " "protocol version {}.{}.{}", - v->bbdo_major, v->bbdo_minor, v->bbdo_patch, std::get<0>(_bbdo_version), - std::get<1>(_bbdo_version), std::get<2>(_bbdo_version)); + v->bbdo_major, v->bbdo_minor, v->bbdo_patch, BBDO_VERSION_MAJOR, + BBDO_VERSION_MINOR, BBDO_VERSION_PATCH); throw msg_fmt( "BBDO: peer is using protocol version {}.{}.{}" " whereas we're using protocol version {}.{}.{}", - v->bbdo_major, v->bbdo_minor, v->bbdo_patch, std::get<0>(_bbdo_version), - std::get<1>(_bbdo_version), std::get<2>(_bbdo_version)); + v->bbdo_major, v->bbdo_minor, v->bbdo_patch, BBDO_VERSION_MAJOR, + BBDO_VERSION_MINOR, BBDO_VERSION_PATCH); } log_v2::bbdo()->info( "BBDO: peer is using protocol version {}.{}.{}, we're using version " "{}.{}.{}", - v->bbdo_major, v->bbdo_minor, v->bbdo_patch, std::get<0>(_bbdo_version), - std::get<1>(_bbdo_version), std::get<2>(_bbdo_version)); + v->bbdo_major, v->bbdo_minor, v->bbdo_patch, BBDO_VERSION_MAJOR, + BBDO_VERSION_MINOR, BBDO_VERSION_PATCH); // Send our own packet if we should be second. if (neg == negotiate_second) { @@ -784,8 +719,8 @@ void stream::negotiate(stream::negotiation_type neg) { "BBDO: sending welcome packet (available extensions: {})", extensions); /* if _negotiate, we send all the extensions we would like to have, * otherwise we only send the mandatory extensions */ - auto welcome_packet( - std::make_shared(_bbdo_version, extensions)); + std::shared_ptr welcome_packet( + std::make_shared(extensions)); _write(welcome_packet); _substream->flush(); } @@ -880,31 +815,30 @@ bool stream::read(std::shared_ptr& d, time_t deadline) { bool timed_out(!_read_any(d, deadline)); uint32_t event_id(!d ? 0 : d->type()); - while (!timed_out && ((event_id >> 16) == io::bbdo)) { + while (!timed_out && ((event_id >> 16) == io::events::bbdo)) { // Version response. if ((event_id & 0xffff) == 1) { - auto version(std::static_pointer_cast(d)); - if (version->bbdo_major != std::get<0>(_bbdo_version)) { + std::shared_ptr version( + std::static_pointer_cast(d)); + if (version->bbdo_major != BBDO_VERSION_MAJOR) { log_v2::bbdo()->error( - "BBDO: peer is using protocol version {}.{}.{}, whereas we're " - "using protocol version {}.{}.{}", + "BBDO: peer is using protocol version {0}.{1}.{2} , whereas we're " + "using protocol version " + "{3}.{4}.{5}", version->bbdo_major, version->bbdo_minor, version->bbdo_patch, - std::get<0>(_bbdo_version), std::get<1>(_bbdo_version), - std::get<2>(_bbdo_version)); + BBDO_VERSION_MAJOR, BBDO_VERSION_MINOR, BBDO_VERSION_PATCH); throw msg_fmt( "BBDO: peer is using protocol version {}.{}.{} " "whereas we're using protocol version {}.{}.{}", version->bbdo_major, version->bbdo_minor, version->bbdo_patch, - std::get<0>(_bbdo_version), std::get<1>(_bbdo_version), - std::get<2>(_bbdo_version)); + BBDO_VERSION_MAJOR, BBDO_VERSION_MINOR, BBDO_VERSION_PATCH); } log_v2::bbdo()->info( "BBDO: peer is using protocol version {}.{}.{} , we're using " "version " "{}.{}.{}", version->bbdo_major, version->bbdo_minor, version->bbdo_patch, - std::get<0>(_bbdo_version), std::get<1>(_bbdo_version), - std::get<2>(_bbdo_version)); + BBDO_VERSION_MAJOR, BBDO_VERSION_MINOR, BBDO_VERSION_PATCH); } else if ((event_id & 0xffff) == 2) { log_v2::bbdo()->info( "BBDO: received acknowledgement for {} events", @@ -1066,7 +1000,7 @@ bool stream::_read_any(std::shared_ptr& d, time_t deadline) { BBDO_HEADER_SIZE + packet_size, event_id); } else { log_v2::bbdo()->warn("unknown event type {} event cannot be decoded", - event_id); + event_id); log_v2::bbdo()->trace("discarded {} bytes", BBDO_HEADER_SIZE + packet_size); } diff --git a/centreon-broker/core/src/bbdo/version_response.cc b/centreon-broker/core/src/bbdo/version_response.cc index 242113ddaee..cf8bdc5ad5b 100644 --- a/centreon-broker/core/src/bbdo/version_response.cc +++ b/centreon-broker/core/src/bbdo/version_response.cc @@ -35,13 +35,11 @@ version_response::version_response() * * @param extensions A string with extensions asked for. */ -version_response::version_response( - const std::tuple& bbdo_version, - std::string extensions) +version_response::version_response(std::string extensions) : io::data(version_response::static_type()), - bbdo_major(std::get<0>(bbdo_version)), - bbdo_minor(std::get<1>(bbdo_version)), - bbdo_patch(std::get<2>(bbdo_version)), + bbdo_major(BBDO_VERSION_MAJOR), + bbdo_minor(BBDO_VERSION_MINOR), + bbdo_patch(BBDO_VERSION_PATCH), extensions(std::move(extensions)) {} // Mapping. @@ -57,4 +55,4 @@ static auto new_version_response() -> io::data* { return new version_response; } io::event_info::event_operations const version_response::operations = { - &new_version_response, nullptr, nullptr}; + &new_version_response}; diff --git a/centreon-broker/core/src/broker_impl.cc b/centreon-broker/core/src/broker_impl.cc index d6384f788a7..90d466de489 100644 --- a/centreon-broker/core/src/broker_impl.cc +++ b/centreon-broker/core/src/broker_impl.cc @@ -90,14 +90,14 @@ grpc::Status broker_impl::GetModulesStats(grpc::ServerContext* context for (auto& obj : value) { object["module" + obj["name"].get()] = obj; } - response->set_str_arg(object.dump()); + response->set_str_arg(std::move(object.dump())); break; case GenericNameOrIndex::kStr: for (auto& obj : value) { if (obj["name"].get() == request->str()) { found = true; - response->set_str_arg(object.dump()); + response->set_str_arg(std::move(object.dump())); break; } } @@ -145,14 +145,14 @@ grpc::Status broker_impl::GetEndpointStats(grpc::ServerContext* context for (auto& obj : value) { object["module" + obj["name"].get()] = obj; } - response->set_str_arg(object.dump()); + response->set_str_arg(std::move(object.dump())); break; case GenericNameOrIndex::kStr: for (auto& obj : value) { if (obj["name"].get() == request->str()) { found = true; - response->set_str_arg(obj.dump()); + response->set_str_arg(std::move(obj.dump())); break; } } @@ -168,7 +168,7 @@ grpc::Status broker_impl::GetEndpointStats(grpc::ServerContext* context grpc::string("idx too big")); object = value[request->idx()]; - response->set_str_arg(object.dump()); + response->set_str_arg(std::move(object.dump())); break; default: @@ -185,7 +185,7 @@ grpc::Status broker_impl::GetGenericStats( nlohmann::json object; stats::get_generic_stats(object); - response->set_str_arg(object.dump()); + response->set_str_arg(std::move(object.dump())); return grpc::Status::OK; } diff --git a/centreon-broker/core/src/brokerrpc.cc b/centreon-broker/core/src/brokerrpc.cc index af2430bb06e..031aaa96900 100644 --- a/centreon-broker/core/src/brokerrpc.cc +++ b/centreon-broker/core/src/brokerrpc.cc @@ -18,21 +18,15 @@ */ #include "com/centreon/broker/brokerrpc.hh" -#include #include +#include using namespace com::centreon::broker; -/** - * @brief Constructor of our gRPC server - * - * @param address - * @param port - * @param broker_name - */ brokerrpc::brokerrpc(const std::string& address, uint16_t port, std::string const& broker_name) { + //broker_impl* service = new broker_impl; _service.set_broker_name(broker_name); std::string server_address{fmt::format("{}:{}", address, port)}; grpc::ServerBuilder builder; @@ -41,9 +35,6 @@ brokerrpc::brokerrpc(const std::string& address, _server = builder.BuildAndStart(); } -/** - * @brief The shutdown() method, to stop the gRPC server. - */ void brokerrpc::shutdown() { _server->Shutdown(); _server->Wait(); diff --git a/centreon-broker/core/src/compression/stream.cc b/centreon-broker/core/src/compression/stream.cc index 77a71b15103..2084e853f53 100644 --- a/centreon-broker/core/src/compression/stream.cc +++ b/centreon-broker/core/src/compression/stream.cc @@ -99,9 +99,9 @@ bool stream::read(std::shared_ptr& data, time_t deadline) { if (size <= 0 || size > max_data_size) { // Skip corrupted data, one byte at a time. log_v2::core()->error( - "compression: stream got corrupted packet size of {} bytes, not in " + "compression: {:x} got corrupted packet size of {} bytes, not in " "the 0-{} range, skipping next byte", - size, max_data_size); + static_cast(this), size, max_data_size); if (!skipped) log_v2::core()->error( "compression: peer {} is sending corrupted data", peer()); @@ -126,14 +126,15 @@ bool stream::read(std::shared_ptr& data, time_t deadline) { (_rbuffer.data() + sizeof(int32_t))), size); } catch (exceptions::corruption const& e) { - log_v2::core()->debug("corrupted data: {}", e.what()); + log_v2::core()->debug(e.what()); } } if (!r->size()) { // No data or uncompressed size of 0 means corrupted // input. log_v2::core()->error( - "compression: stream got corrupted compressed data, skipping next " - "byte"); + "compression: {:x} got corrupted compressed data, skipping next " + "byte", + static_cast(this)); if (!skipped) log_v2::core()->error( "compression: peer {} is sending corrupted data", peer()); @@ -142,8 +143,8 @@ bool stream::read(std::shared_ptr& data, time_t deadline) { corrupted = true; } else { log_v2::core()->debug( - "compression: stream uncompressed {} bytes to {} bytes", - size + sizeof(int32_t), r->size()); + "compression: {:x} uncompressed {} bytes to {} bytes", + static_cast(this), size + sizeof(int32_t), r->size()); data = r; _rbuffer.pop(size + sizeof(int32_t)); corrupted = false; @@ -263,10 +264,10 @@ void stream::_flush() { // Compress data. std::shared_ptr compressed(new io::raw); std::vector& data(compressed->get_buffer()); - data = zlib::compress(_wbuffer, _level); + data = std::move(zlib::compress(_wbuffer, _level)); log_v2::core()->debug( - "compression: stream compressed {} bytes to {} bytes (level {})", - _wbuffer.size(), compressed->size(), _level); + "compression: {:x} compressed {} bytes to {} bytes (level {})", + static_cast(this), _wbuffer.size(), compressed->size(), _level); _wbuffer.clear(); // Add compressed data size. diff --git a/centreon-broker/core/src/config/applier/modules.cc b/centreon-broker/core/src/config/applier/modules.cc index 90988444328..942cc0ca42a 100644 --- a/centreon-broker/core/src/config/applier/modules.cc +++ b/centreon-broker/core/src/config/applier/modules.cc @@ -169,7 +169,7 @@ bool modules::load_file(const std::string& filename, const void* arg) { void* h = dlopen(filename.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (!h) log_v2::config()->error("modules: could not load module '{}': {}", - filename, dlerror()); + filename, dlerror()); if (_check_module(filename, h)) { void* parents = dlsym(h, handle::parents_list); diff --git a/centreon-broker/core/src/config/applier/state.cc b/centreon-broker/core/src/config/applier/state.cc index c03bd52475b..f569feb5042 100644 --- a/centreon-broker/core/src/config/applier/state.cc +++ b/centreon-broker/core/src/config/applier/state.cc @@ -18,12 +18,16 @@ #include "com/centreon/broker/config/applier/state.hh" +#include #include #include #include +#include #include "com/centreon/broker/config/applier/endpoint.hh" +#include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/instance_broadcast.hh" +#include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/muxer.hh" @@ -40,7 +44,7 @@ static state* gl_state = nullptr; /** * Default constructor. */ -state::state() : _poller_id(0), _rpc_port(0), _bbdo_version{2u, 0u, 0u} {} +state::state() : _poller_id(0), _rpc_port(0) {} /** * Apply a configuration state. @@ -48,7 +52,7 @@ state::state() : _poller_id(0), _rpc_port(0), _bbdo_version{2u, 0u, 0u} {} * @param[in] s State to apply. * @param[in] run_mux Set to true if multiplexing must be run. */ -void state::apply(const com::centreon::broker::config::state& s, bool run_mux) { +void state::apply(com::centreon::broker::config::state const& s, bool run_mux) { // Sanity checks. static char const* const allowed_chars( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 -_."); @@ -92,7 +96,6 @@ void state::apply(const com::centreon::broker::config::state& s, bool run_mux) { _poller_id = s.poller_id(); _poller_name = s.poller_name(); _rpc_port = s.rpc_port(); - _bbdo_version = s.bbdo_version(); // Thread pool size. _pool_size = s.pool_size(); @@ -123,13 +126,13 @@ void state::apply(const com::centreon::broker::config::state& s, bool run_mux) { com::centreon::broker::multiplexing::muxer::event_queue_max_size( s.event_queue_max_size()); - com::centreon::broker::config::state st{s}; + com::centreon::broker::config::state st = s; // Apply input and output configuration. endpoint::instance().apply(st.endpoints()); // Create instance broadcast event. - auto ib{std::make_shared()}; + std::shared_ptr ib(new instance_broadcast); ib->broker_id = io::data::broker_id; ib->poller_id = _poller_id; ib->poller_name = _poller_name; @@ -150,15 +153,6 @@ const std::string& state::cache_dir() const noexcept { return _cache_dir; } -/** - * @brief Get the configured BBDO version - * - * @return The bbdo version. - */ -std::tuple state::bbdo_version() const noexcept { - return _bbdo_version; -} - /** * Get the instance of this object. * diff --git a/centreon-broker/core/src/config/endpoint.cc b/centreon-broker/core/src/config/endpoint.cc index daf4d63c455..cfcead93023 100644 --- a/centreon-broker/core/src/config/endpoint.cc +++ b/centreon-broker/core/src/config/endpoint.cc @@ -1,5 +1,5 @@ /* -** Copyright 2009-2013,2020-2021 Centreon +** Copyright 2009-2013,2020 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ */ #include "com/centreon/broker/config/endpoint.hh" -#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker::config; @@ -39,25 +38,9 @@ endpoint::endpoint(endpoint::io_type way) * * @param[in] other Object to copy. */ -endpoint::endpoint(endpoint const& other) - : _type(other._type), - buffering_timeout{other.buffering_timeout}, - failovers{other.failovers}, - name{other.name}, - params{other.params}, - read_filters{other.read_filters}, - read_timeout{other.read_timeout}, - retry_interval{other.retry_interval}, - type{other.type}, - write_filters{other.write_filters}, - cache_enabled{other.cache_enabled}, - cfg(other.cfg) {} - -/** - * @brief endpoint destructor. - * - */ -endpoint::~endpoint() noexcept {} +endpoint::endpoint(endpoint const& other) : _type(other._type) { + _internal_copy(other); +} /** * Assignment operator. @@ -66,20 +49,9 @@ endpoint::~endpoint() noexcept {} * * @return This object. */ -endpoint& endpoint::operator=(const endpoint& other) { - if (this != &other) { - buffering_timeout = other.buffering_timeout; - failovers = other.failovers; - name = other.name; - params = other.params; - read_filters = other.read_filters; - read_timeout = other.read_timeout; - retry_interval = other.retry_interval; - type = other.type; - write_filters = other.write_filters; - cache_enabled = other.cache_enabled; - cfg = other.cfg; - } +endpoint& endpoint::operator=(endpoint const& other) { + if (this != &other) + _internal_copy(other); return *this; } @@ -153,3 +125,26 @@ bool endpoint::operator<(endpoint const& other) const { } return it1 == end1 && it2 != end2; } + +/** + * @brief Copy data members. + * + * Copy all data members from the given object to the current instance. + * This method is used by the copy constructor and the assignment + * operator. + * + * @param[in] other Object to copy. + */ +void endpoint::_internal_copy(endpoint const& other) { + buffering_timeout = other.buffering_timeout; + failovers = other.failovers; + name = other.name; + params = other.params; + read_filters = other.read_filters; + read_timeout = other.read_timeout; + retry_interval = other.retry_interval; + type = other.type; + write_filters = other.write_filters; + cache_enabled = other.cache_enabled; + cfg = other.cfg; +} diff --git a/centreon-broker/core/src/config/parser.cc b/centreon-broker/core/src/config/parser.cc index 7ecf0b3891c..198bf6e8463 100644 --- a/centreon-broker/core/src/config/parser.cc +++ b/centreon-broker/core/src/config/parser.cc @@ -27,7 +27,6 @@ #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/misc/filesystem.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -136,21 +135,6 @@ state parser::parse(std::string const& file) { json_document["centreonBroker"]["grpc"]["rpc_port"] .get())); } - } else if (it.key() == "bbdo_version" && it.value().is_string()) { - std::string version = json_document["centreonBroker"]["bbdo_version"] - .get(); - std::list v = misc::string::split_sv(version, '.'); - if (v.size() != 3) - throw msg_fmt("config parser: cannot parse bbdo_version '{}'", - version); - - auto it = v.begin(); - uint16_t major = atoi(it->data()); - ++it; - uint16_t minor = atoi(it->data()); - ++it; - uint16_t patch = atoi(it->data()); - retval.bbdo_version({major, minor, patch}); } else if (get_conf({it.key(), it.value()}, "broker_name", retval, &state::broker_name, &json::is_string)) @@ -164,16 +148,12 @@ state parser::parse(std::string const& file) { ; else if (get_conf({it.key(), it.value()}, "module_directory", retval, &state::module_directory, - &json::is_string)) { - if (!misc::filesystem::readable(retval.module_directory())) - throw msg_fmt("The module directory '{}' is not accessible", retval.module_directory()); - } + &json::is_string)) + ; else if (get_conf({it.key(), it.value()}, "cache_directory", retval, &state::cache_directory, - &json::is_string)) { - if (!misc::filesystem::readable(retval.cache_directory())) - throw msg_fmt("The cache directory '{}' is not accessible", retval.cache_directory()); - } + &json::is_string)) + ; else if (get_conf({it.key(), it.value()}, "pool_size", retval, &state::pool_size, &json::is_number, &json::get)) @@ -248,9 +228,6 @@ state parser::parse(std::string const& file) { if (conf.directory.empty()) conf.directory = "/var/log/centreon-broker"; - if (!misc::filesystem::writable(conf.directory)) - throw msg_fmt("The log directory '{}' is not writable", conf.directory); - conf.filename = ""; if (conf_js.contains("filename") && conf_js["filename"].is_string()) { @@ -407,8 +384,6 @@ void parser::_parse_endpoint(json const& elem, module = "70-rrd.so"; else if (e.type == "sql") module = "80-sql.so"; - else if (e.type == "unified_sql") - module = "20-unified_sql.so"; else if (e.type == "storage") module = "20-storage.so"; else if (e.type == "bam") diff --git a/centreon-broker/core/src/config/state.cc b/centreon-broker/core/src/config/state.cc index 91f7c4ff79c..0063214ffdc 100644 --- a/centreon-broker/core/src/config/state.cc +++ b/centreon-broker/core/src/config/state.cc @@ -18,12 +18,8 @@ #include "com/centreon/broker/config/state.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/bbdo/internal.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker::config; -using namespace com::centreon::exceptions; /** * Default constructor. @@ -31,7 +27,6 @@ using namespace com::centreon::exceptions; state::state() : _broker_id{0}, _rpc_port{0}, - _bbdo_version{BBDO_VERSION_MAJOR, BBDO_VERSION_MINOR, BBDO_VERSION_PATCH}, _command_protocol{"json"}, _event_queue_max_size{10000}, _poller_id{0}, @@ -147,25 +142,6 @@ std::string const& state::broker_name() const noexcept { return _broker_name; } -/** - * Set the BBDO version. - * - * @param[in] v bbdo version given as a tuple of uint16. - */ -void state::bbdo_version(std::tuple&& v) { - _bbdo_version = std::move(v); -} - -/** - * Get BBDO version. - * - * @return bbdo version as a tuple of uint16. - */ -const std::tuple& state::bbdo_version() - const noexcept { - return _bbdo_version; -} - /** * Set the cache directory. * @@ -292,16 +268,6 @@ std::list& state::module_list() noexcept { * @param module the module name to add. */ void state::add_module(std::string module) { - bool conflict{false}; - if (module == "20-unified_sql.so") - conflict = std::find(_module_list.begin(), _module_list.end(), "20-storage.so") != _module_list.end() || std::find(_module_list.begin(), _module_list.end(), "80-sql.so") != _module_list.end(); - else if (module == "80-sql.so" || module == "20-storage.so") - conflict = std::find(_module_list.begin(), _module_list.end(), "20-unified_sql.so") != _module_list.end(); - if (conflict) - throw msg_fmt( - "config parser: unified_sql output is incompatible with storage/sql " - "outputs"); - auto found = std::find(_module_list.begin(), _module_list.end(), module); if (found == _module_list.end()) _module_list.emplace_back(std::move(module)); diff --git a/centreon-broker/core/src/instance_broadcast.cc b/centreon-broker/core/src/instance_broadcast.cc index bfe9c05b53d..ad704037e22 100644 --- a/centreon-broker/core/src/instance_broadcast.cc +++ b/centreon-broker/core/src/instance_broadcast.cc @@ -65,7 +65,7 @@ instance_broadcast& instance_broadcast::operator=( */ void instance_broadcast::load() { io::events& e(io::events::instance()); - e.register_event(make_type(io::internal, io::events::de_instance_broadcast), + e.register_event(io::events::internal, io::events::de_instance_broadcast, "instance_broadcast", &instance_broadcast::operations, instance_broadcast::entries); } @@ -101,4 +101,4 @@ static io::data* new_instance_broadcast() { return new instance_broadcast; } io::event_info::event_operations const instance_broadcast::operations = { - &new_instance_broadcast, nullptr, nullptr}; + &new_instance_broadcast}; diff --git a/centreon-broker/core/src/io/events.cc b/centreon-broker/core/src/io/events.cc index bf5a85527d7..74b4bf66a7c 100644 --- a/centreon-broker/core/src/io/events.cc +++ b/centreon-broker/core/src/io/events.cc @@ -63,23 +63,51 @@ void events::unload() { } /** - * @brief Unregister a category. + * Register a category. * - * @param category_id Category ID. + * @param[in] name Categoy name. + * @param[in] hint Whished category ID. + * + * @return Assigned category ID. This could be different than hint. */ -void events::unregister_category(uint16_t category_id) { - for (auto it = _elements.begin(), end = _elements.end(); it != end;) { - if (category_of_type(it->first) == category_id) - it = _elements.erase(it); - else - ++it; +unsigned short events::register_category(const std::string& name, + unsigned short hint) { + if (!hint) + ++hint; + while (_elements.find(hint) != _elements.end()) { + if (!++hint) + ++hint; } + _elements[hint].name = name; + return hint; } +/** + * Unregister a category. + * + * @param[in] category_id Category ID. + */ +void events::unregister_category(unsigned short category_id) { + categories_container::iterator it(_elements.find(category_id)); + if (it != _elements.end()) + _elements.erase(it); +} + +/** + * Register an event. + * + * @param[in] category_id Category ID. Category must have been + * registered through register_category(). + * @param[in] event_id Event ID whithin the category. + * @param[in] info Information about the event. + * + * @return Event type ID. + */ /** * @brief Register an event. * - * @param category_id Category ID. + * @param category_id Category ID. Category must have been registered through + * register_category(). * @param event_id Event ID within the category. * @param name Name of the event. * @param ops event operations @@ -89,15 +117,20 @@ void events::unregister_category(uint16_t category_id) { * * @return The type of this new event. */ -uint32_t events::register_event(uint32_t type_id, +uint32_t events::register_event(unsigned short category_id, + unsigned short event_id, const std::string& name, event_info::event_operations const* ops, mapping::entry const* entries, const std::string& table_v2) { - _elements.emplace(std::piecewise_construct, - std::forward_as_tuple(type_id), - std::forward_as_tuple(name, ops, entries, table_v2)); - return type_id; + categories_container::iterator it(_elements.find(category_id)); + if (it == _elements.end()) + throw msg_fmt( + "core: could not register event '{}': category {} was not registered", + name, category_id); + int type(make_type(category_id, event_id)); + it->second.events.emplace(type, event_info(name, ops, entries, table_v2)); + return type; } /** @@ -106,9 +139,31 @@ uint32_t events::register_event(uint32_t type_id, * @param[in] type_id Type ID. */ void events::unregister_event(uint32_t type_id) { - auto it = _elements.find(type_id); - if (it != _elements.end()) - _elements.erase(it); + unsigned short category_id(category_of_type(type_id)); + categories_container::iterator itc(_elements.find(category_id)); + if (itc != _elements.end()) { + events_container::iterator ite(itc->second.events.find(type_id)); + if (ite != itc->second.events.end()) + itc->second.events.erase(ite); + } +} + +/** + * Get first iterator. + * + * @return First iterator. + */ +events::categories_container::const_iterator events::begin() const { + return _elements.begin(); +} + +/** + * Get last iterator. + * + * @return Last iterator. + */ +events::categories_container::const_iterator events::end() const { + return _elements.end(); } /** @@ -121,16 +176,25 @@ void events::unregister_event(uint32_t type_id) { events::events_container events::get_events_by_category_name( const std::string& name) const { // Special category matching all registered events. - if (name == "all") - return _elements; + if (name == "all") { + events::events_container all; + for (categories_container::const_iterator it1(_elements.begin()), + end1(_elements.end()); + it1 != end1; ++it1) + for (events_container::const_iterator it2(it1->second.events.begin()), + end2(it1->second.events.end()); + it2 != end2; ++it2) + all.insert(*it2); + return all; + } + // Category name. else { - std::unordered_map retval; - uint16_t cat = category_id(name.c_str()); - for (auto it = _elements.begin(), end = _elements.end(); it != end; ++it) { - if (category_of_type(it->first) == cat) - retval.emplace(it->first, it->second); + for (categories_container::const_iterator it(_elements.begin()), + end(_elements.end()); + it != end; ++it) { + if (it->second.name == name) + return it->second.events; } - return retval; } throw msg_fmt("core: cannot find event category '{}'", name); } @@ -142,10 +206,15 @@ events::events_container events::get_events_by_category_name( * * @return Event information structure if found, NULL otherwise. */ -const event_info* events::get_event_info(uint32_t type) { - auto it = _elements.find(type); - if (it != _elements.end()) - return &it->second; +event_info const* events::get_event_info(uint32_t type) { + std::unordered_map::const_iterator itc( + _elements.find(category_of_type(type))); + if (itc != _elements.end()) { + std::unordered_map::const_iterator ite( + itc->second.events.find(type)); + if (ite != itc->second.events.end()) + return &ite->second; + } return nullptr; } @@ -189,18 +258,25 @@ events::events_container events::get_matching_events( * Default constructor. */ events::events() { + // Register internal category. + register_category("internal", io::events::internal); + // Register instance_broadcast - register_event(make_type(io::internal, io::events::de_instance_broadcast), + register_event(io::events::internal, io::events::de_instance_broadcast, "instance_broadcast", &instance_broadcast::operations, instance_broadcast::entries); + // Register BBDO + int cat = register_category("bbdo", io::events::bbdo); + assert(cat == io::events::bbdo); + // Register BBDO events. - register_event(make_type(io::bbdo, bbdo::de_version_response), + register_event(io::events::bbdo, bbdo::de_version_response, "version_response", &bbdo::version_response::operations, bbdo::version_response::entries); - register_event(make_type(io::bbdo, bbdo::de_ack), "ack", - &bbdo::ack::operations, bbdo::ack::entries); - register_event(make_type(io::bbdo, bbdo::de_stop), "stop", + register_event(io::events::bbdo, bbdo::de_ack, "ack", &bbdo::ack::operations, + bbdo::ack::entries); + register_event(io::events::bbdo, bbdo::de_stop, "stop", &bbdo::stop::operations, bbdo::stop::entries); // Register BBDO protocol. @@ -214,4 +290,10 @@ events::events() { events::~events() { // Unregister BBDO protocol. io::protocols::instance().unreg("BBDO"); + + // Unregister category. + unregister_category(io::events::bbdo); + + // Unregister internal category. + unregister_category(io::events::internal); } diff --git a/centreon-broker/core/src/main.cc b/centreon-broker/core/src/main.cc index d03eff1089e..6615de76d5e 100644 --- a/centreon-broker/core/src/main.cc +++ b/centreon-broker/core/src/main.cc @@ -72,7 +72,7 @@ static void hup_handler(int signum) { try { log_v2::instance().apply(conf); } catch (const std::exception& e) { - log_v2::core()->error("problem while reloading cbd: {}", e.what()); + log_v2::core()->error(e.what()); } try { @@ -235,7 +235,7 @@ int main(int argc, char* argv[]) { try { log_v2::instance().apply(conf); } catch (const std::exception& e) { - log_v2::core()->error("{}", e.what()); + log_v2::core()->error(e.what()); } if (n_thread > 0 && n_thread < 100) diff --git a/centreon-broker/core/src/misc/diagnostic.cc b/centreon-broker/core/src/misc/diagnostic.cc index 93e2b062c9b..291a8cc1655 100644 --- a/centreon-broker/core/src/misc/diagnostic.cc +++ b/centreon-broker/core/src/misc/diagnostic.cc @@ -17,6 +17,7 @@ */ #include "com/centreon/broker/misc/diagnostic.hh" +#include #include #include #include @@ -24,6 +25,7 @@ #include #include #include "com/centreon/broker/config/parser.hh" +#include "com/centreon/broker/config/state.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/filesystem.hh" #include "com/centreon/broker/misc/misc.hh" @@ -229,7 +231,6 @@ void diagnostic::generate(std::vector const& cfg_files, config::parser parsr; config::state conf; try { - log_v2::core()->info("diagnostic: reading configuration file."); conf = parsr.parse(*it); } catch (std::exception const& e) { log_v2::core()->error( diff --git a/centreon-broker/core/src/misc/filesystem.cc b/centreon-broker/core/src/misc/filesystem.cc index 0c14dc0535f..fb912a1b31b 100644 --- a/centreon-broker/core/src/misc/filesystem.cc +++ b/centreon-broker/core/src/misc/filesystem.cc @@ -23,7 +23,6 @@ #include #include #include -#include #include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker; @@ -179,27 +178,3 @@ int64_t filesystem::file_size(std::string const& path) { int64_t size{file.tellg()}; return size; } - -/** - * @brief Return true if the file/directory is writable. - * - * @param name - * - * @return a boolean - */ -bool filesystem::writable(const std::string& name) { - int retval = access(name.c_str(), W_OK); - return retval == 0; -} - -/** - * @brief Return true if the file/directory is writable. - * - * @param name - * - * @return a boolean - */ -bool filesystem::readable(const std::string& name) { - int retval = access(name.c_str(), R_OK); - return retval == 0; -} diff --git a/centreon-broker/core/src/misc/global_lock.cc b/centreon-broker/core/src/misc/global_lock.cc new file mode 100644 index 00000000000..ae4797ef8a1 --- /dev/null +++ b/centreon-broker/core/src/misc/global_lock.cc @@ -0,0 +1,29 @@ +/* +** Copyright 2009-2011 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/misc/global_lock.hh" + +using namespace com::centreon::broker; + +/************************************** + * * + * Global Objects * + * * + **************************************/ + +std::mutex misc::global_lock; diff --git a/centreon-broker/core/src/misc/string.cc b/centreon-broker/core/src/misc/string.cc index 0be814c03ef..af9c17efb2d 100644 --- a/centreon-broker/core/src/misc/string.cc +++ b/centreon-broker/core/src/misc/string.cc @@ -35,7 +35,7 @@ static char const* whitespaces(" \t\r\n"); * * @return The trimming stream. */ -std::string& string::trim(std::string& str) noexcept { +std::string& string::trim(std::string& str) throw() { size_t pos(str.find_last_not_of(whitespaces)); if (pos == std::string::npos) str.clear(); @@ -82,6 +82,7 @@ std::list string::split_sv(std::string const& str, char sep) { return retval; } + std::string string::base64_encode(const std::string& str) { static const std::string b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; diff --git a/centreon-broker/core/src/modules/handle.cc b/centreon-broker/core/src/modules/handle.cc index 9588acf61e0..4f9aa373513 100644 --- a/centreon-broker/core/src/modules/handle.cc +++ b/centreon-broker/core/src/modules/handle.cc @@ -43,7 +43,7 @@ handle::~handle() noexcept { try { _close(); } catch (std::exception const& e) { - log_v2::core()->error("{}", e.what()); + log_v2::core()->error(e.what()); } catch (...) { log_v2::core()->error("modules: unknown error while unloading '{}'", _filename); diff --git a/centreon-broker/core/src/multiplexing/engine.cc b/centreon-broker/core/src/multiplexing/engine.cc index 0a39932b81b..e335d16f634 100644 --- a/centreon-broker/core/src/multiplexing/engine.cc +++ b/centreon-broker/core/src/multiplexing/engine.cc @@ -17,9 +17,11 @@ */ #include "com/centreon/broker/multiplexing/engine.hh" +#include "com/centreon/broker/log_v2.hh" #include +#include #include #include #include @@ -35,9 +37,31 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::multiplexing; // Class instance. -engine* engine::_instance{nullptr}; +engine* engine::_instance(nullptr); std::mutex engine::_load_m; +/** + * Clear events stored in the multiplexing engine. + */ +void engine::clear() { + while (!_kiew.empty()) + _kiew.pop(); +} + +/** + * Set a hook. + * + * @param[in] h Hook. + * @param[in] with_data Write data to hook. + */ +void engine::hook(hooker& h, bool with_data) { + std::lock_guard lock(_engine_m); + + _hooks.push_back({&h, with_data}); + _hooks_begin = _hooks.begin(); + _hooks_end = _hooks.end(); +} + /** * Get engine instance. * @@ -52,26 +76,11 @@ engine& engine::instance() { * Load engine instance. */ void engine::load() { - log_v2::core()->trace("multiplexing: loading engine"); std::lock_guard lk(_load_m); if (!_instance) _instance = new engine; } -/** - * Unload class instance. - */ -void engine::unload() { - log_v2::core()->trace("multiplexing: unloading engine"); - std::lock_guard lk(_load_m); - // Commit the cache file, if needed. - if (_instance && _instance->_cache_file) - _instance->_cache_file->commit(); - - delete _instance; - _instance = nullptr; -} - /** * Send an event to all subscribers. * @@ -80,54 +89,42 @@ void engine::unload() { void engine::publish(const std::shared_ptr& e) { // Lock mutex. std::lock_guard lock(_engine_m); - switch (_state) { - case stopped: - _cache_file->add(e); - _unprocessed_events++; - break; - case not_started: - _kiew.push_back(e); - break; - default: - _kiew.push_back(e); - _send_to_subscribers(); - break; - } + _publish(e); } void engine::publish(const std::list>& to_publish) { std::lock_guard lock(_engine_m); - switch (_state) { - case stopped: - for (auto& e : to_publish) { - _cache_file->add(e); - _unprocessed_events++; - } - break; - default: - for (auto& e : to_publish) - _kiew.push_back(e); - _send_to_subscribers(); - break; - } + for (auto& e : to_publish) + _publish(e); +} + +/** + * Send an event to all subscribers. It must be used from this class, and + * _engine_m must be locked previously. Otherwise use engine::publish(). + * + * @param[in] e Event to publish. + */ +void engine::_publish(std::shared_ptr const& e) { + // Store object for further processing. + _kiew.push(e); + // Processing function. + (this->*_write_func)(e); } /** - * Start multiplexing. This function gets back the retention content and - * inserts it in front of the engine's queue. Then all this content is - * published. + * Start multiplexing. */ void engine::start() { - std::lock_guard lock(_engine_m); - if (_state == not_started) { + if (_write_func != &engine::_write) { // Set writing method. - log_v2::core()->debug("multiplexing: engine starting"); - _state = running; + log_v2::perfdata()->debug("multiplexing: starting"); + _write_func = &engine::_write; stats::center::instance().update(&EngineStats::set_mode, _stats, EngineStats::WRITE); + std::lock_guard lock(_engine_m); // Local queue. - std::deque> kiew; + std::queue> kiew; // Get events from the cache file to the local queue. try { persistent_cache cache(_cache_file_path()); @@ -136,34 +133,74 @@ void engine::start() { cache.get(d); if (!d) break; - kiew.push_back(d); + kiew.push(d); } } catch (const std::exception& e) { - log_v2::core()->error("multiplexing: engine couldn't read cache file: {}", - e.what()); + log_v2::perfdata()->error("multiplexing: couldn't read cache file: {}", + e.what()); } // Copy global event queue to local queue. while (!_kiew.empty()) { - kiew.push_back(_kiew.front()); - _kiew.pop_front(); + kiew.push(_kiew.front()); + _kiew.pop(); } - // Send events queued while multiplexing was stopped. - _kiew = std::move(kiew); + // Notify hooks of multiplexing loop start. + for (std::vector>::iterator it(_hooks_begin), + end(_hooks_end); + it != end; ++it) { + it->first->starting(); + + // Read events from hook. + try { + std::shared_ptr d; + it->first->read(d); + while (d) { + _kiew.push(d); + it->first->read(d, 0); + } + } catch (const std::exception& e) { + log_v2::perfdata()->error("multiplexing: cannot read from hook: {}", + e.what()); + } + } + + // Process events from hooks. _send_to_subscribers(); + + // Send events queued while multiplexing was stopped. + while (!kiew.empty()) { + _publish(kiew.front()); + kiew.pop(); + } } - log_v2::core()->info("multiplexing: engine started"); } /** * Stop multiplexing. */ void engine::stop() { - std::unique_lock lock(_engine_m); - if (_state != stopped) { + if (_write_func != &engine::_nop) { // Notify hooks of multiplexing loop end. - log_v2::core()->debug("multiplexing: stopping engine"); + log_v2::core()->debug("multiplexing: stopping"); + std::unique_lock lock(_engine_m); + for (std::vector>::iterator it(_hooks_begin), + end(_hooks_end); + it != end; ++it) { + it->first->stopping(); + + // Read events from hook. + try { + std::shared_ptr d; + it->first->read(d); + while (d) { + _kiew.push(d); + it->first->read(d); + } + } catch (...) { + } + } do { // Process events from hooks. @@ -189,11 +226,10 @@ void engine::stop() { } // Set writing method. - _state = stopped; + _write_func = &engine::_write_to_cache_file; stats::center::instance().update(&EngineStats::set_mode, _stats, EngineStats::WRITE_TO_CACHE_FILE); } - log_v2::core()->debug("multiplexing: engine stopped"); } /** @@ -202,23 +238,49 @@ void engine::stop() { * @param[in] subscriber Subscriber. */ void engine::subscribe(muxer* subscriber) { - std::lock_guard lock(_engine_m); - log_v2::core()->trace("muxer {} subscribes to engine", subscriber->name()); + std::lock_guard lock(_muxers_m); _muxers.push_back(subscriber); } +/** + * Remove a hook. + * + * @param[in] h Hook. + */ +void engine::unhook(hooker& h) { + std::lock_guard lock(_engine_m); + for (std::vector>::iterator it(_hooks_begin); + it != _hooks.end();) + if (it->first == &h) + it = _hooks.erase(it); + else + ++it; + _hooks_begin = _hooks.begin(); + _hooks_end = _hooks.end(); +} + +/** + * Unload class instance. + */ +void engine::unload() { + std::lock_guard lk(_load_m); + // Commit the cache file, if needed. + if (_instance && _instance->_cache_file.get()) + _instance->_cache_file->commit(); + + delete _instance; + _instance = nullptr; +} + /** * Unsubscribe from the multiplexing engine. * * @param[in] subscriber Subscriber. */ void engine::unsubscribe(muxer* subscriber) { - std::lock_guard lock(_engine_m); - // std::remove(_muxers.begin(), _muxers.end(), subscriber); + std::lock_guard lock(_muxers_m); for (auto it = _muxers.begin(), end = _muxers.end(); it != end; ++it) if (*it == subscriber) { - log_v2::core()->trace("muxer {} unsubscribes to engine", - subscriber->name()); _muxers.erase(it); break; } @@ -228,10 +290,15 @@ void engine::unsubscribe(muxer* subscriber) { * Default constructor. */ engine::engine() - : _state{not_started}, + : _hooks{}, + _hooks_begin{_hooks.begin()}, + _hooks_end{_hooks.end()}, + _engine_m{}, _muxers{}, + _muxers_m{}, _stats{stats::center::instance().register_engine()}, - _unprocessed_events{0u} { + _unprocessed_events{0u}, + _write_func(&engine::_nop) { stats::center::instance().update(&EngineStats::set_mode, _stats, EngineStats::NOP); } @@ -247,23 +314,68 @@ std::string engine::_cache_file_path() const { return retval; } +/** + * Do nothing. + * + * @param[in] d Unused. + */ +void engine::_nop(std::shared_ptr const& d) { + (void)d; +} + /** * Send queued events to subscribers. */ void engine::_send_to_subscribers() { // Process all queued events. - std::deque> kiew; - std::swap(_kiew, kiew); - for (auto& e : kiew) { + std::lock_guard lock(_muxers_m); + while (!_kiew.empty()) { // Send object to every subscriber. for (muxer* m : _muxers) - m->publish(e); + m->publish(_kiew.front()); + _kiew.pop(); } } /** - * Clear events stored in the multiplexing engine. + * The real event publication is done here. This method is just called by + * the publish method. No need of a lock, it is already owned by the publish + * method. + * + * @param[in] e Data to publish. */ -void engine::clear() { - _kiew.clear(); +void engine::_write(std::shared_ptr const& e) { + // Send object to every hook. + for (std::vector>::iterator it(_hooks_begin), + end(_hooks_end); + it != end; ++it) + if (it->second) { + it->first->write(e); + std::shared_ptr d; + it->first->read(d); + while (d) { + _kiew.push(d); + it->first->read(d); + } + } + + // Send events to subscribers. + _send_to_subscribers(); +} + +/** + * Write to a cache file that will be played back at startup. + * + * @param[in] d Data to write. + */ +void engine::_write_to_cache_file(std::shared_ptr const& d) { + try { + if (_cache_file) { + _cache_file->add(d); + _unprocessed_events++; + } + } catch (const std::exception& e) { + log_v2::perfdata()->error("multiplexing: could not write to cache file: {}", + e.what()); + } } diff --git a/centreon-broker/core/src/multiplexing/hooker.cc b/centreon-broker/core/src/multiplexing/hooker.cc new file mode 100644 index 00000000000..2cb9a724e12 --- /dev/null +++ b/centreon-broker/core/src/multiplexing/hooker.cc @@ -0,0 +1,47 @@ +/* +** Copyright 2011,2020 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/multiplexing/hooker.hh" +#include "com/centreon/broker/multiplexing/engine.hh" + +using namespace com::centreon::broker::multiplexing; + +/** + * Default constructor. + */ +hooker::hooker() : io::stream("hooker"), _registered{false} {} + +/** + * Destructor. + */ +hooker::~hooker() noexcept {} + +/** + * Enable or disable hooking. + * + * @param[in] should_hook Set to true if hooker should hook. + */ +void hooker::hook(bool should_hook) { + if (_registered && !should_hook) { + engine::instance().unhook(*this); + _registered = false; + } else if (!_registered && should_hook) { + engine::instance().hook(*this); + _registered = true; + } +} diff --git a/centreon-broker/core/src/multiplexing/muxer.cc b/centreon-broker/core/src/multiplexing/muxer.cc index b25f706c11b..03e6b18a4f9 100644 --- a/centreon-broker/core/src/multiplexing/muxer.cc +++ b/centreon-broker/core/src/multiplexing/muxer.cc @@ -19,6 +19,8 @@ #include "com/centreon/broker/multiplexing/muxer.hh" #include +#include +#include #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/exceptions/shutdown.hh" @@ -27,6 +29,7 @@ #include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/multiplexing/engine.hh" +#include "com/centreon/broker/persistent_file.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::multiplexing; @@ -477,7 +480,3 @@ void muxer::remove_queue_files() { persistent_file file(_queue_file()); file.remove_all_files(); } - -const std::string& muxer::name() const { - return _name; -} diff --git a/centreon-broker/core/src/mysql.cc b/centreon-broker/core/src/mysql.cc index 582f7d7fa15..64bf1fb5576 100644 --- a/centreon-broker/core/src/mysql.cc +++ b/centreon-broker/core/src/mysql.cc @@ -23,6 +23,8 @@ using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::database; +std::once_flag init_flag; + /** * Constructor. * diff --git a/centreon-broker/core/src/mysql_connection.cc b/centreon-broker/core/src/mysql_connection.cc index a066822102f..ab6be074166 100644 --- a/centreon-broker/core/src/mysql_connection.cc +++ b/centreon-broker/core/src/mysql_connection.cc @@ -78,11 +78,6 @@ bool mysql_connection::_server_error(int code) const { void mysql_connection::_prepare_connection() { mysql_set_character_set(_conn, "utf8mb4"); - /* This is to set a timeout for the mysql_ping() function that can hang - * sometimes */ - uint32_t timeout = 5; - mysql_optionsv(_conn, MYSQL_OPT_READ_TIMEOUT, (void*)&timeout); - if (_qps > 1) mysql_autocommit(_conn, 0); else @@ -155,7 +150,6 @@ bool mysql_connection::_try_to_reconnect() { //update_stats(); return false; } - _last_access = std::time(nullptr); _prepare_connection(); @@ -254,8 +248,6 @@ void mysql_connection::_commit(mysql_task* t) { log_v2::sql()->error("mysql_connection: {}", err_msg); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } - if (res == 0) - _last_access = std::time(nullptr); } else res = 0; @@ -628,7 +620,6 @@ void mysql_connection::_run() { _start_condition.notify_all(); return; } - _last_access = std::time(nullptr); } if (config::applier::mode == config::applier::finished) { @@ -654,23 +645,9 @@ void mysql_connection::_run() { _tasks_count = 0; //update_stats(); _tasks_condition.wait( - lock, - [this] { return _finish_asked || !_tasks_list.empty(); }); - - std::time_t now = std::time(nullptr);; - if (_tasks_list.empty()) + lock, [this] { return _finish_asked || !_tasks_list.empty(); }); + if (_tasks_list.empty()) { _state = finished; - else if (now >= _last_access + 30) { - lock.unlock(); - log_v2::sql()->trace("SQL: performing mysql_ping."); - if (mysql_ping(_conn)) { - if (!_try_to_reconnect()) - log_v2::sql()->error("SQL: Reconnection failed."); - } else { - log_v2::sql()->trace("SQL: connection always alive"); - _last_access = now; - } - lock.lock(); } continue; } @@ -722,7 +699,6 @@ mysql_connection::mysql_connection(database_config const& db_cfg) _finish_asked(false), _tasks_count(0), _need_commit(false), - _last_access{0}; _host(db_cfg.get_host()), _socket(db_cfg.get_socket()), _user(db_cfg.get_user()), diff --git a/centreon-broker/core/src/mysql_manager.cc b/centreon-broker/core/src/mysql_manager.cc index eaa4e732ea9..7190e48fa45 100644 --- a/centreon-broker/core/src/mysql_manager.cc +++ b/centreon-broker/core/src/mysql_manager.cc @@ -122,7 +122,7 @@ void mysql_manager::clear() { conn->finish(); } catch (const std::exception& e) { log_v2::sql()->info("mysql_manager: Unable to stop a connection: {}", - e.what()); + e.what()); } } log_v2::sql()->debug("mysql_manager: clear finished"); diff --git a/centreon-broker/core/src/processing/failover.cc b/centreon-broker/core/src/processing/failover.cc index ea9fcbe1e9f..31a901141f4 100644 --- a/centreon-broker/core/src/processing/failover.cc +++ b/centreon-broker/core/src/processing/failover.cc @@ -81,8 +81,7 @@ void failover::exit() { _should_exit = true; log_v2::processing()->trace("Waiting for {} to be stopped", _name); - _state_cv.wait( - lck, [this] { return _state == stopped || _state == not_started; }); + _state_cv.wait(lck, [this] { return _state == stopped || _state == not_started; }); } if (_thread.joinable()) _thread.join(); @@ -359,8 +358,7 @@ void failover::_run() { try { ack_events = _stream->stop(); } catch (const std::exception& e) { - log_v2::core()->error("Failed to send stop event to stream: {}", - e.what()); + log_v2::core()->error("Failed to send stop event to stream: {}", e.what()); } _subscriber->get_muxer().ack_events(ack_events); std::lock_guard stream_lock(_stream_m); @@ -381,10 +379,9 @@ void failover::_run() { { int32_t ack_events; try { - ack_events = _stream->stop(); + ack_events = _stream->stop(); } catch (const std::exception& e) { - log_v2::core()->error("Failed to send stop event to stream: {}", - e.what()); + log_v2::core()->error("Failed to send stop event to stream: {}", e.what()); } _subscriber->get_muxer().ack_events(ack_events); std::lock_guard stream_lock(_stream_m); @@ -404,10 +401,9 @@ void failover::_run() { // If ack_events is not zero, then we will store data twice int32_t ack_events; try { - ack_events = _stream->stop(); + ack_events = _stream->stop(); } catch (const std::exception& e) { - log_v2::core()->error("Failed to send stop event to stream: {}", - e.what()); + log_v2::core()->error("Failed to send stop event to stream: {}", e.what()); } _subscriber->get_muxer().ack_events(ack_events); _stream.reset(); diff --git a/centreon-broker/core/src/stats/center.cc b/centreon-broker/core/src/stats/center.cc index dbdbd53c90b..9a3f31a5802 100644 --- a/centreon-broker/core/src/stats/center.cc +++ b/centreon-broker/core/src/stats/center.cc @@ -23,9 +23,9 @@ #include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/config/applier/state.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/misc/filesystem.hh" #include "com/centreon/broker/version.hh" +#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::stats; @@ -87,7 +87,9 @@ center::~center() { * a last action and wait it is over. */ std::promise p; std::future f{p.get_future()}; - _strand.post([&p] { p.set_value(true); }); + _strand.post([&p] { + p.set_value(true); + }); f.get(); pool::instance().stop_stats(); } @@ -126,9 +128,10 @@ bool center::unregister_mysql_connection(SqlConnectionStats* connection) { std::promise p; std::future retval = p.get_future(); _strand.post([this, &p, connection] { - for (auto it = _stats.mutable_connections()->begin(), - end = _stats.mutable_connections()->end(); - it != end; ++it) { + for (auto + it = _stats.mutable_connections()->begin(), + end = _stats.mutable_connections()->end(); + it != end; ++it) { if (&(*it) == connection) { _stats.mutable_connections()->erase(it); break; @@ -251,7 +254,7 @@ bool center::unregister_mysql_connection(SqlConnectionStats* connection) { * * @return A pointer to the conflict_manager statistics. */ -ConflictManagerStats* center::register_conflict_manager() { + ConflictManagerStats* center::register_conflict_manager() { std::promise p; std::future retval = p.get_future(); _strand.post([this, &p] { @@ -354,8 +357,8 @@ void center::get_sql_connection_size(GenericSize* response) { std::promise p; std::future done = p.get_future(); _strand.post([&s = this->_stats, &p, response] { - response->set_size(s.connections().size()); - p.set_value(true); + response->set_size(s.connections().size()); + p.set_value(true); }); // We wait for the response. @@ -366,8 +369,8 @@ void center::get_conflict_manager_stats(ConflictManagerStats* response) { std::promise p; std::future done = p.get_future(); _strand.post([&s = this->_stats, &p, response] { - *response = s.conflict_manager(); - p.set_value(true); + *response = s.conflict_manager(); + p.set_value(true); }); // We wait for the response. diff --git a/centreon-broker/core/src/time/timerange.cc b/centreon-broker/core/src/time/timerange.cc index a4485107981..e93da3b38ab 100644 --- a/centreon-broker/core/src/time/timerange.cc +++ b/centreon-broker/core/src/time/timerange.cc @@ -17,10 +17,10 @@ */ #include "com/centreon/broker/time/timerange.hh" -#include #include -#include "com/centreon/broker/log_v2.hh" +#include #include "com/centreon/broker/misc/string.hh" +#include "com/centreon/broker/log_v2.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::time; @@ -199,38 +199,31 @@ static bool _build_time_t(const fmt::string_view& time_str, uint64_t& ret) { char* endptr1; // move cursor while we meet blanks - while (std::isspace(*begin_str)) { - begin_str++; - } + while (std::isspace(*begin_str)) { begin_str++; } uint64_t hours = strtoull(begin_str, &endptr, 10); - + if (endptr == begin_str || endptr + 2 >= endc || *endptr != ':') { - log_v2::core()->error( - "parser timeranges: error while reading hours '{}' at {}.", begin_str, - endptr - begin_str); + log_v2::core()->error("parser timeranges: error while reading hours '{}' at {}.", + begin_str, endptr - begin_str); return false; } uint64_t minutes = strtoull(endptr + 1, &endptr1, 10); if (endptr1 == endptr + 1) { - log_v2::core()->error( - "parser timeranges: error while reading minutes '{}' at {}.", begin_str, - endptr1 - begin_str); + log_v2::core()->error("parser timeranges: error while reading minutes '{}' at {}.", + begin_str, endptr1 - begin_str); return false; } // move cursor while we meet blanks - while (endptr1 < endc && std::isspace(*endptr1)) { - endptr1++; - } + while (endptr1 < endc && std::isspace(*endptr1)) { endptr1++; } if (endptr1 != endc) { - log_v2::core()->error( - "parser timeranges: error while reading end " - "of your timerange '{}' at {}.", - begin_str, endptr1 - begin_str); + log_v2::core()->error("parser timeranges: error while reading end " + "of your timerange '{}' at {}.", begin_str, + endptr1 - begin_str); return false; } diff --git a/centreon-broker/core/test/bbdo/category.cc b/centreon-broker/core/test/bbdo/category.cc index 7e2677b435c..f4d27a2da41 100644 --- a/centreon-broker/core/test/bbdo/category.cc +++ b/centreon-broker/core/test/bbdo/category.cc @@ -31,12 +31,12 @@ using namespace com::centreon::broker; * @param BbdoCategory */ TEST(CategoryTest, BbdoCategory) { - ASSERT_EQ(io::neb, 1); - ASSERT_EQ(io::bbdo, 2); - ASSERT_EQ(io::storage, 3); - ASSERT_EQ(io::dumper, 5); - ASSERT_EQ(io::bam, 6); - ASSERT_EQ(io::extcmd, 7); - ASSERT_EQ(io::generator, 8); - ASSERT_EQ(io::internal, 65535); + ASSERT_EQ(io::events::neb, 1); + ASSERT_EQ(io::events::bbdo, 2); + ASSERT_EQ(io::events::storage, 3); + ASSERT_EQ(io::events::dumper, 5); + ASSERT_EQ(io::events::bam, 6); + ASSERT_EQ(io::events::extcmd, 7); + ASSERT_EQ(io::events::generator, 8); + ASSERT_EQ(io::events::internal, 65535); } diff --git a/centreon-broker/core/test/bbdo/output.cc b/centreon-broker/core/test/bbdo/output.cc index 5de4350d711..f83786a2952 100644 --- a/centreon-broker/core/test/bbdo/output.cc +++ b/centreon-broker/core/test/bbdo/output.cc @@ -166,7 +166,7 @@ TEST_F(OutputTest, WriteLongService) { ASSERT_EQ(mem1.size(), 70285u); // The buffer is too big. So it is splitted into several -- here 2 -- buffers. - // They are concatenated, keeped into the same block, but a new header is + // The are concatenated, keeped into the same block, but a new header is // inserted in the "middle" of the buffer: Something like this: // HEADER | BUFFER1 | HEADER | BUFFER2 ASSERT_EQ(htons(*reinterpret_cast(&mem1[0] + 2)), 0xffffu); diff --git a/centreon-broker/core/test/compression/stream/memory_stream.hh b/centreon-broker/core/test/compression/stream/memory_stream.hh index 6546e693c01..9625dd2ec31 100644 --- a/centreon-broker/core/test/compression/stream/memory_stream.hh +++ b/centreon-broker/core/test/compression/stream/memory_stream.hh @@ -51,8 +51,7 @@ class CompressionStreamMemoryStream : public com::centreon::broker::io::stream { return true; } - int write( - std::shared_ptr const& d) override { + int write(std::shared_ptr const& d) override { using namespace com::centreon::broker; if (!d || d->type() != io::raw::static_type()) throw com::centreon::exceptions::msg_fmt("invalid data sent to {}", diff --git a/centreon-broker/core/test/config/parser.cc b/centreon-broker/core/test/config/parser.cc index 31cd6cfa48f..85d2d07c066 100644 --- a/centreon-broker/core/test/config/parser.cc +++ b/centreon-broker/core/test/config/parser.cc @@ -187,11 +187,11 @@ TEST(parser, global) { " \"poller_id\": 1,\n" " \"poller_name\": \"Central\",\n" " \"module_directory\": " - "\"/etc\",\n" + "\"/usr/share/centreon/lib/centreon-broker\",\n" " \"log_timestamp\": true,\n" " \"event_queue_max_size\": 100000,\n" " \"command_file\": \"/var/lib/centreon-broker/command.sock\",\n" - " \"cache_directory\": \"/tmp\",\n" + " \"cache_directory\": \"/var/lib/centreon-broker\",\n" " \"log_thread_id\": false,\n" " \"log\": []\n" " }\n" @@ -227,11 +227,11 @@ TEST(parser, log) { " \"poller_id\": 1,\n" " \"poller_name\": \"Central\",\n" " \"module_directory\": " - "\"/etc\",\n" + "\"/usr/share/centreon/lib/centreon-broker\",\n" " \"log_timestamp\": true,\n" " \"event_queue_max_size\": 100000,\n" " \"command_file\": \"/var/lib/centreon-broker/command.sock\",\n" - " \"cache_directory\": \"/tmp\",\n" + " \"cache_directory\": \"/var/lib/centreon-broker\",\n" " \"log\": {\n" " \"directory\": \"/tmp\"\n" " }\n" @@ -257,10 +257,10 @@ TEST(parser, log) { ASSERT_EQ(s.broker_id(), 1); ASSERT_EQ(s.broker_name(), "central-broker-master"); ASSERT_EQ(s.poller_id(), 1); - ASSERT_EQ(s.module_directory(), "/etc"); + ASSERT_EQ(s.module_directory(), "/usr/share/centreon/lib/centreon-broker"); ASSERT_EQ(s.event_queue_max_size(), 100000); ASSERT_EQ(s.command_file(), "/var/lib/centreon-broker/command.sock"); - ASSERT_EQ(s.cache_directory(), "/tmp/"); + ASSERT_EQ(s.cache_directory(), "/var/lib/centreon-broker/"); ASSERT_EQ(s.log_conf().directory, "/tmp"); ASSERT_EQ(s.log_conf().max_size, 0u); } @@ -283,11 +283,11 @@ TEST(parser, logBadFilename) { " \"poller_id\": 1,\n" " \"poller_name\": \"Central\",\n" " \"module_directory\": " - "\"/etc\",\n" + "\"/usr/share/centreon/lib/centreon-broker\",\n" " \"log_timestamp\": true,\n" " \"event_queue_max_size\": 100000,\n" " \"command_file\": \"/var/lib/centreon-broker/command.sock\",\n" - " \"cache_directory\": \"/tmp\",\n" + " \"cache_directory\": \"/var/lib/centreon-broker\",\n" " \"log_thread_id\": false,\n" " \"log\": {\n" " \"filename\": \"toto/titi\"\n" @@ -328,14 +328,13 @@ TEST(parser, logDefaultDir) { " \"poller_id\": 1,\n" " \"poller_name\": \"Central\",\n" " \"module_directory\": " - "\"/etc\",\n" + "\"/usr/share/centreon/lib/centreon-broker\",\n" " \"log_timestamp\": true,\n" " \"event_queue_max_size\": 100000,\n" " \"command_file\": \"/var/lib/centreon-broker/command.sock\",\n" - " \"cache_directory\": \"/tmp\",\n" + " \"cache_directory\": \"/var/lib/centreon-broker\",\n" " \"log_thread_id\": false,\n" " \"log\": {\n" - " \"directory\": \"/tmp\",\n" " \"filename\": \"toto\",\n" " \"max_size\": \"12345\",\n" " \"loggers\": {\n" @@ -359,7 +358,7 @@ TEST(parser, logDefaultDir) { // Remove temporary file. ::remove(config_file.c_str()); - ASSERT_EQ(s.log_conf().directory, "/tmp"); + ASSERT_EQ(s.log_conf().directory, "/var/log/centreon-broker"); ASSERT_EQ(s.log_conf().filename, "toto"); ASSERT_EQ(s.log_conf().max_size, 12345u); ASSERT_EQ(s.log_conf().loggers.size(), 2u); @@ -383,11 +382,11 @@ TEST(parser, logBadMaxSize) { " \"poller_id\": 1,\n" " \"poller_name\": \"Central\",\n" " \"module_directory\": " - "\"/etc\",\n" + "\"/usr/share/centreon/lib/centreon-broker\",\n" " \"log_timestamp\": true,\n" " \"event_queue_max_size\": 100000,\n" " \"command_file\": \"/var/lib/centreon-broker/command.sock\",\n" - " \"cache_directory\": \"/tmp\",\n" + " \"cache_directory\": \"/var/lib/centreon-broker\",\n" " \"log_thread_id\": false,\n" " \"log\": {\n" " \"filename\": \"toto\"\n" @@ -429,11 +428,11 @@ TEST(parser, logBadLoggers) { " \"poller_id\": 1,\n" " \"poller_name\": \"Central\",\n" " \"module_directory\": " - "\"/etc\",\n" + "\"/usr/share/centreon/lib/centreon-broker\",\n" " \"log_timestamp\": true,\n" " \"event_queue_max_size\": 100000,\n" " \"command_file\": \"/var/lib/centreon-broker/command.sock\",\n" - " \"cache_directory\": \"/tmp\",\n" + " \"cache_directory\": \"/var/lib/centreon-broker\",\n" " \"log_thread_id\": false,\n" " \"log\": {\n" " \"filename\": \"toto\"\n" @@ -476,11 +475,11 @@ TEST(parser, logBadLogger) { " \"poller_id\": 1,\n" " \"poller_name\": \"Central\",\n" " \"module_directory\": " - "\"/etc\",\n" + "\"/usr/share/centreon/lib/centreon-broker\",\n" " \"log_timestamp\": true,\n" " \"event_queue_max_size\": 100000,\n" " \"command_file\": \"/var/lib/centreon-broker/command.sock\",\n" - " \"cache_directory\": \"/tmp\",\n" + " \"cache_directory\": \"/var/lib/centreon-broker\",\n" " \"log_thread_id\": false,\n" " \"log\": {\n" " \"filename\": \"toto\"\n" @@ -523,14 +522,13 @@ TEST(parser, logWithNullLoggers) { " \"poller_id\": 1,\n" " \"poller_name\": \"Central\",\n" " \"module_directory\": " - "\"/etc\",\n" + "\"/usr/share/centreon/lib/centreon-broker\",\n" " \"log_timestamp\": true,\n" " \"event_queue_max_size\": 100000,\n" " \"command_file\": \"/var/lib/centreon-broker/command.sock\",\n" - " \"cache_directory\": \"/tmp\",\n" + " \"cache_directory\": \"/var/lib/centreon-broker\",\n" " \"log_thread_id\": false,\n" " \"log\": {\n" - " \"directory\": \"/tmp\",\n" " \"loggers\": null\n" " }\n" " }\n" @@ -550,340 +548,3 @@ TEST(parser, logWithNullLoggers) { // Remove temporary file. ::remove(config_file.c_str()); } - -TEST(parser, unifiedSql) { - // File name. - std::string config_file(misc::temp_path()); - - // Open file. - FILE* file_stream(fopen(config_file.c_str(), "w")); - if (!file_stream) - throw msg_fmt("could not open '{}'", config_file); - // Data. - std::string data{ - "{" - " \"centreonBroker\": {\n" - " \"broker_id\": 1,\n" - " \"broker_name\": \"central-broker-master\",\n" - " \"poller_id\": 1,\n" - " \"bbdo_version\": \"3.1.2\",\n" - " \"poller_name\": \"Central\",\n" - " \"module_directory\": " - "\"/etc\",\n" - " \"log_timestamp\": true,\n" - " \"log_thread_id\": false,\n" - " \"event_queue_max_size\": 100000,\n" - " \"command_file\": \"/var/lib/centreon-broker/command.sock\",\n" - " \"cache_directory\": \"/tmp\",\n" - " \"input\": [\n" - " {\n" - " \"name\": \"connection-to-local\",\n" - " \"port\": \"5668\",\n" - " \"protocol\": \"bbdo\",\n" - " \"tls\": \"no\",\n" - " \"private_key\": \"/etc/centreon-broker/server.key\",\n" - " \"public_cert\": \"/etc/centreon-broker/server.crt\",\n" - " \"ca_certificate\": " - "\"/etc/centreon-broker/client.crt\",\n" - " \"negotiation\": \"yes\",\n" - " \"buffering_timeout\": \"0\",\n" - " \"retry_interval\": \"60\",\n" - " \"one_peer_retention_mode\": \"no\",\n" - " \"compression\": \"no\",\n" - " \"type\": \"ipv4\"\n" - " }\n" - " ],\n" - " \"logger\": [\n" - " {\n" - " \"name\": " - "\"/var/log/centreon-broker/central-broker-master.log\",\n" - " \"config\": \"yes\",\n" - " \"debug\": \"no\",\n" - " \"error\": \"yes\",\n" - " \"info\": \"no\",\n" - " \"level\": \"low\",\n" - " \"type\": \"file\"\n" - " }\n" - " ],\n" - " \"output\": [\n" - " {\n" - " \"type\": \"unified_sql\",\n" - " \"name\": \"central-broker-master-sql\",\n" - " \"db_type\": \"mysql\",\n" - " \"db_host\": \"localhost\",\n" - " \"db_port\": \"3306\",\n" - " \"db_user\": \"centreon\",\n" - " \"db_password\": \"centreon\",\n" - " \"db_name\": \"centreon_storage\",\n" - " \"interval\": \"60\",\n" - " \"length\": \"15552000\",\n" - " \"queries_per_transaction\": \"20000\",\n" - " \"connections_count\": \"4\",\n" - " \"read_timeout\": \"60\",\n" - " \"buffering_timeout\": \"0\",\n" - " \"retry_interval\": \"60\",\n" - " \"check_replication\": \"no\",\n" - " \"store_in_data_bin\": \"yes\",\n" - " \"insert_in_index_data\": \"1\"\n" - " },\n" - " {\n" - " \"name\": \"centreon-broker-master-rrd\",\n" - " \"port\": \"5670\",\n" - " \"host\": \"localhost\",\n" - " \"protocol\": \"bbdo\",\n" - " \"tls\": \"no\",\n" - " \"private_key\": \"/etc/centreon-broker/client.key\",\n" - " \"public_cert\": \"/etc/centreon-broker/client.crt\",\n" - " \"ca_certificate\": " - "\"/etc/centreon-broker/server.crt\",\n" - " \"negotiation\": \"yes\",\n" - " \"buffering_timeout\": \"0\",\n" - " \"retry_interval\": \"60\",\n" - " \"one_peer_retention_mode\": \"no\",\n" - " \"compression\": \"no\",\n" - " \"type\": \"ipv4\"\n" - " },\n" - " {\n" - " \"name\": \"centreon-bam-monitoring\",\n" - " \"cache\": \"yes\",\n" - " \"check_replication\": \"no\",\n" - " \"command_file\": " - "\"/var/lib/centreon-engine/rw/centengine.cmd\",\n" - " \"db_host\": \"localhost\",\n" - " \"db_name\": \"centreon\",\n" - " \"db_password\": \"centreon\",\n" - " \"db_port\": \"3306\",\n" - " \"db_type\": \"mysql\",\n" - " \"db_user\": \"centreon\",\n" - " \"queries_per_transaction\": \"0\",\n" - " \"storage_db_name\": \"centreon_storage\",\n" - " \"type\": \"bam\"\n" - " },\n" - " {\n" - " \"name\": \"centreon-bam-reporting\",\n" - " \"filters\": {\n" - " \"category\": [\n" - " \"bam\"\n" - " ]\n" - " },\n" - " \"check_replication\": \"no\",\n" - " \"db_host\": \"localhost\",\n" - " \"db_name\": \"centreon_storage\",\n" - " \"db_password\": \"centreon\",\n" - " \"db_port\": \"3306\",\n" - " \"db_type\": \"mysql\",\n" - " \"db_user\": \"centreon\",\n" - " \"queries_per_transaction\": \"0\",\n" - " \"type\": \"bam_bi\"\n" - " },\n" - " {\n" - " \"name\": \"test-cache\",\n" - " \"path\": \"/usr/share/centreon-broker/lua/test.lua\",\n" - " \"type\": \"lua\"\n" - " }\n" - " ],\n" - " \"stats\": [\n" - " {\n" - " \"type\": \"stats\",\n" - " \"name\": \"central-broker-master-stats\",\n" - " \"json_fifo\": " - "\"/var/lib/centreon-broker/central-broker-master-stats.json\"\n" - " }\n" - " ],\n" - " \"grpc\": {\n" - " \"port\": 51001\n" - " }\n" - " }\n" - "}"}; - - // Write data. - if (fwrite(data.c_str(), data.size(), 1, file_stream) != 1) - throw msg_fmt("could not write content of '{}'", config_file); - - // Close file. - fclose(file_stream); - - // Parse. - config::parser p; - auto retval = p.parse(config_file); - ASSERT_EQ(std::get<0>(retval.bbdo_version()), 3u); - ASSERT_EQ(std::get<1>(retval.bbdo_version()), 1u); - ASSERT_EQ(std::get<2>(retval.bbdo_version()), 2u); - // Remove temporary file. - ::remove(config_file.c_str()); -} - -// UnifiedSql is not compatible with storage/sql. The parser returns an error. -TEST(parser, unifiedSqlVsStorageSql) { - // File name. - std::string config_file(misc::temp_path()); - - // Open file. - FILE* file_stream(fopen(config_file.c_str(), "w")); - if (!file_stream) - throw msg_fmt("could not open '{}'", config_file); - // Data. - std::string data{ - "{" - " \"centreonBroker\": {\n" - " \"broker_id\": 1,\n" - " \"broker_name\": \"central-broker-master\",\n" - " \"poller_id\": 1,\n" - " \"bbdo_version\": \"3.1.2\",\n" - " \"poller_name\": \"Central\",\n" - " \"module_directory\": " - "\"/etc\",\n" - " \"log_timestamp\": true,\n" - " \"log_thread_id\": false,\n" - " \"event_queue_max_size\": 100000,\n" - " \"command_file\": \"/var/lib/centreon-broker/command.sock\",\n" - " \"cache_directory\": \"/tmp\",\n" - " \"input\": [\n" - " {\n" - " \"name\": \"connection-to-local\",\n" - " \"port\": \"5668\",\n" - " \"protocol\": \"bbdo\",\n" - " \"tls\": \"no\",\n" - " \"private_key\": \"/etc/centreon-broker/server.key\",\n" - " \"public_cert\": \"/etc/centreon-broker/server.crt\",\n" - " \"ca_certificate\": " - "\"/etc/centreon-broker/client.crt\",\n" - " \"negotiation\": \"yes\",\n" - " \"buffering_timeout\": \"0\",\n" - " \"retry_interval\": \"60\",\n" - " \"one_peer_retention_mode\": \"no\",\n" - " \"compression\": \"no\",\n" - " \"type\": \"ipv4\"\n" - " }\n" - " ],\n" - " \"logger\": [\n" - " {\n" - " \"name\": " - "\"/var/log/centreon-broker/central-broker-master.log\",\n" - " \"config\": \"yes\",\n" - " \"debug\": \"no\",\n" - " \"error\": \"yes\",\n" - " \"info\": \"no\",\n" - " \"level\": \"low\",\n" - " \"type\": \"file\"\n" - " }\n" - " ],\n" - " \"output\": [\n" - " {\n" - " \"name\": \"central-broker-master-sql\",\n" - " \"db_type\": \"mysql\",\n" - " \"retry_interval\": \"5\",\n" - " \"buffering_timeout\": \"0\",\n" - " \"db_host\": \"1.2.3.4\",\n" - " \"db_port\": \"3306\",\n" - " \"db_user\": \"centreon\",\n" - " \"db_password\": \"centreon\",\n" - " \"db_name\": \"centreon_storage\",\n" - " \"queries_per_transaction\": \"1000\",\n" - " \"connections_count\": \"3\",\n" - " \"read_timeout\": \"1\",\n" - " \"type\": \"sql\"\n" - " },\n" - " {\n" - " \"type\": \"unified_sql\",\n" - " \"name\": \"central-broker-master-sql\",\n" - " \"db_type\": \"mysql\",\n" - " \"db_host\": \"localhost\",\n" - " \"db_port\": \"3306\",\n" - " \"db_user\": \"centreon\",\n" - " \"db_password\": \"centreon\",\n" - " \"db_name\": \"centreon_storage\",\n" - " \"interval\": \"60\",\n" - " \"length\": \"15552000\",\n" - " \"queries_per_transaction\": \"20000\",\n" - " \"connections_count\": \"4\",\n" - " \"read_timeout\": \"60\",\n" - " \"buffering_timeout\": \"0\",\n" - " \"retry_interval\": \"60\",\n" - " \"check_replication\": \"no\",\n" - " \"store_in_data_bin\": \"yes\",\n" - " \"insert_in_index_data\": \"1\"\n" - " },\n" - " {\n" - " \"name\": \"centreon-broker-master-rrd\",\n" - " \"port\": \"5670\",\n" - " \"host\": \"localhost\",\n" - " \"protocol\": \"bbdo\",\n" - " \"tls\": \"no\",\n" - " \"private_key\": \"/etc/centreon-broker/client.key\",\n" - " \"public_cert\": \"/etc/centreon-broker/client.crt\",\n" - " \"ca_certificate\": " - "\"/etc/centreon-broker/server.crt\",\n" - " \"negotiation\": \"yes\",\n" - " \"buffering_timeout\": \"0\",\n" - " \"retry_interval\": \"60\",\n" - " \"one_peer_retention_mode\": \"no\",\n" - " \"compression\": \"no\",\n" - " \"type\": \"ipv4\"\n" - " },\n" - " {\n" - " \"name\": \"centreon-bam-monitoring\",\n" - " \"cache\": \"yes\",\n" - " \"check_replication\": \"no\",\n" - " \"command_file\": " - "\"/var/lib/centreon-engine/rw/centengine.cmd\",\n" - " \"db_host\": \"localhost\",\n" - " \"db_name\": \"centreon\",\n" - " \"db_password\": \"centreon\",\n" - " \"db_port\": \"3306\",\n" - " \"db_type\": \"mysql\",\n" - " \"db_user\": \"centreon\",\n" - " \"queries_per_transaction\": \"0\",\n" - " \"storage_db_name\": \"centreon_storage\",\n" - " \"type\": \"bam\"\n" - " },\n" - " {\n" - " \"name\": \"centreon-bam-reporting\",\n" - " \"filters\": {\n" - " \"category\": [\n" - " \"bam\"\n" - " ]\n" - " },\n" - " \"check_replication\": \"no\",\n" - " \"db_host\": \"localhost\",\n" - " \"db_name\": \"centreon_storage\",\n" - " \"db_password\": \"centreon\",\n" - " \"db_port\": \"3306\",\n" - " \"db_type\": \"mysql\",\n" - " \"db_user\": \"centreon\",\n" - " \"queries_per_transaction\": \"0\",\n" - " \"type\": \"bam_bi\"\n" - " },\n" - " {\n" - " \"name\": \"test-cache\",\n" - " \"path\": \"/usr/share/centreon-broker/lua/test.lua\",\n" - " \"type\": \"lua\"\n" - " }\n" - " ],\n" - " \"stats\": [\n" - " {\n" - " \"type\": \"stats\",\n" - " \"name\": \"central-broker-master-stats\",\n" - " \"json_fifo\": " - "\"/var/lib/centreon-broker/central-broker-master-stats.json\"\n" - " }\n" - " ],\n" - " \"grpc\": {\n" - " \"port\": 51001\n" - " }\n" - " }\n" - "}"}; - - // Write data. - if (fwrite(data.c_str(), data.size(), 1, file_stream) != 1) - throw msg_fmt("could not write content of '{}'", config_file); - - // Close file. - fclose(file_stream); - - // Parse. - config::parser p; - ASSERT_THROW(p.parse(config_file), std::exception); - // Remove temporary file. - ::remove(config_file.c_str()); -} diff --git a/centreon-broker/core/test/misc/perfdata.cc b/centreon-broker/core/test/misc/perfdata.cc deleted file mode 100644 index bfc70e7eb84..00000000000 --- a/centreon-broker/core/test/misc/perfdata.cc +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - * - */ - -#include -#include - -#include -#include - -#include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/misc/misc.hh" - -using namespace com::centreon::broker; - -/** - * Check that the perfdata assignment operator works properly. - */ -TEST(MiscPerfdata, Assign) { - // First object. - misc::perfdata p1; - p1.critical(42.0); - p1.critical_low(-456.032); - p1.critical_mode(false); - p1.max(76.3); - p1.min(567.2); - p1.name("foo"); - p1.unit("bar"); - p1.value(52189.912); - p1.value_type(misc::perfdata::counter); - p1.warning(4548.0); - p1.warning_low(42.42); - p1.warning_mode(true); - - // Second object. - misc::perfdata p2; - p2.critical(2345678.9672374); - p2.critical_low(-3284523786.8923); - p2.critical_mode(true); - p2.max(834857.9023); - p2.min(348.239479); - p2.name("merethis"); - p2.unit("centreon"); - p2.value(8374598345.234); - p2.value_type(misc::perfdata::absolute); - p2.warning(0.823745784); - p2.warning_low(NAN); - p2.warning_mode(false); - - // Assignment. - p2 = p1; - - // Change first object. - p1.critical(9432.5); - p1.critical_low(1000.0001); - p1.critical_mode(true); - p1.max(123.0); - p1.min(843.876); - p1.name("baz"); - p1.unit("qux"); - p1.value(3485.9); - p1.value_type(misc::perfdata::derive); - p1.warning(3612.0); - p1.warning_low(-987579.0); - p1.warning_mode(false); - - // Check objects properties values. - ASSERT_FALSE(fabs(p1.critical() - 9432.5) > 0.00001); - ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001) > 0.00001); - ASSERT_FALSE(!p1.critical_mode()); - ASSERT_FALSE(fabs(p1.max() - 123.0) > 0.00001); - ASSERT_FALSE(fabs(p1.min() - 843.876) > 0.00001); - ASSERT_FALSE(p1.name() != "baz"); - ASSERT_FALSE(p1.unit() != "qux"); - ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); - ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); - ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); - ASSERT_FALSE(p1.warning_mode()); - ASSERT_FALSE(fabs(p2.critical() - 42.0) > 0.00001); - ASSERT_FALSE(fabs(p2.critical_low() + 456.032) > 0.00001); - ASSERT_FALSE(p2.critical_mode()); - ASSERT_FALSE(fabs(p2.max() - 76.3) > 0.00001); - ASSERT_FALSE(fabs(p2.min() - 567.2) > 0.00001); - ASSERT_FALSE(p2.name() != "foo"); - ASSERT_FALSE(p2.unit() != "bar"); - ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); - ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); - ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); - ASSERT_FALSE(!p2.warning_mode()); -} - -/** - * Check that the perfdata copy constructor works properly. - */ -TEST(MiscPerfdata, CopyCtor) { - // First object. - misc::perfdata p1; - p1.critical(42.0); - p1.critical_low(-456.032); - p1.critical_mode(false); - p1.max(76.3); - p1.min(567.2); - p1.name("foo"); - p1.unit("bar"); - p1.value(52189.912); - p1.value_type(misc::perfdata::counter); - p1.warning(4548.0); - p1.warning_low(42.42); - p1.warning_mode(true); - - // Second object. - misc::perfdata p2(p1); - - // Change first object. - p1.critical(9432.5); - p1.critical_low(1000.0001); - p1.critical_mode(true); - p1.max(123.0); - p1.min(843.876); - p1.name("baz"); - p1.unit("qux"); - p1.value(3485.9); - p1.value_type(misc::perfdata::derive); - p1.warning(3612.0); - p1.warning_low(-987579.0); - p1.warning_mode(false); - - // Check objects properties values. - ASSERT_FALSE(fabs(p1.critical() - 9432.5) > 0.00001); - ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001) > 0.00001); - ASSERT_FALSE(!p1.critical_mode()); - ASSERT_FALSE(fabs(p1.max() - 123.0) > 0.00001); - ASSERT_FALSE(fabs(p1.min() - 843.876) > 0.00001); - ASSERT_FALSE(p1.name() != "baz"); - ASSERT_FALSE(p1.unit() != "qux"); - ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); - ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); - ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); - ASSERT_FALSE(p1.warning_mode()); - ASSERT_FALSE(fabs(p2.critical() - 42.0) > 0.00001); - ASSERT_FALSE(fabs(p2.critical_low() + 456.032) > 0.00001); - ASSERT_FALSE(p2.critical_mode()); - ASSERT_FALSE(fabs(p2.max() - 76.3) > 0.00001); - ASSERT_FALSE(fabs(p2.min() - 567.2) > 0.00001); - ASSERT_FALSE(p2.name() != "foo"); - ASSERT_FALSE(p2.unit() != "bar"); - ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); - ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); - ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); - ASSERT_FALSE(!p2.warning_mode()); -} - -/** - * Check that the perfdata object properly default constructs. - * - * @return 0 on success. - */ -TEST(MiscPerfdata, DefaultCtor) { - // Build object. - misc::perfdata p; - - // Check properties values. - ASSERT_FALSE(!std::isnan(p.critical())); - ASSERT_FALSE(!std::isnan(p.critical_low())); - ASSERT_FALSE(p.critical_mode()); - ASSERT_FALSE(!std::isnan(p.max())); - ASSERT_FALSE(!std::isnan(p.min())); - ASSERT_FALSE(!p.name().empty()); - ASSERT_FALSE(!p.unit().empty()); - ASSERT_FALSE(!std::isnan(p.value())); - ASSERT_FALSE(p.value_type() != misc::perfdata::gauge); - ASSERT_FALSE(!std::isnan(p.warning())); - ASSERT_FALSE(!std::isnan(p.warning_low())); - ASSERT_FALSE(p.warning_mode()); -} - -class MiscParserParsePerfdata : public testing::Test { - public: - void SetUp() override { config::applier::init(0, "test_broker"); } - void TearDown() override { config::applier::deinit(); }; -}; - -// Given a misc::parser object -// When parse_perfdata() is called with a valid perfdata string -// Then perfdata are returned in a list -TEST_F(MiscParserParsePerfdata, Simple1) { - // Parse perfdata. - std::list lst{misc::parse_perfdata( - 0, 0, "time=2.45698s;2.000000;5.000000;0.000000;10.000000")}; - - // Assertions. - ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; - expected.name("time"); - expected.value_type(misc::perfdata::gauge); - expected.value(2.45698); - expected.unit("s"); - expected.warning(2.0); - expected.warning_low(0.0); - expected.critical(5.0); - expected.critical_low(0.0); - expected.min(0.0); - expected.max(10.0); - ASSERT_TRUE(expected == *it); -} - -TEST_F(MiscParserParsePerfdata, Simple2) { - // Parse perfdata. - std::list list{ - misc::parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100")}; - - // Assertions. - ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; - expected.name("ABCD12E"); - expected.value_type(misc::perfdata::gauge); - expected.value(18.0); - expected.unit("%"); - expected.warning(std::numeric_limits::infinity()); - expected.warning_low(15.0); - expected.critical(std::numeric_limits::infinity()); - expected.critical_low(10.0); - expected.min(0.0); - expected.max(100.0); - ASSERT_TRUE(expected == *it); -} - -TEST_F(MiscParserParsePerfdata, Complex1) { - // Parse perfdata. - std::list list{ - misc::parse_perfdata( - 0, 0, - "time=2.45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " - "infotraffic=18x;;;; a[foo]=1234;10;11: c[bar]=1234;~:10;20:30 " - "baz=1234;@10:20; 'q u x'=9queries_per_second;@10:;@5:;0;100")}; - - // Assertions. - ASSERT_EQ(list.size(), 7u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; - - // #1. - expected.name("time"); - expected.value_type(misc::perfdata::gauge); - expected.value(2.45698); - expected.unit("s"); - expected.max(std::numeric_limits::infinity()); - ASSERT_TRUE(expected == *it); - ++it; - - // #2. - expected = misc::perfdata(); - expected.name("metric"); - expected.value_type(misc::perfdata::derive); - expected.value(239765); - expected.unit("B/s"); - expected.warning(5.0); - expected.warning_low(0.0); - expected.min(-std::numeric_limits::infinity()); - ASSERT_TRUE(expected == *it); - ++it; - - // #3. - expected = misc::perfdata(); - expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); - expected.value(18.0); - expected.unit("x"); - ASSERT_TRUE(expected == *it); - ++it; - - // #4. - expected = misc::perfdata(); - expected.name("foo"); - expected.value_type(misc::perfdata::absolute); - expected.value(1234.0); - expected.warning(10.0); - expected.warning_low(0.0); - expected.critical(std::numeric_limits::infinity()); - expected.critical_low(11.0); - ASSERT_TRUE(expected == *it); - ++it; - - // #5. - expected = misc::perfdata(); - expected.name("bar"); - expected.value_type(misc::perfdata::counter); - expected.value(1234.0); - expected.warning(10.0); - expected.warning_low(-std::numeric_limits::infinity()); - expected.critical(30.0); - expected.critical_low(20.0); - ASSERT_TRUE(expected == *it); - ++it; - - // #6. - expected = misc::perfdata(); - expected.name("baz"); - expected.value_type(misc::perfdata::gauge); - expected.value(1234.0); - expected.warning(20.0); - expected.warning_low(10.0); - expected.warning_mode(true); - ASSERT_TRUE(expected == *it); - ++it; - - // #7. - expected = misc::perfdata(); - expected.name("q u x"); - expected.value_type(misc::perfdata::gauge); - expected.value(9.0); - expected.unit("queries_per_second"); - expected.warning(std::numeric_limits::infinity()); - expected.warning_low(10.0); - expected.warning_mode(true); - expected.critical(std::numeric_limits::infinity()); - expected.critical_low(5.0); - expected.critical_mode(true); - expected.min(0.0); - expected.max(100.0); - ASSERT_TRUE(expected == *it); -} - -// Given a misc::parser object -// When parse_perfdata() is called multiple time with valid strings -// Then the corresponding perfdata list is returned -TEST_F(MiscParserParsePerfdata, Loop) { - // Objects. - std::list list; - - // Loop. - for (uint32_t i(0); i < 10000; ++i) { - // Parse perfdata string. - list = misc::parse_perfdata( - 0, 0, "c[time]=2.45698s;2.000000;5.000000;0.000000;10.000000"); - - // Assertions. - ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; - expected.name("time"); - expected.value_type(misc::perfdata::counter); - expected.value(2.45698); - expected.unit("s"); - expected.warning(2.0); - expected.warning_low(0.0); - expected.critical(5.0); - expected.critical_low(0.0); - expected.min(0.0); - expected.max(10.0); - ASSERT_TRUE(expected == *it); - ++it; - } -} - -// Given a misc::parser object -// When parse_perfdata() is called with an invalid string -TEST_F(MiscParserParsePerfdata, Incorrect1) { - // Attempt to parse perfdata. - auto list{misc::parse_perfdata(0, 0, "metric1= 10 metric2=42")}; - ASSERT_EQ(list.size(), 1u); - ASSERT_EQ(list.back().name(), "metric2"); - ASSERT_EQ(list.back().value(), 42); -} - -// Given a misc::parser object -// When parse_perfdata() is called with a metric without value but with unit -TEST_F(MiscParserParsePerfdata, Incorrect2) { - // Then - auto list{misc::parse_perfdata(0, 0, "metric=kb/s")}; - ASSERT_TRUE(list.empty()); -} - -TEST_F(MiscParserParsePerfdata, LabelWithSpaces) { - // Parse perfdata. - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; - - // Assertions. - ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; - expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); - expected.value(2); - expected.unit("s"); - expected.warning(2.0); - expected.warning_low(0.0); - expected.critical(5.0); - expected.critical_low(0.0); - ASSERT_TRUE(expected == *it); -} - -TEST_F(MiscParserParsePerfdata, LabelWithSpacesMultiline) { - // Parse perfdata. - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; - - // Assertions. - ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; - expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); - expected.value(2); - expected.unit("s"); - expected.warning(2.0); - expected.warning_low(0.0); - expected.critical(5.0); - expected.critical_low(0.0); - ASSERT_TRUE(expected == *it); -} - -TEST_F(MiscParserParsePerfdata, Complex2) { - // Parse perfdata. - auto list{misc::parse_perfdata( - 0, 0, - "' \n time'=2,45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " - "g[test]=8x;;;;" - " infotraffic=18,6x;;;; a[foo]=1234,17;10;11: c[bar]=1234,147;~:10;20:30")}; - - // Assertions. - ASSERT_EQ(list.size(), 6u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; - - // #1. - expected.name("time"); - expected.value_type(misc::perfdata::gauge); - expected.value(2.45698); - expected.unit("s"); - expected.max(std::numeric_limits::infinity()); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; - - // #2. - expected = misc::perfdata(); - expected.name("metric"); - expected.value_type(misc::perfdata::derive); - expected.value(239765); - expected.unit("B/s"); - expected.warning(5.0); - expected.warning_low(0.0); - expected.min(-std::numeric_limits::infinity()); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; - - // #3. - expected = misc::perfdata(); - expected.name("test"); - expected.value_type(misc::perfdata::gauge); - expected.value(8); - expected.unit("x"); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; - - // #4. - expected = misc::perfdata(); - expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); - expected.value(18.6); - expected.unit("x"); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; - - // #5. - expected = misc::perfdata(); - expected.name("foo"); - expected.value_type(misc::perfdata::absolute); - expected.value(1234.17); - expected.warning(10.0); - expected.warning_low(0.0); - expected.critical(std::numeric_limits::infinity()); - expected.critical_low(11.0); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; - - // #6. - expected = misc::perfdata(); - expected.name("bar"); - expected.value_type(misc::perfdata::counter); - expected.value(1234.147); - expected.warning(10.0); - expected.warning_low(-std::numeric_limits::infinity()); - expected.critical(30.0); - expected.critical_low(20.0); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; -} - -// Given a misc::parser object -// When parse_perfdata() is called with a valid perfdata string -// Then perfdata are returned in a list -TEST_F(MiscParserParsePerfdata, SimpleWithR) { - auto lst{misc::parse_perfdata(0, 0, "'total'=5;;;0;\r")}; - - // Assertions. - ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; - expected.name("total"); - expected.value_type(misc::perfdata::gauge); - expected.value(5); - expected.unit(""); - expected.warning(NAN); - expected.warning_low(NAN); - expected.critical(NAN); - expected.critical_low(NAN); - expected.min(0.0); - expected.max(NAN); - ASSERT_TRUE(expected == *it); -} - -// Given a misc::parser object -// When parse_perfdata() is called with a valid perfdata string -// Then perfdata are returned in a list -TEST_F(MiscParserParsePerfdata, BadMetric) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3")}; - - // Assertions. - ASSERT_EQ(lst.size(), 3u); - int i = 1; - for (auto& p : lst) { - ASSERT_EQ(p.name(), fmt::format("user{}", i)); - ASSERT_EQ(p.value(), static_cast(i)); - ++i; - } -} - -TEST_F(MiscParserParsePerfdata, BadMetric1) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3")}; - - // Assertions. - ASSERT_EQ(lst.size(), 3u); - int i = 1; - for (auto& p : lst) { - ASSERT_EQ(p.name(), fmt::format("user{}", i)); - ASSERT_EQ(p.value(), static_cast(i)); - ++i; - } -} diff --git a/centreon-broker/core/test/modules/bad_version_module.cc b/centreon-broker/core/test/modules/bad_version_module.cc index c54ac716de1..85f9947e9d0 100644 --- a/centreon-broker/core/test/modules/bad_version_module.cc +++ b/centreon-broker/core/test/modules/bad_version_module.cc @@ -22,7 +22,9 @@ char const* broker_module_version = "42"; /** * Module deinitialization routine. */ -void broker_module_deinit() {} +void broker_module_deinit() { + return; +} /** * Module initialization routine. @@ -31,5 +33,6 @@ void broker_module_deinit() {} */ void broker_module_init(void const* arg) { (void)arg; + return; } } diff --git a/centreon-broker/core/test/modules/null_module.cc b/centreon-broker/core/test/modules/null_module.cc index 09d8fbb03d8..94e653ea90f 100644 --- a/centreon-broker/core/test/modules/null_module.cc +++ b/centreon-broker/core/test/modules/null_module.cc @@ -22,7 +22,9 @@ extern "C" { /** * Module deinitialization routine. */ -void broker_module_deinit() {} +void broker_module_deinit() { + return; +} /** * Module initialization routine. @@ -31,5 +33,6 @@ void broker_module_deinit() {} */ void broker_module_init(void const* arg) { (void)arg; + return; } } diff --git a/centreon-broker/core/test/multiplexing/engine/hook.cc b/centreon-broker/core/test/multiplexing/engine/hook.cc new file mode 100644 index 00000000000..79e4db5d2de --- /dev/null +++ b/centreon-broker/core/test/multiplexing/engine/hook.cc @@ -0,0 +1,143 @@ +/* + * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ +#include + +#include +#include + +#include "com/centreon/broker/config/applier/init.hh" +#include "com/centreon/broker/io/events.hh" +#include "com/centreon/broker/io/raw.hh" +#include "com/centreon/broker/multiplexing/engine.hh" +#include "com/centreon/broker/multiplexing/muxer.hh" +#include "com/centreon/broker/multiplexing/subscriber.hh" +#include "com/centreon/exceptions/msg_fmt.hh" +#include "hooker.hh" + +using namespace com::centreon::exceptions; +using namespace com::centreon::broker; + +const std::string MSG1("0123456789abcdef"); +const std::string MSG2("foo bar baz"); +const std::string MSG3("last message with qux"); +const std::string MSG4("no this is the last message"); + +class Hook : public testing::Test { + public: + void SetUp() override { config::applier::init(0, "test_broker"); } + + void TearDown() override { config::applier::deinit(); } +}; + +/** + * Check that multiplexing engine works properly. + * + */ +TEST_F(Hook, EngineWorks) { + // Initialization. + + bool error(true); + + try { + // Subscriber. + std::unordered_set filters; + filters.insert(io::raw::static_type()); + multiplexing::subscriber s("core_multiplexing_engine_hook", ""); + s.get_muxer().set_read_filters(filters); + s.get_muxer().set_write_filters(filters); + + // Hook. + hooker h; + h.hook(true); + + // Send events through engine. + { + std::array messages{MSG1, MSG2}; + for (const std::string& m : messages) { + std::shared_ptr data(std::make_shared()); + data->append(m); + multiplexing::engine::instance().publish( + std::static_pointer_cast(data)); + } + } + + // Should read no events from subscriber. + { + std::shared_ptr data; + s.get_muxer().read(data, 0); + if (data) + throw msg_fmt("error at step #1"); + } + + // Start multiplexing engine. + multiplexing::engine::instance().start(); + + // Publish a new event. + { + std::shared_ptr data(new io::raw); + data->append(MSG3); + multiplexing::engine::instance().publish( + std::static_pointer_cast(data)); + } + + // Stop multiplexing engine. + multiplexing::engine::instance().stop(); + + // Publish a new event. + { + std::shared_ptr data(new io::raw); + data->append(MSG4); + multiplexing::engine::instance().publish( + std::static_pointer_cast(data)); + } + + // Check subscriber content. + { + std::array messages{HOOKMSG1, MSG1, HOOKMSG2, MSG2, + HOOKMSG2, MSG3, HOOKMSG2, HOOKMSG3}; + for (auto& m : messages) { + std::shared_ptr d; + s.get_muxer().read(d, 0); + if (!d || (d->type() != io::raw::static_type())) + throw msg_fmt("error at step #2"); + else { + std::shared_ptr raw(std::static_pointer_cast(d)); + if (strncmp(raw->const_data(), m.c_str(), m.size())) + throw msg_fmt("error at step #3"); + } + } + std::shared_ptr d; + s.get_muxer().read(d, 0); + if (d) + throw msg_fmt("error at step #4"); + } + + // Unhook. + h.hook(false); + + // Success. + error = false; + } catch (std::exception const& e) { + std::cerr << e.what() << "\n"; + } catch (...) { + std::cerr << "unknown exception\n"; + } + + ASSERT_FALSE(error); +} diff --git a/centreon-broker/core/test/multiplexing/engine/hooker.hh b/centreon-broker/core/test/multiplexing/engine/hooker.hh new file mode 100644 index 00000000000..60104de79c3 --- /dev/null +++ b/centreon-broker/core/test/multiplexing/engine/hooker.hh @@ -0,0 +1,54 @@ +/* + * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ +#ifndef HOOKER_HH +#define HOOKER_HH + +#include + +#include "com/centreon/broker/multiplexing/hooker.hh" + +const std::string HOOKMSG1("my first hooking message (when engine is started)"); +const std::string HOOKMSG2( + "my second hooking message (when multiplexing events)"); +const std::string HOOKMSG3("my third hooking message (when engine is stopped)"); + +using namespace com::centreon::broker; + +/** + * @class hooker hooker.hh "test/multiplexing/engine/hooker.hh" + * @brief Test hook class. + * + * Simple class that hook events from the multiplexing engine. + */ +class hooker : public multiplexing::hooker { + std::queue> _queue; + + public: + hooker(); + ~hooker(); + hooker(const hooker&) = delete; + hooker& operator=(const hooker&) = delete; + bool read(std::shared_ptr& d, time_t deadline = (time_t)-1) override; + void starting() override; + void stopping() override; + int32_t write(std::shared_ptr const& d) override; + int32_t stop() override; +}; + +#endif // !HOOKER_HH diff --git a/centreon-broker/core/test/multiplexing/engine/start_stop.cc b/centreon-broker/core/test/multiplexing/engine/start_stop.cc index 36c8e6f1ad8..d66c351e47c 100644 --- a/centreon-broker/core/test/multiplexing/engine/start_stop.cc +++ b/centreon-broker/core/test/multiplexing/engine/start_stop.cc @@ -64,16 +64,18 @@ TEST_F(StartStop, MultiplexingWorks) { // Send events through engine. std::array messages{MSG1, MSG2}; for (auto& m : messages) { - auto data{std::make_shared()}; + std::shared_ptr data(new io::raw); data->append(m); - multiplexing::engine::instance().publish(data); + multiplexing::engine::instance().publish( + std::static_pointer_cast(data)); } // Should read no events from subscriber. { std::shared_ptr data; s.get_muxer().read(data, 0); - ASSERT_FALSE(data); + if (data) + throw msg_fmt("error at step #1"); } // Start multiplexing engine. @@ -83,27 +85,34 @@ TEST_F(StartStop, MultiplexingWorks) { for (auto& m : messages) { std::shared_ptr data; s.get_muxer().read(data, 0); - ASSERT_TRUE(data); - ASSERT_EQ(data->type(), io::raw::static_type()); - std::shared_ptr raw(std::static_pointer_cast(data)); - ASSERT_EQ(strncmp(raw->const_data(), m.c_str(), m.size()), 0); + if (!data || data->type() != io::raw::static_type()) + throw msg_fmt("error at step #2"); + else { + std::shared_ptr raw(std::static_pointer_cast(data)); + if (strncmp(raw->const_data(), m.c_str(), m.size())) + throw msg_fmt("error at step #3"); + } } // Publish a new event. { - auto data{std::make_shared()}; + std::shared_ptr data(new io::raw); data->append(MSG3); - multiplexing::engine::instance().publish(data); + multiplexing::engine::instance().publish( + std::static_pointer_cast(data)); } // Read event. { std::shared_ptr data; s.get_muxer().read(data, 0); - ASSERT_TRUE(data); - ASSERT_EQ(data->type(), io::raw::static_type()); - auto raw{std::static_pointer_cast(data)}; - ASSERT_EQ(strncmp(raw->const_data(), MSG3.c_str(), MSG3.size()), 0); + if (!data || data->type() != io::raw::static_type()) + throw msg_fmt("error at step #4"); + else { + std::shared_ptr raw(std::static_pointer_cast(data)); + if (strncmp(raw->const_data(), MSG3.c_str(), MSG3.size())) + throw msg_fmt("error at step #5"); + } } // Stop multiplexing engine. diff --git a/centreon-broker/core/test/multiplexing/engine/unhook.cc b/centreon-broker/core/test/multiplexing/engine/unhook.cc new file mode 100644 index 00000000000..a04e3ede36b --- /dev/null +++ b/centreon-broker/core/test/multiplexing/engine/unhook.cc @@ -0,0 +1,138 @@ +/* + * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +#include + +#include +#include + +#include "com/centreon/broker/config/applier/init.hh" +#include "com/centreon/broker/io/events.hh" +#include "com/centreon/broker/io/raw.hh" +#include "com/centreon/broker/multiplexing/engine.hh" +#include "com/centreon/broker/multiplexing/muxer.hh" +#include "com/centreon/broker/multiplexing/subscriber.hh" +#include "com/centreon/exceptions/msg_fmt.hh" +#include "hooker.hh" + +using namespace com::centreon::exceptions; +using namespace com::centreon::broker; + +const std::string MSG1("0123456789abcdef"); +const std::string MSG2("foo bar baz"); +const std::string MSG3("last message with qux"); + +class Unhook : public testing::Test { + public: + void SetUp() override { config::applier::init(0, "test_broker"); } + + void TearDown() override { config::applier::deinit(); } +}; + +/** + * Check that multiplexing engine works properly. + * + */ +TEST_F(Unhook, EngineWorks) { + // Initialization. + bool error(true); + + try { + // Subscriber. + std::unordered_set filters; + filters.insert(io::raw::static_type()); + multiplexing::subscriber s("core_multiplexing_engine_unhook", ""); + s.get_muxer().set_read_filters(filters); + s.get_muxer().set_write_filters(filters); + + // Hook. + hooker h; + h.hook(true); + + // Should read no events from subscriber. + { + std::shared_ptr data; + s.get_muxer().read(data, 0); + if (data) + throw msg_fmt("error at step #1"); + } + + // Start multiplexing engine. + multiplexing::engine::instance().start(); + + // Publish event. + { + std::shared_ptr data(new io::raw); + data->append(MSG1); + multiplexing::engine::instance().publish( + std::static_pointer_cast(data)); + } + + // Unhook. + h.hook(false); + + // Publish a new event. + { + std::shared_ptr data(new io::raw); + data->append(MSG2); + multiplexing::engine::instance().publish( + std::static_pointer_cast(data)); + } + + // Stop multiplexing engine. + multiplexing::engine::instance().stop(); + + // Publish a new event. + { + std::shared_ptr data(new io::raw); + data->append(MSG3); + multiplexing::engine::instance().publish( + std::static_pointer_cast(data)); + } + + // Check subscriber content. + { + std::array messages{HOOKMSG1, MSG1, HOOKMSG2, MSG2}; + for (auto& m : messages) { + std::shared_ptr d; + s.get_muxer().read(d, 0); + if (!d || d->type() != io::raw::static_type()) + throw msg_fmt("error at step #2"); + else { + std::shared_ptr raw(std::static_pointer_cast(d)); + if (strncmp(raw->const_data(), m.c_str(), m.size())) + throw msg_fmt("error at step #3"); + } + } + std::shared_ptr data; + s.get_muxer().read(data, 0); + if (data) + throw msg_fmt("error at step #4"); + } + + // Success. + error = false; + } catch (std::exception const& e) { + std::cerr << e.what() << "\n"; + } catch (...) { + std::cerr << "unknown exception\n"; + } + + ASSERT_FALSE(error); +} diff --git a/centreon-broker/core/test/rpc/brokerrpc.cc b/centreon-broker/core/test/rpc/brokerrpc.cc index 8ebb3b61f1e..3f5da1cb8d2 100644 --- a/centreon-broker/core/test/rpc/brokerrpc.cc +++ b/centreon-broker/core/test/rpc/brokerrpc.cc @@ -23,6 +23,8 @@ #include +#include + #include #include #include @@ -168,12 +170,10 @@ TEST_F(BrokerRpc, GetSqlConnectionSize) { SqlConnectionStats* _stats; _stats = stats::center::instance().register_mysql_connection(); - stats::center::instance().update(&SqlConnectionStats::set_waiting_tasks, - _stats, 3); + stats::center::instance().update(&SqlConnectionStats::set_waiting_tasks, _stats, 3); _stats = stats::center::instance().register_mysql_connection(); - stats::center::instance().update(&SqlConnectionStats::set_waiting_tasks, - _stats, 5); + stats::center::instance().update(&SqlConnectionStats::set_waiting_tasks, _stats, 5); auto output = execute("GetSqlConnectionSize"); ASSERT_EQ(output.front(), "connection array size: 2\n"); diff --git a/centreon-broker/core/test/time/timerange.cc b/centreon-broker/core/test/time/timerange.cc index 6e1528f4023..415621ceaa5 100644 --- a/centreon-broker/core/test/time/timerange.cc +++ b/centreon-broker/core/test/time/timerange.cc @@ -17,22 +17,26 @@ * */ -#include "com/centreon/broker/time/timerange.hh" #include -#include +#include "com/centreon/broker/time/timerange.hh" #include "com/centreon/broker/time/timeperiod.hh" +#include using namespace com::centreon::broker::time; + TEST(Timerange, ParseWeirdTimerange) { std::unique_ptr tp; // Here we tests weird timeranges but they should not throw // Timerange parser must understands theses - ASSERT_NO_THROW(tp.reset(new timeperiod( - 2, "test", "alias", "\r \r08:00\r-12:00\r", "\n\n08:00 - 12:00\r", - "08:00 -12:00\r", "08:00 - \n12:00\r", "08:00\t-\t12:00\r", + ASSERT_NO_THROW(tp.reset(new timeperiod(2, "test", "alias", + "\r \r08:00\r-12:00\r", + "\n\n08:00 - 12:00\r", + "08:00 -12:00\r", + "08:00 - \n12:00\r", + "08:00\t-\t12:00\r", "08:00-12:00,09:00-12:00,10:00-12:00", "08:00-12:00 , 09:00-12:00, \r\n 10:00-12:00"))); @@ -45,13 +49,14 @@ TEST(Timerange, ParseWeirdTimerange) { ASSERT_EQ(v[5].back().start(), 28800u); ASSERT_EQ(v[5].front().end(), 43200u); ASSERT_EQ(timerange::build_string_from_timeranges(v[5]), - "08:00-12:00, 09:00-12:00, 10:00-12:00"); + "08:00-12:00, 09:00-12:00, 10:00-12:00"); ASSERT_EQ(v[6].front().start(), 36000u); ASSERT_EQ(v[6].front().end(), 43200u); ASSERT_EQ(v[6].back().start(), 28800u); ASSERT_EQ(v[6].front().end(), 43200u); ASSERT_EQ(timerange::build_string_from_timeranges(v[6]), - "08:00-12:00, 09:00-12:00, 10:00-12:00"); + "08:00-12:00, 09:00-12:00, 10:00-12:00"); + } TEST(Timerange, ParseWrongTimerange) { diff --git a/centreon-broker/deps.go b/centreon-broker/deps.go index 2d417a9c80a..fa1523a37de 100644 --- a/centreon-broker/deps.go +++ b/centreon-broker/deps.go @@ -34,10 +34,8 @@ func findIncludes(file string, treated *[]string, depth int) { "watchdog/inc/", "stats/inc/", "notification/inc/", - "../protobuf/", "dumper/inc/", "storage/inc/", - "unified_sql/inc/", "influxdb/inc/", "sql/inc/" } { f, err = os.Open(pref + file1) diff --git a/centreon-broker/generator/src/dummy.cc b/centreon-broker/generator/src/dummy.cc index 28e3c788fbf..66c279d51de 100644 --- a/centreon-broker/generator/src/dummy.cc +++ b/centreon-broker/generator/src/dummy.cc @@ -65,5 +65,4 @@ mapping::entry const dummy::entries[] = { static io::data* new_dummy() { return new dummy(); } -io::event_info::event_operations const dummy::operations = {&new_dummy, nullptr, - nullptr}; +io::event_info::event_operations const dummy::operations = {&new_dummy}; diff --git a/centreon-broker/generator/src/main.cc b/centreon-broker/generator/src/main.cc index a8ee1435381..7de281ce0c5 100644 --- a/centreon-broker/generator/src/main.cc +++ b/centreon-broker/generator/src/main.cc @@ -48,7 +48,7 @@ void broker_module_deinit() { // Deregister storage layer. io::protocols::instance().unreg(generator_module); // Deregister generator events. - io::events::instance().unregister_category(io::generator); + io::events::instance().unregister_category(io::events::generator); } } @@ -72,8 +72,20 @@ void broker_module_init(void const* arg) { io::events& e(io::events::instance()); + // Register category. + int category(e.register_category("generator", io::events::generator)); + if (category != io::events::generator) { + e.unregister_category(category); + --instances; + throw msg_fmt( + "generator: category {}" + " is already registered whereas it should be " + "reserved for the generator module", + io::events::generator); + } + // Register bam events. - e.register_event(io::generator, generator::de_dummy, + e.register_event(io::events::generator, generator::de_dummy, io::event_info("dummy", &generator::dummy::operations, generator::dummy::entries)); } diff --git a/centreon-broker/graphite/CMakeLists.txt b/centreon-broker/graphite/CMakeLists.txt index f8c79f2bff0..71060aaba3d 100644 --- a/centreon-broker/graphite/CMakeLists.txt +++ b/centreon-broker/graphite/CMakeLists.txt @@ -43,7 +43,6 @@ add_library("${GRAPHITE}" SHARED "${INC_DIR}/query.hh" "${INC_DIR}/macro_cache.hh" ) -target_link_libraries("${GRAPHITE}" bbdo_storage) set_target_properties("${GRAPHITE}" PROPERTIES PREFIX "") # Testing. diff --git a/centreon-broker/graphite/inc/com/centreon/broker/graphite/macro_cache.hh b/centreon-broker/graphite/inc/com/centreon/broker/graphite/macro_cache.hh index ce7fa191584..97db3bd5bcf 100644 --- a/centreon-broker/graphite/inc/com/centreon/broker/graphite/macro_cache.hh +++ b/centreon-broker/graphite/inc/com/centreon/broker/graphite/macro_cache.hh @@ -30,8 +30,8 @@ #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/neb/service.hh" #include "com/centreon/broker/persistent_cache.hh" -#include "bbdo/storage/index_mapping.hh" -#include "bbdo/storage/metric_mapping.hh" +#include "com/centreon/broker/storage/index_mapping.hh" +#include "com/centreon/broker/storage/metric_mapping.hh" CCB_BEGIN() diff --git a/centreon-broker/graphite/inc/com/centreon/broker/graphite/query.hh b/centreon-broker/graphite/inc/com/centreon/broker/graphite/query.hh index 888f92bcd29..6ce2ae43ab9 100644 --- a/centreon-broker/graphite/inc/com/centreon/broker/graphite/query.hh +++ b/centreon-broker/graphite/inc/com/centreon/broker/graphite/query.hh @@ -22,10 +22,10 @@ #include #include #include -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/graphite/macro_cache.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/metric.hh" +#include "com/centreon/broker/storage/status.hh" CCB_BEGIN() diff --git a/centreon-broker/graphite/inc/com/centreon/broker/graphite/stream.hh b/centreon-broker/graphite/inc/com/centreon/broker/graphite/stream.hh index 03b816af87f..920323016ba 100644 --- a/centreon-broker/graphite/inc/com/centreon/broker/graphite/stream.hh +++ b/centreon-broker/graphite/inc/com/centreon/broker/graphite/stream.hh @@ -26,12 +26,13 @@ #include #include #include -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/graphite/macro_cache.hh" #include "com/centreon/broker/graphite/query.hh" #include "com/centreon/broker/io/stream.hh" +#include "com/centreon/broker/multiplexing/hooker.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/metric.hh" +#include "com/centreon/broker/storage/status.hh" #if ASIO_VERSION < 101200 namespace asio { diff --git a/centreon-broker/graphite/src/main.cc b/centreon-broker/graphite/src/main.cc index e3c2d7b948d..4c7cd810019 100644 --- a/centreon-broker/graphite/src/main.cc +++ b/centreon-broker/graphite/src/main.cc @@ -1,5 +1,5 @@ /* -** Copyright 2011-2013, 2020-2021 Centreon +** Copyright 2011-2013 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/storage/internal.hh" using namespace com::centreon::broker; @@ -39,7 +40,7 @@ char const* broker_module_version = CENTREON_BROKER_VERSION; * @return An array of const char* */ const char* const* broker_module_parents() { - constexpr static const char* retval[]{"10-neb.so", nullptr}; + constexpr static const char* retval[]{"10-neb.so", "20-storage.so", nullptr}; return retval; } @@ -68,23 +69,6 @@ void broker_module_init(void const* arg) { log_v2::graphite()->info("graphite: module for Centreon Broker {}", CENTREON_BROKER_VERSION); - io::events& e(io::events::instance()); - - // Register events. - { - e.register_event(make_type(io::storage, storage::de_metric), "metric", - &storage::metric::operations, storage::metric::entries, - "rt_metrics"); - e.register_event(make_type(io::storage, storage::de_status), "status", - &storage::status::operations, storage::status::entries); - e.register_event(make_type(io::storage, storage::de_index_mapping), - "index_mapping", &storage::index_mapping::operations, - storage::index_mapping::entries); - e.register_event(make_type(io::storage, storage::de_metric_mapping), - "metric_mapping", &storage::metric_mapping::operations, - storage::metric_mapping::entries); - } - // Register storage layer. io::protocols::instance().reg("graphite", std::make_shared(), 1, 7); diff --git a/centreon-broker/graphite/src/stream.cc b/centreon-broker/graphite/src/stream.cc index 31504eaccb2..3258eaa4954 100644 --- a/centreon-broker/graphite/src/stream.cc +++ b/centreon-broker/graphite/src/stream.cc @@ -18,13 +18,15 @@ #include "com/centreon/broker/graphite/stream.hh" #include -#include "bbdo/storage/metric.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/misc/global_lock.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/publisher.hh" +#include "com/centreon/broker/storage/internal.hh" +#include "com/centreon/broker/storage/metric.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace asio; @@ -180,11 +182,11 @@ int stream::write(std::shared_ptr const& data) { // Process metric events. if (data->type() == - io::events::data_type::value) { + io::events::data_type::value) { if (_process_metric(*std::static_pointer_cast(data))) ++_actual_query; - } else if (data->type() == - io::events::data_type::value) { + } else if (data->type() == io::events::data_type::value) { if (_process_status(*std::static_pointer_cast(data))) ++_actual_query; } diff --git a/centreon-broker/influxdb/CMakeLists.txt b/centreon-broker/influxdb/CMakeLists.txt index 53e42901bb8..95bc89d7f1c 100644 --- a/centreon-broker/influxdb/CMakeLists.txt +++ b/centreon-broker/influxdb/CMakeLists.txt @@ -48,7 +48,6 @@ add_library("${INFLUXDB}" SHARED "${INC_DIR}/macro_cache.hh" "${INC_DIR}/stream.hh" ) -target_link_libraries("${INFLUXDB}" bbdo_storage) set_target_properties("${INFLUXDB}" PROPERTIES PREFIX "") # Testing. diff --git a/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/influxdb.hh b/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/influxdb.hh index cbb12a4c6f3..a828efdd019 100644 --- a/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/influxdb.hh +++ b/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/influxdb.hh @@ -21,9 +21,9 @@ #include #include -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/metric.hh" +#include "com/centreon/broker/storage/status.hh" CCB_BEGIN() diff --git a/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/influxdb12.hh b/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/influxdb12.hh index 59ae41c9619..583271a6702 100644 --- a/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/influxdb12.hh +++ b/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/influxdb12.hh @@ -22,12 +22,12 @@ #include #include #include -#include "bbdo/storage/metric.hh" #include "com/centreon/broker/influxdb/column.hh" #include "com/centreon/broker/influxdb/influxdb.hh" #include "com/centreon/broker/influxdb/line_protocol_query.hh" #include "com/centreon/broker/influxdb/macro_cache.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/metric.hh" #if ASIO_VERSION < 101200 namespace asio { diff --git a/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/line_protocol_query.hh b/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/line_protocol_query.hh index 014ad77f2fa..b6d4803ac36 100644 --- a/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/line_protocol_query.hh +++ b/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/line_protocol_query.hh @@ -22,11 +22,11 @@ #include #include #include -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/influxdb/column.hh" #include "com/centreon/broker/influxdb/macro_cache.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/metric.hh" +#include "com/centreon/broker/storage/status.hh" CCB_BEGIN() diff --git a/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/macro_cache.hh b/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/macro_cache.hh index 64d84af36da..e667a086c4f 100644 --- a/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/macro_cache.hh +++ b/centreon-broker/influxdb/inc/com/centreon/broker/influxdb/macro_cache.hh @@ -30,8 +30,8 @@ #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/neb/service.hh" #include "com/centreon/broker/persistent_cache.hh" -#include "bbdo/storage/index_mapping.hh" -#include "bbdo/storage/metric_mapping.hh" +#include "com/centreon/broker/storage/index_mapping.hh" +#include "com/centreon/broker/storage/metric_mapping.hh" CCB_BEGIN() namespace influxdb { diff --git a/centreon-broker/influxdb/src/main.cc b/centreon-broker/influxdb/src/main.cc index fb81e2397e1..7d54796acfd 100644 --- a/centreon-broker/influxdb/src/main.cc +++ b/centreon-broker/influxdb/src/main.cc @@ -1,5 +1,5 @@ /* -** Copyright 2011-2013, 2020-2021 Centreon +** Copyright 2011-2013 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" -//#include "com/centreon/broker/storage/internal.hh" +#include "com/centreon/broker/storage/internal.hh" using namespace com::centreon::broker; @@ -40,7 +40,7 @@ char const* broker_module_version = CENTREON_BROKER_VERSION; * @return An array of const char* */ const char* const* broker_module_parents() { - constexpr static const char* retval[]{"10-neb.so", nullptr}; + constexpr static const char* retval[]{"10-neb.so", "20-storage.so", nullptr}; return retval; } @@ -69,26 +69,10 @@ void broker_module_init(void const* arg) { log_v2::influxdb()->info("influxdb: module for Centreon Broker {}", CENTREON_BROKER_VERSION); - io::events& e(io::events::instance()); - - // Register events. - { - e.register_event(make_type(io::storage, storage::de_metric), "metric", - &storage::metric::operations, storage::metric::entries, - "rt_metrics"); - e.register_event(make_type(io::storage, storage::de_status), "status", - &storage::status::operations, storage::status::entries); - e.register_event(make_type(io::storage, storage::de_index_mapping), - "index_mapping", &storage::index_mapping::operations, - storage::index_mapping::entries); - e.register_event(make_type(io::storage, storage::de_metric_mapping), - "metric_mapping", &storage::metric_mapping::operations, - storage::metric_mapping::entries); - } - // Register storage layer. io::protocols::instance().reg("influxdb", std::make_shared(), 1, 7); } + return; } } diff --git a/centreon-broker/influxdb/src/stream.cc b/centreon-broker/influxdb/src/stream.cc index d4926500867..a17cdee00d9 100644 --- a/centreon-broker/influxdb/src/stream.cc +++ b/centreon-broker/influxdb/src/stream.cc @@ -17,13 +17,15 @@ */ #include "com/centreon/broker/influxdb/stream.hh" -#include "bbdo/storage/metric.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/influxdb/influxdb12.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/misc/global_lock.hh" #include "com/centreon/broker/multiplexing/engine.hh" #include "com/centreon/broker/multiplexing/publisher.hh" +#include "com/centreon/broker/storage/internal.hh" +#include "com/centreon/broker/storage/metric.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::influxdb; @@ -134,11 +136,11 @@ int stream::write(std::shared_ptr const& data) { // Process metric events. if (data->type() == - io::events::data_type::value) { + io::events::data_type::value) { _influx_db->write(*std::static_pointer_cast(data)); ++_actual_query; - } else if (data->type() == - io::events::data_type::value) { + } else if (data->type() == io::events::data_type::value) { _influx_db->write(*std::static_pointer_cast(data)); ++_actual_query; } diff --git a/centreon-broker/influxdb/test/factory.cc b/centreon-broker/influxdb/test/factory.cc index f3ce4defbff..39eb6d0c946 100644 --- a/centreon-broker/influxdb/test/factory.cc +++ b/centreon-broker/influxdb/test/factory.cc @@ -19,8 +19,8 @@ #include "com/centreon/broker/influxdb/factory.hh" #include -#include #include "com/centreon/exceptions/msg_fmt.hh" +#include using namespace com::centreon::exceptions; using namespace com::centreon::broker; @@ -87,56 +87,72 @@ TEST(InfluxDBFactory, StatusException) { std::unique_ptr ep; ASSERT_NO_THROW(ep.reset(fact.new_endpoint(cfg, is_acceptor, cache))); - json js1 = json::object({{"name", json{nullptr}}, - {"value", json{nullptr}}, - {"is_tag", json{nullptr}}, - {"type", json{nullptr}}}); + json js1 = json::object({ + {"name", json{nullptr}}, + {"value", json{nullptr}}, + {"is_tag", json{nullptr}}, + {"type", json{nullptr}} + }); conf["status_column"] = js1; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - json js2 = json::object({{"name", "host"}, - {"value", json{nullptr}}, - {"is_tag", json{nullptr}}, - {"type", json{nullptr}}}); + json js2 = json::object({ + {"name", "host"}, + {"value", json{nullptr}}, + {"is_tag", json{nullptr}}, + {"type", json{nullptr}} + }); conf["status_column"] = js2; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - json js3 = json::object({{"name", "host"}, - {"value", "val"}, - {"is_tag", json{nullptr}}, - {"type", json{nullptr}}}); + json js3 = json::object({ + {"name", "host"}, + {"value", "val"}, + {"is_tag", json{nullptr}}, + {"type", json{nullptr}} + }); conf["status_column"] = js3; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - json js4 = json::object({{"name", "host"}, - {"value", "val"}, - {"is_tag", "true"}, - {"type", json{nullptr}}}); + json js4 = json::object({ + {"name", "host"}, + {"value", "val"}, + {"is_tag", "true"}, + {"type", json{nullptr}} + }); conf["status_column"] = js4; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - json js5 = json::object({{"name", "host"}, - {"value", "val"}, - {"is_tag", "true"}, - {"type", "bad"}}); + json js5 = json::object({ + {"name", "host"}, + {"value", "val"}, + {"is_tag", "true"}, + {"type", "bad"} + }); conf["status_column"] = js5; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - json js6 = json::object({{"name", "host"}, - {"value", "val"}, - {"is_tag", "true"}, - {"type", "number"}}); + json js6 = json::object({ + {"name", "host"}, + {"value", "val"}, + {"is_tag", "true"}, + {"type", "number"} + }); conf["status_column"] = js6; cfg.cfg = conf; ASSERT_NO_THROW(delete fact.new_endpoint(cfg, is_acceptor, cache)); - json js7 = json::object( - {{"name", ""}, {"value", "val"}, {"is_tag", "true"}, {"type", "number"}}); + json js7 = json::object({ + {"name", ""}, + {"value", "val"}, + {"is_tag", "true"}, + {"type", "number"} + }); conf["status_column"] = js7; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); @@ -173,58 +189,72 @@ TEST(InfluxDBFactory, MetricException) { std::unique_ptr ep; ASSERT_NO_THROW(ep.reset(fact.new_endpoint(cfg, is_acceptor, cache))); - json js1 = json::object({{"name", json{nullptr}}, - {"value", json{nullptr}}, - {"is_tag", json{nullptr}}, - {"type", json{nullptr}}}); + json js1 = json::object({ + {"name", json{nullptr}}, + {"value", json{nullptr}}, + {"is_tag", json{nullptr}}, + {"type", json{nullptr}} + }); conf["metrics_column"] = js1; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - json js2 = json::object({{"name", "host"}, - {"value", json{nullptr}}, - {"is_tag", json{nullptr}}, - {"type", json{nullptr}}}); + json js2 = json::object({ + {"name", "host"}, + {"value", json{nullptr}}, + {"is_tag", json{nullptr}}, + {"type", json{nullptr}} + }); conf["metrics_column"] = js2; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - json js3 = json::object({{"name", "host"}, - {"value", "val"}, - {"is_tag", json{nullptr}}, - {"type", json{nullptr}}}); + json js3 = json::object({ + {"name", "host"}, + {"value", "val"}, + {"is_tag", json{nullptr}}, + {"type", json{nullptr}} + }); conf["metrics_column"] = js3; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - json js4 = json::object({{"name", "host"}, - {"value", "val"}, - {"is_tag", "true"}, - {"type", json{nullptr}}}); + json js4 = json::object({ + {"name", "host"}, + {"value", "val"}, + {"is_tag", "true"}, + {"type", json{nullptr}} + }); conf["metrics_column"] = js4; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - json js5 = json::object({{"name", "host"}, - {"value", "val"}, - {"is_tag", "true"}, - {"type", "bad"}}); + json js5 = json::object({ + {"name", "host"}, + {"value", "val"}, + {"is_tag", "true"}, + {"type", "bad"} + }); conf["metrics_column"] = js5; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - json js6 = json::object({{"name", "host"}, - {"value", "val"}, - {"is_tag", "true"}, - {"type", "number"}}); + json js6 = json::object({ + {"name", "host"}, + {"value", "val"}, + {"is_tag", "true"}, + {"type", "number"} + }); conf["metrics_column"] = js6; cfg.cfg = conf; ASSERT_NO_THROW(delete fact.new_endpoint(cfg, is_acceptor, cache)); - json js7 = json::object({{"name", ""}, - {"value", "val"}, - {"is_tag", "false"}, - {"type", "number"}}); + json js7 = json::object({ + {"name", ""}, + {"value", "val"}, + {"is_tag", "false"}, + {"type", "number"} + }); conf["metrics_column"] = js7; cfg.cfg = conf; ASSERT_THROW(fact.new_endpoint(cfg, is_acceptor, cache), msg_fmt); diff --git a/centreon-broker/influxdb/test/line_protocol_query.cc b/centreon-broker/influxdb/test/line_protocol_query.cc index b328e50b6dd..ecd72c744f7 100644 --- a/centreon-broker/influxdb/test/line_protocol_query.cc +++ b/centreon-broker/influxdb/test/line_protocol_query.cc @@ -67,7 +67,7 @@ TEST(InfluxDBLineProtoQuery, GenerateMetric) { influxdb::macro_cache cache(pcache); storage::metric m1{1u, 1u, "host1", 2000llu, 60, true, 42u, 42, 42.0, 4}; storage::metric m2{1u, 1u, "host2", 4000llu, 120, false, 43, 42, 42.0, 4}; - storage::metric m3{2u, 3u, "hotst3", 2000llu, 60, true, 42u, 43, 43.0, 0}; + storage::metric m3{2u, 3u, "hotst3", 2000llu, 60, true, 42u, 43, 43.0, 5}; columns.push_back( influxdb::column{"host1", "42.0", true, influxdb::column::number}); diff --git a/centreon-broker/lua/CMakeLists.txt b/centreon-broker/lua/CMakeLists.txt index d2e537eef53..9bc711f9b6c 100644 --- a/centreon-broker/lua/CMakeLists.txt +++ b/centreon-broker/lua/CMakeLists.txt @@ -21,9 +21,11 @@ set(INC_DIR "${PROJECT_SOURCE_DIR}/lua/inc") set(SRC_DIR "${PROJECT_SOURCE_DIR}/lua/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/lua/test") -include_directories("${INC_DIR}" - "${PROJECT_SOURCE_DIR}/neb/inc" - ${OpenSSL_INCLUDE_DIRS}) +include_directories("${INC_DIR}") +include_directories("${PROJECT_SOURCE_DIR}/bam/inc") +include_directories("${PROJECT_SOURCE_DIR}/neb/inc") +include_directories("${PROJECT_SOURCE_DIR}/storage/inc") +include_directories(${OpenSSL_INCLUDE_DIRS}) set(INC_DIR "${INC_DIR}/com/centreon/broker/lua") # Storage module. @@ -54,7 +56,7 @@ add_library("${LUA}" SHARED "${INC_DIR}/macro_cache.hh" "${INC_DIR}/stream.hh" ) -target_link_libraries("${LUA}" ${LUA_LIBRARIES} ${OpenSSL_LIBS} bbdo_storage bbdo_bam) +target_link_libraries("${LUA}" ${LUA_LIBRARIES} ${OpenSSL_LIBS}) set_target_properties("${LUA}" PROPERTIES PREFIX "") # Testing. @@ -72,7 +74,6 @@ if (WITH_TESTING) PARENT_SCOPE ) endif() - # Install rule. install(TARGETS "${LUA}" LIBRARY DESTINATION "${PREFIX_MODULES}" diff --git a/centreon-broker/lua/inc/com/centreon/broker/lua/macro_cache.hh b/centreon-broker/lua/inc/com/centreon/broker/lua/macro_cache.hh index 1bf4930827e..78af245f725 100644 --- a/centreon-broker/lua/inc/com/centreon/broker/lua/macro_cache.hh +++ b/centreon-broker/lua/inc/com/centreon/broker/lua/macro_cache.hh @@ -23,12 +23,10 @@ #include #include -#include "bbdo/bam/dimension_ba_bv_relation_event.hh" -#include "bbdo/bam/dimension_ba_event.hh" -#include "bbdo/bam/dimension_bv_event.hh" -#include "bbdo/bam/dimension_truncate_table_signal.hh" -#include "bbdo/storage/index_mapping.hh" -#include "bbdo/storage/metric_mapping.hh" +#include "com/centreon/broker/bam/dimension_ba_bv_relation_event.hh" +#include "com/centreon/broker/bam/dimension_ba_event.hh" +#include "com/centreon/broker/bam/dimension_bv_event.hh" +#include "com/centreon/broker/bam/dimension_truncate_table_signal.hh" #include "com/centreon/broker/misc/pair.hh" #include "com/centreon/broker/neb/custom_variable.hh" #include "com/centreon/broker/neb/host.hh" @@ -39,6 +37,8 @@ #include "com/centreon/broker/neb/service_group.hh" #include "com/centreon/broker/neb/service_group_member.hh" #include "com/centreon/broker/persistent_cache.hh" +#include "com/centreon/broker/storage/index_mapping.hh" +#include "com/centreon/broker/storage/metric_mapping.hh" CCB_BEGIN() diff --git a/centreon-broker/lua/inc/com/centreon/broker/lua/stream.hh b/centreon-broker/lua/inc/com/centreon/broker/lua/stream.hh index 62bff223cba..91ffdbdefb0 100644 --- a/centreon-broker/lua/inc/com/centreon/broker/lua/stream.hh +++ b/centreon-broker/lua/inc/com/centreon/broker/lua/stream.hh @@ -23,9 +23,9 @@ #include #include #include +#include #include #include -#include #include #include diff --git a/centreon-broker/lua/src/broker_event.cc b/centreon-broker/lua/src/broker_event.cc index ff93d36f32c..ce634f34f86 100644 --- a/centreon-broker/lua/src/broker_event.cc +++ b/centreon-broker/lua/src/broker_event.cc @@ -1,5 +1,5 @@ /* -** Copyright 2020-2021 Centreon +** Copyright 2020 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -57,8 +57,8 @@ void broker_event::create(lua_State* L, std::shared_ptr e) { */ void broker_event::create_as_table(lua_State* L, const io::data& d) { uint32_t type(d.type()); - uint16_t cat(category_of_type(type)); - uint16_t elem(element_of_type(type)); + unsigned short cat(io::events::category_of_type(type)); + unsigned short elem(io::events::element_of_type(type)); lua_newtable(L); lua_pushstring(L, "_type"); lua_pushinteger(L, type); diff --git a/centreon-broker/lua/src/broker_utils.cc b/centreon-broker/lua/src/broker_utils.cc index 2f267fd5b9c..e0a0a0332bc 100644 --- a/centreon-broker/lua/src/broker_utils.cc +++ b/centreon-broker/lua/src/broker_utils.cc @@ -1,5 +1,5 @@ /* -** Copyright 2018-2021 Centreon +** Copyright 2018 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -31,7 +31,8 @@ #include "com/centreon/broker/io/data.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/mapping/entry.hh" -#include "com/centreon/broker/misc/misc.hh" +#include "com/centreon/broker/storage/exceptions/perfdata.hh" +#include "com/centreon/broker/storage/parser.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; @@ -452,7 +453,15 @@ static void l_stacktrace(lua_State* L) { static int l_broker_parse_perfdata(lua_State* L) { char const* perf_data(lua_tostring(L, 1)); int full(lua_toboolean(L, 2)); - std::list pds{misc::parse_perfdata(0, 0, perf_data)}; + storage::parser p; + std::list pds; + try { + p.parse_perfdata(0, 0, perf_data, pds); + } catch (storage::exceptions::perfdata const& e) { + lua_pushnil(L); + lua_pushstring(L, e.what()); + return 2; + } lua_createtable(L, 0, pds.size()); for (auto const& pd : pds) { lua_pushstring(L, pd.name().c_str()); diff --git a/centreon-broker/lua/src/luabinding.cc b/centreon-broker/lua/src/luabinding.cc index 4cf4b7b9d67..3a42cbb34a5 100644 --- a/centreon-broker/lua/src/luabinding.cc +++ b/centreon-broker/lua/src/luabinding.cc @@ -292,8 +292,8 @@ int luabinding::write(std::shared_ptr const& data) noexcept { // Process event. uint32_t type(data->type()); - uint16_t cat(category_of_type(type)); - uint16_t elem(element_of_type(type)); + unsigned short cat(io::events::category_of_type(type)); + unsigned short elem(io::events::element_of_type(type)); bool execute_write = true; diff --git a/centreon-broker/lua/src/main.cc b/centreon-broker/lua/src/main.cc index 753081b63d8..39a16c64808 100644 --- a/centreon-broker/lua/src/main.cc +++ b/centreon-broker/lua/src/main.cc @@ -1,5 +1,5 @@ /* -** Copyright 2017-2021 Centreon +** Copyright 2017-2018 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -16,8 +16,6 @@ ** For more information : contact@centreon.com */ -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/lua/factory.hh" @@ -26,7 +24,7 @@ using namespace com::centreon::broker; // Load count. -static uint32_t instances{0u}; +static uint32_t instances(0); extern "C" { /** @@ -40,7 +38,8 @@ char const* broker_module_version = CENTREON_BROKER_VERSION; * @return An array of const char* */ const char* const* broker_module_parents() { - constexpr static const char* retval[]{"10-neb.so", nullptr}; + constexpr static const char* retval[]{"10-neb.so", "20-bam.so", + "20-storage.so", nullptr}; return retval; } @@ -69,41 +68,6 @@ void broker_module_init(void const* arg) { log_v2::lua()->info("lua: module for Centreon Broker {}", CENTREON_BROKER_VERSION); - io::events& e(io::events::instance()); - - // Register events. - { - e.register_event(make_type(io::storage, storage::de_metric), "metric", - &storage::metric::operations, storage::metric::entries, - "rt_metrics"); - e.register_event(make_type(io::storage, storage::de_status), "status", - &storage::status::operations, storage::status::entries); - e.register_event(make_type(io::storage, storage::de_index_mapping), - "index_mapping", &storage::index_mapping::operations, - storage::index_mapping::entries); - e.register_event(make_type(io::storage, storage::de_metric_mapping), - "metric_mapping", &storage::metric_mapping::operations, - storage::metric_mapping::entries); - e.register_event( - make_type(io::bam, bam::de_dimension_ba_bv_relation_event), - "dimension_ba_bv_relation_event", - &bam::dimension_ba_bv_relation_event::operations, - bam::dimension_ba_bv_relation_event::entries); - e.register_event(make_type(io::bam, bam::de_dimension_ba_event), - "dimension_ba_event", - &bam::dimension_ba_event::operations, - bam::dimension_ba_event::entries); - e.register_event(make_type(io::bam, bam::de_dimension_bv_event), - "dimension_bv_event", - &bam::dimension_bv_event::operations, - bam::dimension_bv_event::entries); - e.register_event( - make_type(io::bam, bam::de_dimension_truncate_table_signal), - "dimension_truncate_table_signal", - &bam::dimension_truncate_table_signal::operations, - bam::dimension_truncate_table_signal::entries); - } - // Register lua layer. io::protocols::instance().reg("lua", std::make_shared(), 1, 7); diff --git a/centreon-broker/lua/test/lua.cc b/centreon-broker/lua/test/lua.cc index 20ad7cca6a6..e834478233d 100644 --- a/centreon-broker/lua/test/lua.cc +++ b/centreon-broker/lua/test/lua.cc @@ -25,7 +25,6 @@ #include #include "../../core/test/test_server.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/lua/luabinding.hh" @@ -34,6 +33,7 @@ #include "com/centreon/broker/misc/variant.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/neb/instance.hh" +#include "com/centreon/broker/storage/status.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; diff --git a/centreon-broker/neb/CMakeLists.txt b/centreon-broker/neb/CMakeLists.txt index 7973fdb8c24..269400a9dee 100644 --- a/centreon-broker/neb/CMakeLists.txt +++ b/centreon-broker/neb/CMakeLists.txt @@ -259,5 +259,5 @@ endif() # Install rules. install(TARGETS "${CBMOD}" - LIBRARY DESTINATION "${PREFIX_CBMOD}" + LIBRARY DESTINATION "${PREFIX_LIB}" ) diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/acknowledgement.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/acknowledgement.hh index 97b6e4aee94..c89be4df15f 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/acknowledgement.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/acknowledgement.hh @@ -53,7 +53,8 @@ class acknowledgement : public io::data { * @return The event type. */ constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } short acknowledgement_type; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/comment.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/comment.hh index fbdd12f326e..bf9a41b0121 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/comment.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/comment.hh @@ -44,7 +44,7 @@ class comment : public io::data { ~comment(); comment& operator=(comment const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } std::string author; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/custom_variable.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/custom_variable.hh index 68d16fc7680..e7ec9a72a0b 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/custom_variable.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/custom_variable.hh @@ -44,7 +44,8 @@ class custom_variable : public custom_variable_status { ~custom_variable(); custom_variable& operator=(custom_variable const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } std::string default_value; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/custom_variable_status.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/custom_variable_status.hh index 81376656f23..d740762319f 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/custom_variable_status.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/custom_variable_status.hh @@ -46,7 +46,7 @@ class custom_variable_status : public io::data { virtual ~custom_variable_status(); custom_variable_status& operator=(custom_variable_status const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; } diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/downtime.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/downtime.hh index 4c63c3247e9..9deb1e681eb 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/downtime.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/downtime.hh @@ -54,7 +54,7 @@ class downtime : public io::data { * @return The event type. */ constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } timestamp actual_end_time; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/event_handler.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/event_handler.hh index b2ebf32ea9d..334345c2fee 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/event_handler.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/event_handler.hh @@ -46,7 +46,7 @@ class event_handler : public io::data { ~event_handler(); event_handler& operator=(event_handler const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } std::string command_args; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/flapping_status.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/flapping_status.hh index c5bc82cdce3..ff4300f934c 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/flapping_status.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/flapping_status.hh @@ -44,7 +44,8 @@ class flapping_status : public io::data { ~flapping_status(); flapping_status& operator=(flapping_status const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } timestamp event_time; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/host.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/host.hh index 650463023cb..6989833936a 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/host.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/host.hh @@ -48,7 +48,7 @@ class host : public host_service, public host_status { ~host(); host& operator=(host const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } std::string address; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/host_check.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/host_check.hh index 452172afc98..ce76eef1d91 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/host_check.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/host_check.hh @@ -43,7 +43,7 @@ class host_check : public check { virtual ~host_check(); host_check& operator=(host_check const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/host_dependency.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/host_dependency.hh index 3b1c9a38484..235c7907761 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/host_dependency.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/host_dependency.hh @@ -43,7 +43,8 @@ class host_dependency : public dependency { ~host_dependency(); host_dependency& operator=(host_dependency const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/host_group.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/host_group.hh index 3df05a29c99..aab46fb3682 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/host_group.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/host_group.hh @@ -42,7 +42,7 @@ class host_group : public group { ~host_group(); host_group& operator=(host_group const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/host_group_member.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/host_group_member.hh index cdacfdd42dd..9854313fe82 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/host_group_member.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/host_group_member.hh @@ -46,7 +46,8 @@ class host_group_member : public group_member { virtual ~host_group_member(); host_group_member& operator=(host_group_member const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/host_parent.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/host_parent.hh index 6e740cdb056..ca3d886d88d 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/host_parent.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/host_parent.hh @@ -42,7 +42,7 @@ class host_parent : public io::data { ~host_parent(); host_parent& operator=(host_parent const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } bool enabled; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/host_status.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/host_status.hh index f343c49bcc9..3276cf618dc 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/host_status.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/host_status.hh @@ -44,7 +44,7 @@ class host_status : public host_service_status { virtual ~host_status(); host_status& operator=(host_status const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } timestamp last_time_down; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/instance.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/instance.hh index 588cc8ebb04..30890ca94dd 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/instance.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/instance.hh @@ -46,7 +46,7 @@ class instance : public io::data { ~instance(); instance& operator=(instance const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } std::string engine; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/instance_configuration.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/instance_configuration.hh index 065cee61d65..365a976fb67 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/instance_configuration.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/instance_configuration.hh @@ -47,7 +47,7 @@ class instance_configuration : public io::data { ~instance_configuration(); instance_configuration& operator=(instance_configuration const& i); constexpr static uint32_t static_type() { - return io::events::data_type::value; } diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/instance_status.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/instance_status.hh index 4869012d798..2377355d28c 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/instance_status.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/instance_status.hh @@ -48,7 +48,8 @@ class instance_status : public status { ~instance_status(); instance_status& operator=(instance_status const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } bool active_host_checks_enabled; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/log_entry.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/log_entry.hh index 2b597f7b570..78caa810101 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/log_entry.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/log_entry.hh @@ -65,7 +65,7 @@ class log_entry : public io::data { ~log_entry(); log_entry& operator=(const log_entry& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } timestamp c_time; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/module.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/module.hh index 8b168e966e2..16801f71c62 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/module.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/module.hh @@ -45,7 +45,7 @@ class module : public io::data { ~module(); module& operator=(module const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } std::string args; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/responsive_instance.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/responsive_instance.hh index 38afd42ace0..bd47934b6f4 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/responsive_instance.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/responsive_instance.hh @@ -42,7 +42,8 @@ class responsive_instance : public io::data { ~responsive_instance(); responsive_instance& operator=(responsive_instance const& i); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t poller_id; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/service.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/service.hh index 0c0dfbdf3a5..4d71666a6c4 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/service.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/service.hh @@ -50,7 +50,7 @@ class service : public host_service, public service_status { ~service(); service& operator=(service const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } bool flap_detection_on_critical; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/service_check.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/service_check.hh index aaa854ddd72..58cd651bfa4 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/service_check.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/service_check.hh @@ -44,7 +44,7 @@ class service_check : public check { virtual ~service_check(); service_check& operator=(service_check const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t service_id; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/service_dependency.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/service_dependency.hh index ba28629f93d..d004b36905e 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/service_dependency.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/service_dependency.hh @@ -43,7 +43,8 @@ class service_dependency : public dependency { ~service_dependency(); service_dependency& operator=(service_dependency const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t dependent_service_id; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/service_group.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/service_group.hh index a132330dd42..0e511e31203 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/service_group.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/service_group.hh @@ -43,7 +43,7 @@ class service_group : public group { ~service_group(); service_group& operator=(service_group const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/service_group_member.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/service_group_member.hh index 7271f1ea928..29bb2a65b30 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/service_group_member.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/service_group_member.hh @@ -47,7 +47,8 @@ class service_group_member : public group_member { virtual ~service_group_member(); service_group_member& operator=(service_group_member const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint32_t service_id; diff --git a/centreon-broker/neb/inc/com/centreon/broker/neb/service_status.hh b/centreon-broker/neb/inc/com/centreon/broker/neb/service_status.hh index 16c48f84168..5abf4e2c070 100644 --- a/centreon-broker/neb/inc/com/centreon/broker/neb/service_status.hh +++ b/centreon-broker/neb/inc/com/centreon/broker/neb/service_status.hh @@ -45,7 +45,8 @@ class service_status : public host_service_status { virtual ~service_status(); service_status& operator=(service_status const& other); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } std::string host_name; diff --git a/centreon-broker/neb/inc/com/centreon/clib/version.hh b/centreon-broker/neb/inc/com/centreon/clib/version.hh index 493aaa06b76..89a8279b63b 100644 --- a/centreon-broker/neb/inc/com/centreon/clib/version.hh +++ b/centreon-broker/neb/inc/com/centreon/clib/version.hh @@ -17,34 +17,34 @@ */ #ifndef CC_CLIB_VERSION_HH -#define CC_CLIB_VERSION_HH +# define CC_CLIB_VERSION_HH // Compile-time values. -#define CENTREON_CLIB_VERSION_MAJOR 21 -#define CENTREON_CLIB_VERSION_MINOR 04 -#define CENTREON_CLIB_VERSION_PATCH 2 -#define CENTREON_CLIB_VERSION_STRING "21.04.2" +# define CENTREON_CLIB_VERSION_MAJOR 21 +# define CENTREON_CLIB_VERSION_MINOR 04 +# define CENTREON_CLIB_VERSION_PATCH 2 +# define CENTREON_CLIB_VERSION_STRING "21.04.2" -#include "com/centreon/namespace.hh" +# include "com/centreon/namespace.hh" CC_BEGIN() -namespace clib { -namespace version { -// Compile-time values. -unsigned int const major = 21; -unsigned int const minor = 04; -unsigned int const patch = 2; -char const* const string = "21.04.2"; - -// Run-time values. -unsigned int get_major() throw(); -unsigned int get_minor() throw(); -unsigned int get_patch() throw(); -char const* get_string() throw(); -} // namespace version -} // namespace clib +namespace clib { + namespace version { + // Compile-time values. + unsigned int const major = 21; + unsigned int const minor = 04; + unsigned int const patch = 2; + char const* const string = "21.04.2"; + + // Run-time values. + unsigned int get_major() throw (); + unsigned int get_minor() throw (); + unsigned int get_patch() throw (); + char const* get_string() throw (); + } +} CC_END() -#endif // !CC_HANDLE_HH +#endif // !CC_HANDLE_HH diff --git a/centreon-broker/neb/inc/com/centreon/clib/version.hh.in b/centreon-broker/neb/inc/com/centreon/clib/version.hh.in index dea870844df..74e410192dc 100644 --- a/centreon-broker/neb/inc/com/centreon/clib/version.hh.in +++ b/centreon-broker/neb/inc/com/centreon/clib/version.hh.in @@ -20,9 +20,9 @@ # define CC_CLIB_VERSION_HH // Compile-time values. -# define CENTREON_CLIB_VERSION_MAJOR @COLLECT_MAJOR@ -# define CENTREON_CLIB_VERSION_MINOR @COLLECT_MINOR@ -# define CENTREON_CLIB_VERSION_PATCH @COLLECT_PATCH@ +# define CENTREON_CLIB_VERSION_MAJOR @CLIB_MAJOR@ +# define CENTREON_CLIB_VERSION_MINOR @CLIB_MINOR@ +# define CENTREON_CLIB_VERSION_PATCH @CLIB_PATCH@ # define CENTREON_CLIB_VERSION_STRING "@CLIB_VERSION@" # include "com/centreon/namespace.hh" @@ -32,16 +32,16 @@ CC_BEGIN() namespace clib { namespace version { // Compile-time values. - unsigned int const major = @COLLECT_MAJOR@; - unsigned int const minor = @COLLECT_MINOR@; - unsigned int const patch = @COLLECT_PATCH@; + unsigned int const major = @CLIB_MAJOR@; + unsigned int const minor = @CLIB_MINOR@; + unsigned int const patch = @CLIB_PATCH@; char const* const string = "@CLIB_VERSION@"; // Run-time values. - unsigned int get_major() noexcept; - unsigned int get_minor() noexcept; - unsigned int get_patch() noexcept; - char const* get_string() noexcept; + unsigned int get_major() throw (); + unsigned int get_minor() throw (); + unsigned int get_patch() throw (); + char const* get_string() throw (); } } diff --git a/centreon-broker/neb/inc/com/centreon/clib_lock_guard.hh b/centreon-broker/neb/inc/com/centreon/clib_lock_guard.hh index 20fda67f16f..78b89b14950 100644 --- a/centreon-broker/neb/inc/com/centreon/clib_lock_guard.hh +++ b/centreon-broker/neb/inc/com/centreon/clib_lock_guard.hh @@ -23,14 +23,13 @@ #define DEBUG_CLIB #ifdef DEBUG_CLIB -template +template class clib_lock_guard : public std::lock_guard { static const constexpr char* filename = "/tmp/lock.log"; const char* _msg; public: - explicit clib_lock_guard(M& m, const char* msg) - : std::lock_guard(m), _msg(msg) { + explicit clib_lock_guard(M& m, const char* msg) : std::lock_guard(m), _msg(msg) { FILE* f = fopen(filename, "a+"); fprintf(f, "lock_guard lock mutex '%s'\n", _msg); fclose(f); @@ -43,14 +42,13 @@ class clib_lock_guard : public std::lock_guard { } }; -template +template class clib_unique_lock : public std::unique_lock { static const constexpr char* filename = "/tmp/lock.log"; const char* _msg; public: - explicit clib_unique_lock(M& m, const char* msg) - : std::unique_lock(m), _msg(msg) { + explicit clib_unique_lock(M& m, const char* msg) : std::unique_lock(m), _msg(msg) { FILE* f = fopen(filename, "a+"); fprintf(f, "unique_lock lock mutex '%s'\n", _msg); fclose(f); @@ -77,18 +75,18 @@ class clib_unique_lock : public std::unique_lock { } }; #else -template +template class clib_lock_guard : public std::lock_guard { public: - explicit clib_lock_guard(M& m, const char* msg __attribute__((unused))) - : std::lock_guard(m) {} + explicit clib_lock_guard(M& m, const char* msg __attribute__((unused))) : std::lock_guard(m) { + } }; -template +template class clib_unique_lock : public std::unique_lock { public: - explicit clib_unique_lock(M& m, const char* msg __attribute__((unused))) - : std::unique_lock(m) {} + explicit clib_unique_lock(M& m, const char* msg __attribute__((unused))) : std::unique_lock(m) { + } }; #endif diff --git a/centreon-broker/neb/inc/com/centreon/engine/anomalydetection.hh b/centreon-broker/neb/inc/com/centreon/engine/anomalydetection.hh index 896033a3f6e..0ea46c9a45c 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/anomalydetection.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/anomalydetection.hh @@ -20,9 +20,9 @@ #ifndef CCE_ANOMALYDETECTION_HH #define CCE_ANOMALYDETECTION_HH +#include #include #include -#include #include #include "com/centreon/engine/service.hh" diff --git a/centreon-broker/neb/inc/com/centreon/engine/commands/command_listener.hh b/centreon-broker/neb/inc/com/centreon/engine/commands/command_listener.hh index 567934c9f1c..541c659adad 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/commands/command_listener.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/commands/command_listener.hh @@ -29,7 +29,7 @@ CCE_BEGIN() namespace commands { -class command; + class command; /** * @class command_listener command_listener.hh * @brief Notify command events. @@ -42,7 +42,7 @@ class command_listener { public: virtual ~command_listener() noexcept { for (auto it = _clean_callbacks.begin(), end = _clean_callbacks.end(); - it != end; ++it) { + it != end; ++it) { (it->second)(); } } @@ -51,7 +51,9 @@ class command_listener { void reg(command* const ptr, std::function& regf) { _clean_callbacks.insert({ptr, regf}); } - void unreg(command* const ptr) { _clean_callbacks.erase(ptr); } + void unreg(command* const ptr) { + _clean_callbacks.erase(ptr); + } }; } // namespace commands diff --git a/centreon-broker/neb/inc/com/centreon/engine/configuration/anomalydetection.hh b/centreon-broker/neb/inc/com/centreon/engine/configuration/anomalydetection.hh index f75764e88a1..3e7ce6729a9 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/configuration/anomalydetection.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/configuration/anomalydetection.hh @@ -227,8 +227,7 @@ class anomalydetection : public object { typedef std::shared_ptr anomalydetection_ptr; typedef std::list list_anomalydetection; typedef std::set set_anomalydetection; -typedef std::unordered_map, - anomalydetection_ptr> +typedef std::unordered_map, anomalydetection_ptr> map_anomalydetection; } // namespace configuration diff --git a/centreon-broker/neb/inc/com/centreon/engine/configuration/applier/scheduler.hh b/centreon-broker/neb/inc/com/centreon/engine/configuration/applier/scheduler.hh index 0ff83edd33e..69b1635bfcb 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/configuration/applier/scheduler.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/configuration/applier/scheduler.hh @@ -23,8 +23,8 @@ #include #include #include "com/centreon/engine/configuration/applier/difference.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/configuration/state.hh" // Forward declaration. CCE_BEGIN() diff --git a/centreon-broker/neb/inc/com/centreon/engine/configuration/applier/state.hh b/centreon-broker/neb/inc/com/centreon/engine/configuration/applier/state.hh index eac33f5f3d5..115c945a4c7 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/configuration/applier/state.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/configuration/applier/state.hh @@ -21,8 +21,8 @@ #define CCE_CONFIGURATION_APPLIER_STATE_HH #include -#include #include +#include #include #include "com/centreon/engine/configuration/applier/difference.hh" #include "com/centreon/engine/configuration/state.hh" diff --git a/centreon-broker/neb/inc/com/centreon/engine/configuration/parser.hh b/centreon-broker/neb/inc/com/centreon/engine/configuration/parser.hh index a51edcba2a2..2c3880caf1e 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/configuration/parser.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/configuration/parser.hh @@ -20,8 +20,8 @@ #ifndef CCE_CONFIGURATION_PARSER_HH #define CCE_CONFIGURATION_PARSER_HH -#include #include +#include #include #include "com/centreon/engine/configuration/command.hh" #include "com/centreon/engine/configuration/connector.hh" diff --git a/centreon-broker/neb/inc/com/centreon/engine/downtimes/downtime.hh b/centreon-broker/neb/inc/com/centreon/engine/downtimes/downtime.hh index db0be7f8dd0..10cce56716c 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/downtimes/downtime.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/downtimes/downtime.hh @@ -30,7 +30,11 @@ CCE_BEGIN() namespace downtimes { class downtime { public: - enum type { service_downtime = 1, host_downtime = 2, any_downtime = 3 }; + enum type { + service_downtime = 1, + host_downtime = 2, + any_downtime = 3 + }; downtime(type type, std::string const& host_name, time_t entry_time, diff --git a/centreon-broker/neb/inc/com/centreon/engine/downtimes/downtime_manager.hh b/centreon-broker/neb/inc/com/centreon/engine/downtimes/downtime_manager.hh index 828a93a0aba..9ce44254c0b 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/downtimes/downtime_manager.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/downtimes/downtime_manager.hh @@ -37,8 +37,7 @@ class downtime_manager { void delete_downtime(uint64_t downtime_id); int unschedule_downtime(uint64_t downtime_id); - std::shared_ptr find_downtime(downtime::type type, - uint64_t downtime_id); + std::shared_ptr find_downtime(downtime::type type, uint64_t downtime_id); int check_pending_flex_host_downtime(host* hst); int check_pending_flex_service_downtime(service* svc); void add_downtime(downtime* dt) noexcept; diff --git a/centreon-broker/neb/inc/com/centreon/engine/engine_impl.hh b/centreon-broker/neb/inc/com/centreon/engine/engine_impl.hh index 9cf26739933..68e8375994d 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/engine_impl.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/engine_impl.hh @@ -9,7 +9,7 @@ class engine_impl final : public Engine::Service { grpc::Status GetVersion(grpc::ServerContext* context, const ::google::protobuf::Empty* /*request*/, Version* response) override; - grpc::Status GetStats(grpc::ServerContext* context, + grpc::Status GetStats(grpc::ServerContext* context, const GenericString* request, Stats* response) override; grpc::Status ProcessServiceCheckResult(grpc::ServerContext* context, @@ -118,8 +118,8 @@ class engine_impl final : public Engine::Service { const ScheduleDowntimeIdentifier* request, CommandSuccess* response) override; grpc::Status DeleteDowntime(grpc::ServerContext* context, - const GenericValue* request, - CommandSuccess* response) override; + const GenericValue* request, + CommandSuccess* response) override; grpc::Status DeleteHostDowntimeFull(grpc::ServerContext* context, const DowntimeCriterias* request, CommandSuccess* response) override; @@ -187,8 +187,8 @@ class engine_impl final : public Engine::Service { const ChangeObjectCustomVar* request, CommandSuccess* response) override; grpc::Status ShutdownProgram(grpc::ServerContext* context, - const ::google::protobuf::Empty*, - ::google::protobuf::Empty*) override; + const ::google::protobuf::Empty*, + ::google::protobuf::Empty*) override; }; CCE_END() diff --git a/centreon-broker/neb/inc/com/centreon/engine/events/loop.hh b/centreon-broker/neb/inc/com/centreon/engine/events/loop.hh index dfb7579c236..47863d8b71c 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/events/loop.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/events/loop.hh @@ -57,7 +57,11 @@ class loop { void _dispatching(); public: - enum priority { low = 0, high = 1, priority_num }; + enum priority { + low = 0, + high = 1, + priority_num + }; static loop& instance(); void clear(); @@ -69,7 +73,9 @@ class loop { void remove_downtime(uint64_t downtime_id); void remove_event(timed_event* event, priority priority); void remove_events(priority, uint32_t event_type, void* data) noexcept; - timed_event* find_event(priority priority, uint32_t event_type, void* data); + timed_event* find_event(priority priority, + uint32_t event_type, + void* data); void reschedule_event(timed_event* event, priority priority); void resort_event_list(priority priority); void schedule(timed_event* evt, bool high_priority); diff --git a/centreon-broker/neb/inc/com/centreon/engine/events/timed_event.hh b/centreon-broker/neb/inc/com/centreon/engine/events/timed_event.hh index acd70d1baaa..66d712a7d0d 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/events/timed_event.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/events/timed_event.hh @@ -23,9 +23,9 @@ #ifndef CCE_EVENTS_TIMED_EVENT_HH #define CCE_EVENTS_TIMED_EVENT_HH +#include #include #include -#include #include "com/centreon/engine/downtimes/downtime.hh" #include "com/centreon/engine/namespace.hh" diff --git a/centreon-broker/neb/inc/com/centreon/engine/exceptions/error.hh b/centreon-broker/neb/inc/com/centreon/engine/exceptions/error.hh index bc0abdb0129..80d53bd3614 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/exceptions/error.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/exceptions/error.hh @@ -61,7 +61,7 @@ class error : public std::exception { char const* what() const throw() override; }; -} // namespace exceptions +} CCE_END() diff --git a/centreon-broker/neb/inc/com/centreon/engine/my_lock.hh b/centreon-broker/neb/inc/com/centreon/engine/my_lock.hh index 4be35dfe334..f5273a7622f 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/my_lock.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/my_lock.hh @@ -1,5 +1,5 @@ -#include #include +#include template class my_lock_guard : public std::lock_guard { @@ -8,15 +8,12 @@ class my_lock_guard : public std::lock_guard { M* _m; public: - my_lock_guard(M& m, const char* file, int line) - : std::lock_guard(m), _file{file}, _line{line}, _m(&m) { - std::cout << "Lock(G): " << _file << ": " << _m << ":" << _line - << std::endl; + my_lock_guard(M& m, const char* file, int line) : std::lock_guard(m), _file{file}, _line{line}, _m(&m) { + std::cout << "Lock(G): " << _file << ": " << _m << ":" << _line << std::endl; } ~my_lock_guard() { - std::cout << "Unlock(G): " << _file << ": " << _m << ":" << _line - << std::endl; + std::cout << "Unlock(G): " << _file << ": " << _m << ":" << _line << std::endl; } }; @@ -27,20 +24,16 @@ class my_unique_lock : public std::unique_lock { M* _m; public: - my_unique_lock(M& m, const char* file, int line) - : std::unique_lock(m), _file{file}, _line{line}, _m{&m} { - std::cout << "Lock(U): " << _file << ": " << _m << ":" << _line - << std::endl; + my_unique_lock(M& m, const char* file, int line) : std::unique_lock(m), _file{file}, _line{line}, _m{&m} { + std::cout << "Lock(U): " << _file << ": " << _m << ":" << _line << std::endl; } ~my_unique_lock() { - std::cout << "Destroy Lock(U): " << _file << ": " << _m << ":" << _line - << std::endl; + std::cout << "Destroy Lock(U): " << _file << ": " << _m << ":" << _line << std::endl; } void unlock(int line) { - std::cout << "unlock(): " << _file << ": " << _m << ":" << line - << std::endl; + std::cout << "unlock(): " << _file << ": " << _m << ":" << line << std::endl; std::unique_lock::unlock(); } diff --git a/centreon-broker/neb/inc/com/centreon/engine/nebstructs.hh b/centreon-broker/neb/inc/com/centreon/engine/nebstructs.hh index c9cdc103bbf..3fe26753828 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/nebstructs.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/nebstructs.hh @@ -320,8 +320,8 @@ typedef struct nebstruct_flapping_struct { struct timeval timestamp; int flapping_type; - uint64_t host_id; - uint64_t service_id; + uint64_t host_id; + uint64_t service_id; double percent_change; double high_threshold; double low_threshold; diff --git a/centreon-broker/neb/inc/com/centreon/engine/opt.hh b/centreon-broker/neb/inc/com/centreon/engine/opt.hh index c4469051906..6d00eb0a05f 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/opt.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/opt.hh @@ -49,7 +49,7 @@ class opt { bool operator<(opt const& right) const throw() { return (_data < right._data); } - operator T const &() const throw() { return (_data); } + operator T const&() const throw() { return (_data); } T& operator*() throw() { return (_data); } T const& operator*() const throw() { return (_data); } T* operator->() throw() { return (&_data); } diff --git a/centreon-broker/neb/inc/com/centreon/engine/statistics.hh b/centreon-broker/neb/inc/com/centreon/engine/statistics.hh index 78db97f2344..296ab38961a 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/statistics.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/statistics.hh @@ -20,9 +20,9 @@ #ifndef CCE_STATISTICS_HH #define CCE_STATISTICS_HH +#include #include #include -#include #include "com/centreon/engine/namespace.hh" struct buffer_stats { @@ -34,7 +34,6 @@ struct buffer_stats { CCE_BEGIN() class statistics { statistics(); - public: static statistics& instance(); pid_t get_pid() const noexcept; diff --git a/centreon-broker/neb/inc/com/centreon/engine/timezone_manager.hh b/centreon-broker/neb/inc/com/centreon/engine/timezone_manager.hh index cfadc1b0369..a80c12df795 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/timezone_manager.hh +++ b/centreon-broker/neb/inc/com/centreon/engine/timezone_manager.hh @@ -44,10 +44,7 @@ class timezone_manager { * * @return Class instance. */ - static timezone_manager& instance() { - static timezone_manager instance; - return instance; - } + static timezone_manager& instance() { static timezone_manager instance; return instance; } private: struct tz_info { diff --git a/centreon-broker/neb/inc/com/centreon/engine/version.hh.in b/centreon-broker/neb/inc/com/centreon/engine/version.hh.in index c6f1dd8ede7..b442c09fa96 100644 --- a/centreon-broker/neb/inc/com/centreon/engine/version.hh.in +++ b/centreon-broker/neb/inc/com/centreon/engine/version.hh.in @@ -21,9 +21,9 @@ #define CCE_VERSION_HH // Compile-time values. -#define CENTREON_ENGINE_VERSION_MAJOR @COLLECT_MAJOR@ -#define CENTREON_ENGINE_VERSION_MINOR @COLLECT_MINOR@ -#define CENTREON_ENGINE_VERSION_PATCH @COLLECT_PATCH@ +#define CENTREON_ENGINE_VERSION_MAJOR @CENTREON_ENGINE_MAJOR@ +#define CENTREON_ENGINE_VERSION_MINOR @CENTREON_ENGINE_MINOR@ +#define CENTREON_ENGINE_VERSION_PATCH @CENTREON_ENGINE_PATCH@ #define CENTREON_ENGINE_VERSION_STRING "@CENTREON_ENGINE_VERSION@" #endif // !CCE_VERSION_HH diff --git a/centreon-broker/neb/inc/com/centreon/exceptions/basic.hh b/centreon-broker/neb/inc/com/centreon/exceptions/basic.hh index 4ff4c7f824d..442f2ea3ed9 100644 --- a/centreon-broker/neb/inc/com/centreon/exceptions/basic.hh +++ b/centreon-broker/neb/inc/com/centreon/exceptions/basic.hh @@ -50,7 +50,7 @@ class basic : public std::exception { misc::stringifier _buffer; }; -} // namespace exceptions +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/exceptions/interruption.hh b/centreon-broker/neb/inc/com/centreon/exceptions/interruption.hh index e3f25e3be25..5c5d47f73d9 100644 --- a/centreon-broker/neb/inc/com/centreon/exceptions/interruption.hh +++ b/centreon-broker/neb/inc/com/centreon/exceptions/interruption.hh @@ -47,7 +47,7 @@ class interruption : public basic { return (*this); } }; -} // namespace exceptions +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/io/directory_entry.hh b/centreon-broker/neb/inc/com/centreon/io/directory_entry.hh index a6a755bb985..cf6ebf3ab6e 100644 --- a/centreon-broker/neb/inc/com/centreon/io/directory_entry.hh +++ b/centreon-broker/neb/inc/com/centreon/io/directory_entry.hh @@ -21,8 +21,8 @@ #include #include -#include "com/centreon/handle.hh" #include "com/centreon/io/file_entry.hh" +#include "com/centreon/handle.hh" #include "com/centreon/namespace.hh" CC_BEGIN() @@ -55,7 +55,7 @@ class directory_entry { file_entry _entry; std::list _entry_lst; }; -} // namespace io +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/io/file_entry.hh b/centreon-broker/neb/inc/com/centreon/io/file_entry.hh index ce9b240da19..cd3576d0e25 100644 --- a/centreon-broker/neb/inc/com/centreon/io/file_entry.hh +++ b/centreon-broker/neb/inc/com/centreon/io/file_entry.hh @@ -19,9 +19,9 @@ #ifndef CC_IO_FILE_ENTRY_HH #define CC_IO_FILE_ENTRY_HH -#include -#include #include +#include +#include #include "com/centreon/handle.hh" #include "com/centreon/namespace.hh" @@ -65,7 +65,7 @@ class file_entry { std::string _path; struct stat _sbuf; }; -} // namespace io +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/io/file_stream.hh b/centreon-broker/neb/inc/com/centreon/io/file_stream.hh index 9f31b6ed761..8737b6258af 100644 --- a/centreon-broker/neb/inc/com/centreon/io/file_stream.hh +++ b/centreon-broker/neb/inc/com/centreon/io/file_stream.hh @@ -63,7 +63,7 @@ class file_stream : public handle { bool _auto_close; FILE* _stream; }; -} // namespace io +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/logging/backend.hh b/centreon-broker/neb/inc/com/centreon/logging/backend.hh index 2864f666188..6da9ee6fb55 100644 --- a/centreon-broker/neb/inc/com/centreon/logging/backend.hh +++ b/centreon-broker/neb/inc/com/centreon/logging/backend.hh @@ -29,7 +29,12 @@ class stringifier; } namespace logging { -enum time_precision { none = 0, microsecond = 1, millisecond = 2, second = 3 }; +enum time_precision { + none = 0, + microsecond = 1, + millisecond = 2, + second = 3 +}; /** * @class backend backend.hh "com/centreon/logging/backend.hh" @@ -76,7 +81,7 @@ class backend { protected: void _internal_copy(backend const& right); }; -} // namespace logging +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/logging/file.hh b/centreon-broker/neb/inc/com/centreon/logging/file.hh index ed6f33b79b1..c04b2aeccc7 100644 --- a/centreon-broker/neb/inc/com/centreon/logging/file.hh +++ b/centreon-broker/neb/inc/com/centreon/logging/file.hh @@ -68,7 +68,7 @@ class file : public backend { FILE* _out; uint64_t _size; }; -} // namespace logging +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/logging/logger.hh b/centreon-broker/neb/inc/com/centreon/logging/logger.hh index 69aced161ff..42b809b9392 100644 --- a/centreon-broker/neb/inc/com/centreon/logging/logger.hh +++ b/centreon-broker/neb/inc/com/centreon/logging/logger.hh @@ -30,16 +30,20 @@ enum type_value { type_error = (1ull << 63) }; -enum verbosity_level { low = 0, medium = 1, high = 2 }; -} // namespace logging +enum verbosity_level { + low = 0, + medium = 1, + high = 2 +}; +} CC_END() #define log_info(verbose) \ for (unsigned int __com_centreon_logging_define_ui(0); \ !__com_centreon_logging_define_ui && \ - com::centreon::logging::engine::instance().is_log( \ - com::centreon::logging::type_info, verbose); \ + com::centreon::logging::engine::instance().is_log( \ + com::centreon::logging::type_info, verbose); \ ++__com_centreon_logging_define_ui) \ com::centreon::logging::temp_logger(com::centreon::logging::type_info, \ verbose) \ @@ -48,8 +52,8 @@ CC_END() #define log_debug(verbose) \ for (unsigned int __com_centreon_logging_define_ui(0); \ !__com_centreon_logging_define_ui && \ - com::centreon::logging::engine::instance().is_log( \ - com::centreon::logging::type_debug, verbose); \ + com::centreon::logging::engine::instance().is_log( \ + com::centreon::logging::type_debug, verbose); \ ++__com_centreon_logging_define_ui) \ com::centreon::logging::temp_logger(com::centreon::logging::type_debug, \ verbose) \ @@ -58,8 +62,8 @@ CC_END() #define log_error(verbose) \ for (unsigned int __com_centreon_logging_define_ui(0); \ !__com_centreon_logging_define_ui && \ - com::centreon::logging::engine::instance().is_log( \ - com::centreon::logging::type_error, verbose); \ + com::centreon::logging::engine::instance().is_log( \ + com::centreon::logging::type_error, verbose); \ ++__com_centreon_logging_define_ui) \ com::centreon::logging::temp_logger(com::centreon::logging::type_error, \ verbose) \ diff --git a/centreon-broker/neb/inc/com/centreon/logging/syslogger.hh b/centreon-broker/neb/inc/com/centreon/logging/syslogger.hh index b699356283e..c0ec7e6a13f 100644 --- a/centreon-broker/neb/inc/com/centreon/logging/syslogger.hh +++ b/centreon-broker/neb/inc/com/centreon/logging/syslogger.hh @@ -54,7 +54,7 @@ class syslogger : public backend { int _facility; std::string _id; }; -} // namespace logging +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/logging/temp_logger.hh b/centreon-broker/neb/inc/com/centreon/logging/temp_logger.hh index 1527dd4a318..d2d0cfc95e7 100644 --- a/centreon-broker/neb/inc/com/centreon/logging/temp_logger.hh +++ b/centreon-broker/neb/inc/com/centreon/logging/temp_logger.hh @@ -21,8 +21,8 @@ #include #include "com/centreon/logging/engine.hh" -#include "com/centreon/misc/stringifier.hh" #include "com/centreon/namespace.hh" +#include "com/centreon/misc/stringifier.hh" CC_BEGIN() @@ -59,7 +59,7 @@ class temp_logger { unsigned long long _type; unsigned int _verbose; }; -} // namespace logging +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/misc/argument.hh b/centreon-broker/neb/inc/com/centreon/misc/argument.hh index 6566b725ab2..d0c32dcb426 100644 --- a/centreon-broker/neb/inc/com/centreon/misc/argument.hh +++ b/centreon-broker/neb/inc/com/centreon/misc/argument.hh @@ -67,7 +67,7 @@ class argument { char _name; std::string _value; }; -} // namespace misc +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/misc/command_line.hh b/centreon-broker/neb/inc/com/centreon/misc/command_line.hh index ce44383d47d..7182df6e669 100644 --- a/centreon-broker/neb/inc/com/centreon/misc/command_line.hh +++ b/centreon-broker/neb/inc/com/centreon/misc/command_line.hh @@ -55,7 +55,7 @@ class command_line { char** _argv; size_t _size; }; -} // namespace misc +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/misc/get_options.hh b/centreon-broker/neb/inc/com/centreon/misc/get_options.hh index 8eca923d723..1d81b06c221 100644 --- a/centreon-broker/neb/inc/com/centreon/misc/get_options.hh +++ b/centreon-broker/neb/inc/com/centreon/misc/get_options.hh @@ -22,8 +22,8 @@ #include #include #include -#include "com/centreon/misc/argument.hh" #include "com/centreon/namespace.hh" +#include "com/centreon/misc/argument.hh" CC_BEGIN() @@ -74,7 +74,7 @@ class get_options { std::string& key, std::string& value); }; -} // namespace misc +} CC_END() diff --git a/centreon-broker/neb/inc/com/centreon/misc/stringifier.hh b/centreon-broker/neb/inc/com/centreon/misc/stringifier.hh index 3f640fba25a..c11239f1e80 100644 --- a/centreon-broker/neb/inc/com/centreon/misc/stringifier.hh +++ b/centreon-broker/neb/inc/com/centreon/misc/stringifier.hh @@ -75,7 +75,7 @@ class stringifier { static unsigned int const _static_buffer_size = 1024; char _static_buffer[_static_buffer_size]; }; -} // namespace misc +} CC_END() diff --git a/centreon-broker/neb/src/acknowledgement.cc b/centreon-broker/neb/src/acknowledgement.cc index 2526f12aed0..4c1380d608d 100644 --- a/centreon-broker/neb/src/acknowledgement.cc +++ b/centreon-broker/neb/src/acknowledgement.cc @@ -160,5 +160,4 @@ mapping::entry const acknowledgement::entries[] = { static io::data* new_ack() { return new acknowledgement; } -io::event_info::event_operations const acknowledgement::operations = { - &new_ack, nullptr, nullptr}; +io::event_info::event_operations const acknowledgement::operations = {&new_ack}; diff --git a/centreon-broker/neb/src/broker.cc b/centreon-broker/neb/src/broker.cc index 0ae13ea6479..fd35c19c031 100644 --- a/centreon-broker/neb/src/broker.cc +++ b/centreon-broker/neb/src/broker.cc @@ -43,7 +43,7 @@ void broker_module_deinit() { // io::protocols::instance().unreg("node_events"); // Remove events. - io::events::instance().unregister_category(io::neb); + io::events::instance().unregister_category(io::events::neb); } } @@ -59,92 +59,111 @@ void broker_module_init(void const* arg) { CENTREON_BROKER_VERSION); io::events& e(io::events::instance()); + // Register category. + int neb_category(e.register_category("neb", io::events::neb)); + if (neb_category != io::events::neb) { + e.unregister_category(neb_category); + --neb_instances; + throw msg_fmt( + "NEB: category {}" + " is already registered whereas it should be " + "reserved for the NEB module", + io::events::neb); + } + // Register events. { - e.register_event(make_type(io::neb, neb::de_acknowledgement), + e.register_event(io::events::neb, neb::de_acknowledgement, "acknowledgement", &neb::acknowledgement::operations, neb::acknowledgement::entries, "acknowledgements"); - e.register_event(make_type(io::neb, neb::de_comment), "comment", + e.register_event(io::events::neb, neb::de_comment, "comment", &neb::comment::operations, neb::comment::entries, "comments"); - e.register_event(make_type(io::neb, neb::de_custom_variable), + e.register_event(io::events::neb, neb::de_custom_variable, "custom_variable", &neb::custom_variable::operations, neb::custom_variable::entries, "customvariables"); - e.register_event(make_type(io::neb, neb::de_custom_variable_status), + e.register_event(io::events::neb, neb::de_custom_variable_status, "custom_variable_status", &neb::custom_variable_status::operations, neb::custom_variable_status::entries, "customvariables"); - e.register_event(make_type(io::neb, neb::de_downtime), "downtime", + e.register_event(io::events::neb, neb::de_downtime, "downtime", &neb::downtime::operations, neb::downtime::entries, "downtimes"); - e.register_event(make_type(io::neb, neb::de_event_handler), - "event_handler", &neb::event_handler::operations, + e.register_event(io::events::neb, neb::de_event_handler, "event_handler", + &neb::event_handler::operations, neb::event_handler::entries, "eventhandlers"); - e.register_event(make_type(io::neb, neb::de_flapping_status), + e.register_event(io::events::neb, neb::de_flapping_status, "flapping_status", &neb::flapping_status::operations, neb::flapping_status::entries, "flappingstatuses"); - e.register_event(make_type(io::neb, neb::de_host_check), "host_check", + e.register_event(io::events::neb, neb::de_host_check, "host_check", &neb::host_check::operations, neb::host_check::entries, "hosts"); - e.register_event(make_type(io::neb, neb::de_host_dependency), + e.register_event(io::events::neb, neb::de_host_dependency, "host_dependency", &neb::host_dependency::operations, neb::host_dependency::entries, "hosts_hosts_dependencies"); - e.register_event(make_type(io::neb, neb::de_host), "host", + e.register_event(io::events::neb, neb::de_host, "host", &neb::host::operations, neb::host::entries, "hosts"); - e.register_event(make_type(io::neb, neb::de_host_group), "host_group", + e.register_event(io::events::neb, neb::de_host_group, "host_group", &neb::host_group::operations, neb::host_group::entries, "hostgroups"); - e.register_event(make_type(io::neb, neb::de_host_group_member), + e.register_event(io::events::neb, neb::de_host_group_member, "host_group_member", &neb::host_group_member::operations, neb::host_group_member::entries, "hosts_hostgroups"); - e.register_event(make_type(io::neb, neb::de_host_parent), "host_parent", + e.register_event(io::events::neb, neb::de_host_parent, "host_parent", &neb::host_parent::operations, neb::host_parent::entries, "hosts_hosts_parents"); - e.register_event(make_type(io::neb, neb::de_host_status), "host_status", + e.register_event(io::events::neb, neb::de_host_status, "host_status", &neb::host_status::operations, neb::host_status::entries, "hosts"); - e.register_event(make_type(io::neb, neb::de_instance), "instance", + e.register_event(io::events::neb, neb::de_instance, "instance", &neb::instance::operations, neb::instance::entries, "instances"); - e.register_event(make_type(io::neb, neb::de_instance_status), + e.register_event(io::events::neb, neb::de_instance_status, "instance_status", &neb::instance_status::operations, neb::instance_status::entries, "instances"); - e.register_event(make_type(io::neb, neb::de_log_entry), "log_entry", + e.register_event(io::events::neb, neb::de_log_entry, "log_entry", &neb::log_entry::operations, neb::log_entry::entries, "logs"); - e.register_event(make_type(io::neb, neb::de_module), "module", + e.register_event(io::events::neb, neb::de_module, "module", &neb::module::operations, neb::module::entries, "modules"); - e.register_event(make_type(io::neb, neb::de_service_check), - "service_check", &neb::service_check::operations, + e.register_event(io::events::neb, neb::de_service_check, "service_check", + &neb::service_check::operations, neb::service_check::entries, "services"); e.register_event( - make_type(io::neb, neb::de_service_dependency), "service_dependency", + io::events::neb, neb::de_service_dependency, "service_dependency", &neb::service_dependency::operations, neb::service_dependency::entries, "services_services_dependencies"); - e.register_event(make_type(io::neb, neb::de_service), "service", + e.register_event(io::events::neb, neb::de_service, "service", &neb::service::operations, neb::service::entries, "services"); - e.register_event(make_type(io::neb, neb::de_service_group), - "service_group", &neb::service_group::operations, + e.register_event(io::events::neb, neb::de_service_group, "service_group", + &neb::service_group::operations, neb::service_group::entries, "servicegroups"); e.register_event( - make_type(io::neb, neb::de_service_group_member), - "service_group_member", &neb::service_group_member::operations, + io::events::neb, neb::de_service_group_member, "service_group_member", + &neb::service_group_member::operations, neb::service_group_member::entries, "services_servicegroups"); - e.register_event(make_type(io::neb, neb::de_service_status), + e.register_event(io::events::neb, neb::de_service_status, "service_status", &neb::service_status::operations, neb::service_status::entries, "services"); - e.register_event(make_type(io::neb, neb::de_instance_configuration), + e.register_event(io::events::neb, neb::de_instance_configuration, "instance_configuration", &neb::instance_configuration::operations, neb::instance_configuration::entries); - e.register_event(make_type(io::neb, neb::de_responsive_instance), + e.register_event(io::events::neb, neb::de_responsive_instance, "responsive_instance", &neb::responsive_instance::operations, neb::responsive_instance::entries); } + + // // Register neb layer. + // io::protocols::instance().reg( + // "node_events", + // neb::node_events_factory(), + // 1, + // 7); } } } diff --git a/centreon-broker/neb/src/callbacks.cc b/centreon-broker/neb/src/callbacks.cc index c7aaa2d7256..c5e7bec0097 100644 --- a/centreon-broker/neb/src/callbacks.cc +++ b/centreon-broker/neb/src/callbacks.cc @@ -1517,7 +1517,8 @@ int neb::callback_process(int callback_type, void* data) { log_v2::neb()->debug("callbacks: registering callbacks"); for (uint32_t i(0); i < sizeof(gl_callbacks) / sizeof(*gl_callbacks); ++i) gl_registered_callbacks.emplace_back(std::make_unique( - gl_callbacks[i].macro, gl_mod_handle, gl_callbacks[i].callback)); + gl_callbacks[i].macro, gl_mod_handle, + gl_callbacks[i].callback)); // Register Engine-specific callbacks. if (gl_mod_flags & NEBMODULE_ENGINE) { @@ -1526,7 +1527,7 @@ int neb::callback_process(int callback_type, void* data) { ++i) gl_registered_callbacks.emplace_back(std::make_unique( gl_engine_callbacks[i].macro, gl_mod_handle, - gl_engine_callbacks[i].callback)); + gl_engine_callbacks[i].callback)); } // Parse configuration file. @@ -1979,7 +1980,8 @@ int neb::callback_service_status(int callback_type, void* data) { try { // In/Out variables. - auto service_status = std::make_shared(); + std::shared_ptr service_status( + new neb::service_status); // Fill output var. engine::service const* s{static_cast( diff --git a/centreon-broker/neb/src/comment.cc b/centreon-broker/neb/src/comment.cc index 33dafdecd4f..47feb0129d9 100644 --- a/centreon-broker/neb/src/comment.cc +++ b/centreon-broker/neb/src/comment.cc @@ -163,5 +163,4 @@ mapping::entry const comment::entries[] = { static io::data* new_comment() { return new comment; } -io::event_info::event_operations const comment::operations = {&new_comment, - nullptr, nullptr}; +io::event_info::event_operations const comment::operations = {&new_comment}; diff --git a/centreon-broker/neb/src/custom_variable.cc b/centreon-broker/neb/src/custom_variable.cc index 13353e1a22e..f851f628567 100644 --- a/centreon-broker/neb/src/custom_variable.cc +++ b/centreon-broker/neb/src/custom_variable.cc @@ -122,4 +122,4 @@ static io::data* new_custom_var() { return new custom_variable; } io::event_info::event_operations const custom_variable::operations = { - &new_custom_var, nullptr, nullptr}; + &new_custom_var}; diff --git a/centreon-broker/neb/src/custom_variable_status.cc b/centreon-broker/neb/src/custom_variable_status.cc index 1394be62544..81479f11ce0 100644 --- a/centreon-broker/neb/src/custom_variable_status.cc +++ b/centreon-broker/neb/src/custom_variable_status.cc @@ -123,4 +123,4 @@ static io::data* new_custom_var_status() { return new custom_variable_status; } io::event_info::event_operations const custom_variable_status::operations = { - &new_custom_var_status, nullptr, nullptr}; + &new_custom_var_status}; diff --git a/centreon-broker/neb/src/downtime.cc b/centreon-broker/neb/src/downtime.cc index 4e642c39b5c..89b7af8c26c 100644 --- a/centreon-broker/neb/src/downtime.cc +++ b/centreon-broker/neb/src/downtime.cc @@ -205,5 +205,4 @@ mapping::entry const downtime::entries[] = { static io::data* new_downtime() { return new downtime; } -io::event_info::event_operations const downtime::operations = { - &new_downtime, nullptr, nullptr}; +io::event_info::event_operations const downtime::operations = {&new_downtime}; diff --git a/centreon-broker/neb/src/event_handler.cc b/centreon-broker/neb/src/event_handler.cc index 5995b4b8b02..00b7a22a861 100644 --- a/centreon-broker/neb/src/event_handler.cc +++ b/centreon-broker/neb/src/event_handler.cc @@ -146,4 +146,4 @@ static io::data* new_event_handler() { return new event_handler; } io::event_info::event_operations const event_handler::operations = { - &new_event_handler, nullptr, nullptr}; + &new_event_handler}; diff --git a/centreon-broker/neb/src/flapping_status.cc b/centreon-broker/neb/src/flapping_status.cc index dfccbf76c53..3b90880ef64 100644 --- a/centreon-broker/neb/src/flapping_status.cc +++ b/centreon-broker/neb/src/flapping_status.cc @@ -124,4 +124,4 @@ static io::data* new_flapping() { return new flapping_status; } io::event_info::event_operations const flapping_status::operations = { - &new_flapping, nullptr, nullptr}; + &new_flapping}; diff --git a/centreon-broker/neb/src/host.cc b/centreon-broker/neb/src/host.cc index 8122111b8e8..5e50467fc3e 100644 --- a/centreon-broker/neb/src/host.cc +++ b/centreon-broker/neb/src/host.cc @@ -303,5 +303,4 @@ mapping::entry const host::entries[] = { static io::data* new_host() { return new host; } -io::event_info::event_operations const host::operations = {&new_host, nullptr, - nullptr}; +io::event_info::event_operations const host::operations = {&new_host}; diff --git a/centreon-broker/neb/src/host_check.cc b/centreon-broker/neb/src/host_check.cc index 63beb6cff44..744aca5126b 100644 --- a/centreon-broker/neb/src/host_check.cc +++ b/centreon-broker/neb/src/host_check.cc @@ -82,4 +82,4 @@ static io::data* new_host_check() { return new host_check; } io::event_info::event_operations const host_check::operations = { - &new_host_check, nullptr, nullptr}; + &new_host_check}; diff --git a/centreon-broker/neb/src/host_dependency.cc b/centreon-broker/neb/src/host_dependency.cc index a4dbb4c4101..fc86bf0a58a 100644 --- a/centreon-broker/neb/src/host_dependency.cc +++ b/centreon-broker/neb/src/host_dependency.cc @@ -95,4 +95,4 @@ static io::data* new_host_dep() { return (new host_dependency); } io::event_info::event_operations const host_dependency::operations = { - &new_host_dep, nullptr, nullptr}; + &new_host_dep}; diff --git a/centreon-broker/neb/src/host_group.cc b/centreon-broker/neb/src/host_group.cc index f460214faae..68dea29b379 100644 --- a/centreon-broker/neb/src/host_group.cc +++ b/centreon-broker/neb/src/host_group.cc @@ -89,4 +89,4 @@ static io::data* new_host_group() { return new host_group; } io::event_info::event_operations const host_group::operations = { - &new_host_group, nullptr, nullptr}; + &new_host_group}; diff --git a/centreon-broker/neb/src/host_group_member.cc b/centreon-broker/neb/src/host_group_member.cc index a661ca322c0..50c77d5dcd9 100644 --- a/centreon-broker/neb/src/host_group_member.cc +++ b/centreon-broker/neb/src/host_group_member.cc @@ -85,4 +85,4 @@ static io::data* new_host_group_member() { return new host_group_member; } io::event_info::event_operations const host_group_member::operations = { - &new_host_group_member, nullptr, nullptr}; + &new_host_group_member}; diff --git a/centreon-broker/neb/src/host_parent.cc b/centreon-broker/neb/src/host_parent.cc index b2955b19e24..38e8e410eef 100644 --- a/centreon-broker/neb/src/host_parent.cc +++ b/centreon-broker/neb/src/host_parent.cc @@ -91,4 +91,4 @@ static io::data* new_host_parent() { return new host_parent; } io::event_info::event_operations const host_parent::operations = { - &new_host_parent, nullptr, nullptr}; + &new_host_parent}; diff --git a/centreon-broker/neb/src/host_status.cc b/centreon-broker/neb/src/host_status.cc index fbeb2e30b10..735b8ef6b0d 100644 --- a/centreon-broker/neb/src/host_status.cc +++ b/centreon-broker/neb/src/host_status.cc @@ -189,4 +189,4 @@ static io::data* new_host_status() { return new host_status; } io::event_info::event_operations const host_status::operations = { - &new_host_status, nullptr, nullptr}; + &new_host_status}; diff --git a/centreon-broker/neb/src/instance.cc b/centreon-broker/neb/src/instance.cc index 5c32fcce305..a572a78c9f7 100644 --- a/centreon-broker/neb/src/instance.cc +++ b/centreon-broker/neb/src/instance.cc @@ -133,5 +133,4 @@ mapping::entry const instance::entries[] = { static io::data* new_instance() { return new instance; } -io::event_info::event_operations const instance::operations = { - &new_instance, nullptr, nullptr}; +io::event_info::event_operations const instance::operations = {&new_instance}; diff --git a/centreon-broker/neb/src/instance_configuration.cc b/centreon-broker/neb/src/instance_configuration.cc index ce9bbf479fc..de2f0753062 100644 --- a/centreon-broker/neb/src/instance_configuration.cc +++ b/centreon-broker/neb/src/instance_configuration.cc @@ -89,7 +89,7 @@ static io::data* new_ic() { return (new instance_configuration); } io::event_info::event_operations const instance_configuration::operations = { - &new_ic, nullptr, nullptr}; + &new_ic}; /************************************** * * diff --git a/centreon-broker/neb/src/instance_status.cc b/centreon-broker/neb/src/instance_status.cc index a33acd765f1..39ae06a8623 100644 --- a/centreon-broker/neb/src/instance_status.cc +++ b/centreon-broker/neb/src/instance_status.cc @@ -158,5 +158,4 @@ mapping::entry const instance_status::entries[] = { static io::data* new_is() { return new instance_status; } -io::event_info::event_operations const instance_status::operations = { - &new_is, nullptr, nullptr}; +io::event_info::event_operations const instance_status::operations = {&new_is}; diff --git a/centreon-broker/neb/src/log_entry.cc b/centreon-broker/neb/src/log_entry.cc index ef1d0795bba..e61d45fa717 100644 --- a/centreon-broker/neb/src/log_entry.cc +++ b/centreon-broker/neb/src/log_entry.cc @@ -155,5 +155,4 @@ mapping::entry const log_entry::entries[] = { static io::data* new_log_entry() { return new log_entry; } -io::event_info::event_operations const log_entry::operations = { - &new_log_entry, nullptr, nullptr}; +io::event_info::event_operations const log_entry::operations = {&new_log_entry}; diff --git a/centreon-broker/neb/src/module.cc b/centreon-broker/neb/src/module.cc index 8c69435015a..62b4a3f5403 100644 --- a/centreon-broker/neb/src/module.cc +++ b/centreon-broker/neb/src/module.cc @@ -112,5 +112,4 @@ mapping::entry const module::entries[] = { static io::data* new_module() { return new module; } -io::event_info::event_operations const module::operations = {&new_module, - nullptr, nullptr}; +io::event_info::event_operations const module::operations = {&new_module}; diff --git a/centreon-broker/neb/src/neb.cc b/centreon-broker/neb/src/neb.cc index f24d7ae1376..c33ae4c6429 100644 --- a/centreon-broker/neb/src/neb.cc +++ b/centreon-broker/neb/src/neb.cc @@ -135,13 +135,13 @@ int nebmodule_init(int flags, char const* args, void* handle) { try { log_v2::instance().apply(s); } catch (const std::exception& e) { - log_v2::core()->error("main: {}", e.what()); + log_v2::core()->error(e.what()); } com::centreon::broker::config::applier::state::instance().apply(s); } catch (std::exception const& e) { - log_v2::core()->error("main: {}", e.what()); + log_v2::core()->error(e.what()); return -1; } catch (...) { log_v2::core()->error("main: configuration file parsing failed"); diff --git a/centreon-broker/neb/src/responsive_instance.cc b/centreon-broker/neb/src/responsive_instance.cc index a25aee99162..4976f47ed47 100644 --- a/centreon-broker/neb/src/responsive_instance.cc +++ b/centreon-broker/neb/src/responsive_instance.cc @@ -90,7 +90,7 @@ static io::data* new_im() { return new responsive_instance; } io::event_info::event_operations const responsive_instance::operations = { - &new_im, nullptr, nullptr}; + &new_im}; /************************************** * * diff --git a/centreon-broker/neb/src/service.cc b/centreon-broker/neb/src/service.cc index 80d63a0c334..caa4dd5a373 100644 --- a/centreon-broker/neb/src/service.cc +++ b/centreon-broker/neb/src/service.cc @@ -318,5 +318,4 @@ mapping::entry const service::entries[] = { static io::data* new_service() { return new service; } -io::event_info::event_operations const service::operations = {&new_service, - nullptr, nullptr}; +io::event_info::event_operations const service::operations = {&new_service}; diff --git a/centreon-broker/neb/src/service_check.cc b/centreon-broker/neb/src/service_check.cc index f2f6586f5de..c36ef77c3f5 100644 --- a/centreon-broker/neb/src/service_check.cc +++ b/centreon-broker/neb/src/service_check.cc @@ -88,4 +88,4 @@ static io::data* new_service_check() { return new service_check; } io::event_info::event_operations const service_check::operations = { - &new_service_check, nullptr, nullptr}; + &new_service_check}; diff --git a/centreon-broker/neb/src/service_dependency.cc b/centreon-broker/neb/src/service_dependency.cc index 1100ad7b57c..fe3ec3d4eb0 100644 --- a/centreon-broker/neb/src/service_dependency.cc +++ b/centreon-broker/neb/src/service_dependency.cc @@ -127,4 +127,4 @@ static io::data* new_service_dependency() { return new service_dependency; } io::event_info::event_operations const service_dependency::operations = { - &new_service_dependency, nullptr, nullptr}; + &new_service_dependency}; diff --git a/centreon-broker/neb/src/service_group.cc b/centreon-broker/neb/src/service_group.cc index 8c156561215..9b5c315a374 100644 --- a/centreon-broker/neb/src/service_group.cc +++ b/centreon-broker/neb/src/service_group.cc @@ -91,4 +91,4 @@ static io::data* new_service_group() { return new service_group; } io::event_info::event_operations const service_group::operations = { - &new_service_group, nullptr, nullptr}; + &new_service_group}; diff --git a/centreon-broker/neb/src/service_group_member.cc b/centreon-broker/neb/src/service_group_member.cc index 6ed79557d58..03ad0a6ac32 100644 --- a/centreon-broker/neb/src/service_group_member.cc +++ b/centreon-broker/neb/src/service_group_member.cc @@ -91,4 +91,4 @@ static io::data* new_service_group_member() { return new service_group_member; } io::event_info::event_operations const service_group_member::operations = { - &new_service_group_member, nullptr, nullptr}; + &new_service_group_member}; diff --git a/centreon-broker/neb/src/service_status.cc b/centreon-broker/neb/src/service_status.cc index efb82a8ed88..8f0ad8e34f4 100644 --- a/centreon-broker/neb/src/service_status.cc +++ b/centreon-broker/neb/src/service_status.cc @@ -185,4 +185,4 @@ static io::data* new_service_status() { return new service_status; } io::event_info::event_operations const service_status::operations = { - &new_service_status, nullptr, nullptr}; + &new_service_status}; diff --git a/centreon-broker/neb/test/custom_variable.cc b/centreon-broker/neb/test/custom_variable.cc index b82ee81dded..11cc82cd92b 100644 --- a/centreon-broker/neb/test/custom_variable.cc +++ b/centreon-broker/neb/test/custom_variable.cc @@ -94,6 +94,7 @@ TEST_F(CVarTest, DefaultConstructor) { ASSERT_EQ(cvar.value, ""); ASSERT_EQ(cvar.var_type, 0); - ASSERT_TRUE(cvar.type() == - (io::events::data_type::value)); + ASSERT_TRUE( + cvar.type() == + (io::events::data_type::value)); } diff --git a/centreon-broker/neb/test/custom_variable_status.cc b/centreon-broker/neb/test/custom_variable_status.cc index c34d013c305..cca27f0bcb4 100644 --- a/centreon-broker/neb/test/custom_variable_status.cc +++ b/centreon-broker/neb/test/custom_variable_status.cc @@ -90,7 +90,7 @@ TEST_F(CVarStatusTest, DefaultConstructor) { ASSERT_EQ(cvar_status.update_time, 0u); ASSERT_EQ(cvar_status.value, ""); - ASSERT_TRUE( - cvar_status.type() == - (io::events::data_type::value)); + ASSERT_TRUE(cvar_status.type() == + (io::events::data_type::value)); } diff --git a/centreon-broker/neb/test/event_handler.cc b/centreon-broker/neb/test/event_handler.cc index cc60e8544cf..8e45cf06808 100644 --- a/centreon-broker/neb/test/event_handler.cc +++ b/centreon-broker/neb/test/event_handler.cc @@ -98,6 +98,7 @@ TEST_F(EventHandlerTest, DefaultConstructor) { ASSERT_EQ(evnt_hndlr.state, 0); ASSERT_EQ(evnt_hndlr.state_type, 0); ASSERT_EQ(evnt_hndlr.timeout, 0); - ASSERT_TRUE(evnt_hndlr.type() == - (io::events::data_type::value)); + ASSERT_TRUE( + evnt_hndlr.type() == + (io::events::data_type::value)); } diff --git a/centreon-broker/neb/test/flapping_status.cc b/centreon-broker/neb/test/flapping_status.cc index 444b1882181..1a30dbce2e0 100644 --- a/centreon-broker/neb/test/flapping_status.cc +++ b/centreon-broker/neb/test/flapping_status.cc @@ -93,6 +93,7 @@ TEST_F(FlappingStatus, DefaultConstructor) { ASSERT_TRUE(fabs(flappy.percent_state_change) < 0.000001); ASSERT_EQ(flappy.reason_type, 0); ASSERT_EQ(flappy.service_id, 0u); - ASSERT_TRUE(flappy.type() == - (io::events::data_type::value)); + ASSERT_TRUE( + flappy.type() == + (io::events::data_type::value)); } diff --git a/centreon-broker/neb/test/host_check.cc b/centreon-broker/neb/test/host_check.cc index d3d0ccb6e18..71fd2518d05 100644 --- a/centreon-broker/neb/test/host_check.cc +++ b/centreon-broker/neb/test/host_check.cc @@ -88,6 +88,7 @@ TEST_F(HostCheckTest, DefaultConstructor) { ASSERT_TRUE(hchk.command_line.empty()); ASSERT_FALSE((hchk.host_id != 0u)); ASSERT_FALSE((hchk.next_check != 0)); - ASSERT_FALSE((hchk.type() != - (io::events::data_type::value))); + ASSERT_FALSE( + (hchk.type() != + (io::events::data_type::value))); } diff --git a/centreon-broker/neb/test/host_dependency.cc b/centreon-broker/neb/test/host_dependency.cc index 82b709b2d3a..a2071cce5ec 100644 --- a/centreon-broker/neb/test/host_dependency.cc +++ b/centreon-broker/neb/test/host_dependency.cc @@ -93,5 +93,5 @@ TEST_F(HostDependencyTest, DefaultConstructor) { ASSERT_TRUE(hdep.notification_failure_options.empty()); ASSERT_FALSE( hdep.type() != - (io::events::data_type::value)); + (io::events::data_type::value)); } diff --git a/centreon-broker/neb/test/host_parent.cc b/centreon-broker/neb/test/host_parent.cc index 6394b4a324c..63bcfd9b7fa 100644 --- a/centreon-broker/neb/test/host_parent.cc +++ b/centreon-broker/neb/test/host_parent.cc @@ -87,6 +87,7 @@ TEST_F(HostParentTest, DefaultConstructor) { ASSERT_TRUE(hprnt.enabled); ASSERT_EQ(hprnt.host_id, 0u); ASSERT_EQ(hprnt.parent_id, 0u); - ASSERT_FALSE(hprnt.type() != - (io::events::data_type::value)); + ASSERT_FALSE( + hprnt.type() != + (io::events::data_type::value)); } diff --git a/centreon-broker/neb/test/instance.cc b/centreon-broker/neb/test/instance.cc index f73ee2a4de3..02ae0007a68 100644 --- a/centreon-broker/neb/test/instance.cc +++ b/centreon-broker/neb/test/instance.cc @@ -85,7 +85,7 @@ TEST_F(Instance, DefaultCtor) { // Object. neb::instance i; - auto val(io::events::data_type::value); + auto val(io::events::data_type::value); // Check. ASSERT_FALSE(i.source_id != 0); diff --git a/centreon-broker/neb/test/instance_status.cc b/centreon-broker/neb/test/instance_status.cc index eb1046e0947..16f771d1f2e 100644 --- a/centreon-broker/neb/test/instance_status.cc +++ b/centreon-broker/neb/test/instance_status.cc @@ -85,7 +85,8 @@ TEST_F(InstanceStatus, DefaultCtor) { // Object. neb::instance_status is; - auto val(io::events::data_type::value); + auto val( + io::events::data_type::value); // Check. ASSERT_FALSE(is.source_id != 0); diff --git a/centreon-broker/neb/test/log_entry.cc b/centreon-broker/neb/test/log_entry.cc index 3444db48a5a..c8d2467ae58 100644 --- a/centreon-broker/neb/test/log_entry.cc +++ b/centreon-broker/neb/test/log_entry.cc @@ -85,7 +85,7 @@ TEST_F(LogEntry, DefaultCtor) { // Object. neb::log_entry le; - auto val(io::events::data_type::value); + auto val(io::events::data_type::value); // Check. ASSERT_FALSE(le.source_id != 0); ASSERT_FALSE(le.destination_id != 0); diff --git a/centreon-broker/neb/test/module.cc b/centreon-broker/neb/test/module.cc index 8d9bc8b797b..6ede77f0253 100644 --- a/centreon-broker/neb/test/module.cc +++ b/centreon-broker/neb/test/module.cc @@ -85,7 +85,7 @@ TEST_F(Module, DefaultCtor) { // Object. neb::module mod; - auto val(io::events::data_type::value); + auto val(io::events::data_type::value); // Check. ASSERT_FALSE(mod.source_id != 0); ASSERT_FALSE(mod.destination_id != 0); diff --git a/centreon-broker/neb/test/randomize.cc b/centreon-broker/neb/test/randomize.cc index fc5930341c6..950854429fc 100644 --- a/centreon-broker/neb/test/randomize.cc +++ b/centreon-broker/neb/test/randomize.cc @@ -102,53 +102,54 @@ void randomize_init() { io::protocols::load(); io::events::load(); io::events& e(io::events::instance()); - e.register_event(make_type(io::neb, neb::de_acknowledgement), - "acknowledgement", &neb::acknowledgement::operations, + e.register_category("neb", io::events::neb); + e.register_event(io::events::neb, neb::de_acknowledgement, "acknowledgement", + &neb::acknowledgement::operations, neb::acknowledgement::entries); - e.register_event(make_type(io::neb, neb::de_custom_variable), - "custom_variable", &neb::custom_variable::operations, + e.register_event(io::events::neb, neb::de_custom_variable, "custom_variable", + &neb::custom_variable::operations, neb::custom_variable::entries); - e.register_event(make_type(io::neb, neb::de_custom_variable_status), + e.register_event(io::events::neb, neb::de_custom_variable_status, "custom_variable_status", &neb::custom_variable_status::operations, neb::custom_variable_status::entries); - e.register_event(make_type(io::neb, neb::de_downtime), "downtime", + e.register_event(io::events::neb, neb::de_downtime, "downtime", &neb::downtime::operations, neb::downtime::entries); - e.register_event(make_type(io::neb, neb::de_event_handler), "event_handler", + e.register_event(io::events::neb, neb::de_event_handler, "event_handler", &neb::event_handler::operations, neb::event_handler::entries); - e.register_event(make_type(io::neb, neb::de_flapping_status), - "flapping_status", &neb::flapping_status::operations, + e.register_event(io::events::neb, neb::de_flapping_status, "flapping_status", + &neb::flapping_status::operations, neb::flapping_status::entries); - e.register_event(make_type(io::neb, neb::de_host_check), "host_check", + e.register_event(io::events::neb, neb::de_host_check, "host_check", &neb::host_check::operations, neb::host_check::entries); - e.register_event(make_type(io::neb, neb::de_host_dependency), - "host_dependency", &neb::host_dependency::operations, + e.register_event(io::events::neb, neb::de_host_dependency, "host_dependency", + &neb::host_dependency::operations, neb::host_dependency::entries); - e.register_event(make_type(io::neb, neb::de_host), "host", + e.register_event(io::events::neb, neb::de_host, "host", &neb::host::operations, neb::host::entries); - e.register_event(make_type(io::neb, neb::de_host_parent), "host_parent", + e.register_event(io::events::neb, neb::de_host_parent, "host_parent", &neb::host_parent::operations, neb::host_parent::entries); - e.register_event(make_type(io::neb, neb::de_host_status), "host_status", + e.register_event(io::events::neb, neb::de_host_status, "host_status", &neb::host_status::operations, neb::host_status::entries); - e.register_event(make_type(io::neb, neb::de_instance), "instance", + e.register_event(io::events::neb, neb::de_instance, "instance", &neb::instance::operations, neb::instance::entries); - e.register_event(make_type(io::neb, neb::de_instance_status), - "instance_status", &neb::instance_status::operations, + e.register_event(io::events::neb, neb::de_instance_status, "instance_status", + &neb::instance_status::operations, neb::instance_status::entries); - e.register_event(make_type(io::neb, neb::de_log_entry), "log_entry", + e.register_event(io::events::neb, neb::de_log_entry, "log_entry", &neb::log_entry::operations, neb::log_entry::entries); - e.register_event(make_type(io::neb, neb::de_module), "module", + e.register_event(io::events::neb, neb::de_module, "module", &neb::module::operations, neb::module::entries); - e.register_event(make_type(io::neb, neb::de_service_check), "service_check", + e.register_event(io::events::neb, neb::de_service_check, "service_check", &neb::service_check::operations, neb::service_check::entries); - e.register_event(make_type(io::neb, neb::de_service_dependency), + e.register_event(io::events::neb, neb::de_service_dependency, "service_dependency", &neb::service_dependency::operations, neb::service_dependency::entries); - e.register_event(make_type(io::neb, neb::de_service), "service", + e.register_event(io::events::neb, neb::de_service, "service", &neb::service::operations, neb::service::entries); - e.register_event(make_type(io::neb, neb::de_service_status), "service_status", + e.register_event(io::events::neb, neb::de_service_status, "service_status", &neb::service_status::operations, neb::service_status::entries); } diff --git a/centreon-broker/neb/test/service_check.cc b/centreon-broker/neb/test/service_check.cc index 406bc70f852..54db5f0d08d 100644 --- a/centreon-broker/neb/test/service_check.cc +++ b/centreon-broker/neb/test/service_check.cc @@ -93,6 +93,7 @@ TEST_F(ServiceCheck, DefaultCtor) { ASSERT_FALSE(schk.host_id != 0); ASSERT_FALSE(schk.next_check != 0); ASSERT_FALSE(schk.service_id != 0); - auto val(io::events::data_type::value); + auto val( + io::events::data_type::value); ASSERT_FALSE(schk.type() != val); } diff --git a/centreon-broker/neb/test/service_dependency.cc b/centreon-broker/neb/test/service_dependency.cc index 3afb451de33..86da118b155 100644 --- a/centreon-broker/neb/test/service_dependency.cc +++ b/centreon-broker/neb/test/service_dependency.cc @@ -96,6 +96,7 @@ TEST_F(ServiceDependency, DefaultCtor) { ASSERT_FALSE(sdep.inherits_parent != false); ASSERT_FALSE(!sdep.notification_failure_options.empty()); ASSERT_FALSE(sdep.service_id != 0); - auto val(io::events::data_type::value); + auto val(io::events::data_type::value); ASSERT_FALSE(sdep.type() != val); } diff --git a/centreon-broker/notification/CMakeLists.txt b/centreon-broker/notification/CMakeLists.txt new file mode 100644 index 00000000000..2eec285e713 --- /dev/null +++ b/centreon-broker/notification/CMakeLists.txt @@ -0,0 +1,161 @@ +## +## 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 +## + +# Global options. +set(INC_DIR "${PROJECT_SOURCE_DIR}/notification/inc/com/centreon/broker/notification") +set(SRC_DIR "${PROJECT_SOURCE_DIR}/notification/src") +include_directories("${PROJECT_SOURCE_DIR}/notification/inc") +include_directories("${PROJECT_SOURCE_DIR}/dumper/inc") +include_directories("${PROJECT_SOURCE_DIR}/neb/inc") +include_directories("${PROJECT_SOURCE_DIR}/file/inc") +include_directories("${PROJECT_SOURCE_DIR}/bbdo/inc") +include_directories("${PROJECT_SOURCE_DIR}/compression/inc") + +# Some files must be processed by Qt's moc. +unset(QT_WRAPPED_SOURCES) +qt4_wrap_cpp(QT_WRAPPED_SOURCES + "${INC_DIR}/process_manager.hh" + "${INC_DIR}/process.hh") + +# Notification module. +set(NOTIFICATION "40-notification") +set(NOTIFICATION "${NOTIFICATION}" PARENT_SCOPE) +add_library("${NOTIFICATION}" SHARED + ${QT_WRAPPED_SOURCES} + # Sources. + "${SRC_DIR}/action.cc" + "${SRC_DIR}/factory.cc" + "${SRC_DIR}/macro_context.cc" + "${SRC_DIR}/macro_generator.cc" + "${SRC_DIR}/macro_getters.cc" + "${SRC_DIR}/main.cc" + "${SRC_DIR}/node_cache.cc" + "${SRC_DIR}/notification_scheduler.cc" + "${SRC_DIR}/process.cc" + "${SRC_DIR}/process_manager.cc" + "${SRC_DIR}/run_queue.cc" + "${SRC_DIR}/state.cc" + "${SRC_DIR}/stream.cc" + "${SRC_DIR}/connector.cc" + "${SRC_DIR}/objects/command.cc" + "${SRC_DIR}/objects/contact.cc" + "${SRC_DIR}/objects/dependency.cc" + "${SRC_DIR}/objects/node.cc" + "${SRC_DIR}/objects/node_id.cc" + "${SRC_DIR}/objects/defines.cc" + "${SRC_DIR}/objects/notification_method.cc" + "${SRC_DIR}/objects/notification_rule.cc" + "${SRC_DIR}/loaders/contact_loader.cc" + "${SRC_DIR}/loaders/dependency_loader.cc" + "${SRC_DIR}/loaders/node_loader.cc" + "${SRC_DIR}/loaders/timeperiod_loader.cc" + "${SRC_DIR}/loaders/command_loader.cc" + "${SRC_DIR}/loaders/notification_method_loader.cc" + "${SRC_DIR}/loaders/notification_rule_loader.cc" + "${SRC_DIR}/loaders/macro_loader.cc" + "${SRC_DIR}/builders/node_set_builder.cc" + "${SRC_DIR}/builders/composed_contact_builder.cc" + "${SRC_DIR}/builders/contact_by_id_builder.cc" + "${SRC_DIR}/builders/composed_dependency_builder.cc" + "${SRC_DIR}/builders/composed_node_builder.cc" + "${SRC_DIR}/builders/composed_timeperiod_builder.cc" + "${SRC_DIR}/builders/composed_command_builder.cc" + "${SRC_DIR}/builders/composed_notification_method_builder.cc" + "${SRC_DIR}/builders/composed_notification_rule_builder.cc" + "${SRC_DIR}/builders/dependency_by_node_id_builder.cc" + "${SRC_DIR}/builders/timeperiod_by_id_builder.cc" + "${SRC_DIR}/builders/timeperiod_linker.cc" + "${SRC_DIR}/builders/command_by_id_builder.cc" + "${SRC_DIR}/builders/node_by_node_id_builder.cc" + "${SRC_DIR}/builders/global_macro_builder.cc" + "${SRC_DIR}/builders/notification_method_by_id_builder.cc" + "${SRC_DIR}/builders/notification_rule_by_node_builder.cc" + "${SRC_DIR}/builders/notification_rule_by_id_builder.cc" + "${SRC_DIR}/utilities/data_loggers.cc" + "${SRC_DIR}/utilities/qhash_func.cc" + "${SRC_DIR}/utilities/get_datetime_string.cc" + # Headers. + "${INC_DIR}/action.hh" + "${INC_DIR}/factory.hh" + "${INC_DIR}/macro_context.hh" + "${INC_DIR}/macro_generator.hh" + "${INC_DIR}/macro_getters.hh" + "${INC_DIR}/node_cache.hh" + "${INC_DIR}/notification_scheduler.hh" + "${INC_DIR}/process.hh" + "${INC_DIR}/process_manager.hh" + "${INC_DIR}/run_queue.hh" + "${INC_DIR}/state.hh" + "${INC_DIR}/stream.hh" + "${INC_DIR}/connector.hh" + "${INC_DIR}/objects/command.hh" + "${INC_DIR}/objects/contact.hh" + "${INC_DIR}/objects/dependency.hh" + "${INC_DIR}/objects/node.hh" + "${INC_DIR}/objects/node_id.hh" + "${INC_DIR}/objects/defines.hh" + "${INC_DIR}/objects/notification_method.hh" + "${INC_DIR}/objects/notification_rule.hh" + "${INC_DIR}/loaders/command_loader.hh" + "${INC_DIR}/loaders/contact_loader.hh" + "${INC_DIR}/loaders/dependency_loader.hh" + "${INC_DIR}/loaders/node_loader.hh" + "${INC_DIR}/loaders/timeperiod_loader.hh" + "${INC_DIR}/loaders/notification_method_loader.hh" + "${INC_DIR}/loaders/notification_rule_loader.hh" + "${INC_DIR}/loaders/macro_loader.hh" + "${INC_DIR}/builders/timeperiod_builder.hh" + "${INC_DIR}/builders/command_builder.hh" + "${INC_DIR}/builders/contact_builder.hh" + "${INC_DIR}/builders/dependency_builder.hh" + "${INC_DIR}/builders/node_builder.hh" + "${INC_DIR}/builders/node_set_builder.hh" + "${INC_DIR}/builders/composed_contact_builder.hh" + "${INC_DIR}/builders/contact_by_id_builder.hh" + "${INC_DIR}/builders/composed_builder.hh" + "${INC_DIR}/builders/composed_dependency_builder.hh" + "${INC_DIR}/builders/composed_node_builder.hh" + "${INC_DIR}/builders/composed_timeperiod_builder.hh" + "${INC_DIR}/builders/composed_command_builder.hh" + "${INC_DIR}/builders/composed_notification_method_builder.hh" + "${INC_DIR}/builders/composed_notification_rule_builder.hh" + "${INC_DIR}/builders/dependency_by_node_id_builder.hh" + "${INC_DIR}/builders/timeperiod_by_id_builder.hh" + "${INC_DIR}/builders/timeperiod_linker.hh" + "${INC_DIR}/builders/command_by_id_builder.hh" + "${INC_DIR}/builders/macro_builder.hh" + "${INC_DIR}/builders/global_macro_builder.hh" + "${INC_DIR}/builders/node_by_node_id_builder.hh" + "${INC_DIR}/builders/notification_method_builder.hh" + "${INC_DIR}/builders/notification_method_by_id_builder.hh" + "${INC_DIR}/builders/notification_rule_builder.hh" + "${INC_DIR}/builders/notification_rule_by_node_builder.hh" + "${INC_DIR}/builders/notification_rule_by_id_builder.hh" + "${INC_DIR}/utilities/ptr_typedef.hh" + "${INC_DIR}/utilities/data_loggers.hh" + "${INC_DIR}/utilities/qhash_func.hh" + "${INC_DIR}/utilities/get_datetime_string.hh" +) +set_target_properties("${NOTIFICATION}" PROPERTIES + PREFIX "") +target_link_libraries("${NOTIFICATION}" ${QT_LIBRARIES}) + +# Install rule. +install(TARGETS "${NOTIFICATION}" + LIBRARY DESTINATION "${PREFIX_MODULES}" +) diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/action.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/action.hh new file mode 100644 index 00000000000..e61f23e9390 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/action.hh @@ -0,0 +1,107 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_ACTION_HH +#define CCB_NOTIFICATION_ACTION_HH + +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/node_cache.hh" +#include "com/centreon/broker/notification/objects/contact.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" + +CCB_BEGIN() + +namespace notification { +// Forward declaration. +class state; + +/** + * @class action action.hh "com/centreon/broker/notification/action.hh" + * @brief Action object. + * + * Represent an action requested to the notification engine. + */ +class action { + public: + /** + * The type of the action. + */ + enum action_type { + unknown = 0, + notification_processing, // This notification is yet to be processed. + notification_attempt, // Normal notification. + notification_up, // Up notification. + notification_ack, // Ack notification. + notification_downtime // Downtime notification. + }; + action(); + action(action const& obj); + action& operator=(action const& obj); + bool operator==(action const& obj) const; + bool operator<(action const& obj) const; + + action_type get_type() const throw(); + void set_type(action_type type) throw(); + + action_type get_forwarded_type() const throw(); + void set_forwarded_type(action_type type) throw(); + + objects::node_id get_node_id() const throw(); + void set_node_id(objects::node_id id) throw(); + + uint32_t get_notification_rule_id() const throw(); + void set_notification_rule_id(uint32_t id) throw(); + + uint32_t get_notification_number() const throw(); + void set_notification_number(uint32_t num) throw(); + + time_t get_at() const throw(); + void set_at(time_t at) throw(); + + time_t get_first_notification_time() const throw(); + void set_first_notification_time(time_t t) throw(); + + void process_action( + state& st, + node_cache& cache, + std::vector >& spawned_actions) const; + + private: + action_type _act; + action_type _forwarded_action; + objects::node_id _id; + uint32_t _notification_rule_id; + uint32_t _notification_number; + time_t _at; + time_t _first_time_of_notification; + + void _spawn_notification_attempts( + ::com::centreon::broker::notification::state& st, + std::vector >& spawned_actions) const; + void _process_notification( + ::com::centreon::broker::notification::state& st, + node_cache& cache, + std::vector >& spawned_actions) const; +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_ACTION_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/command_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/command_builder.hh new file mode 100644 index 00000000000..fe93f7a0189 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/command_builder.hh @@ -0,0 +1,58 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_COMMAND_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_COMMAND_BUILDER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/objects/command.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class command_builder command_builder.hh + * "com/centreon/broker/notification/builders/command_builder.hh" + * @brief Command builder interface. + * + * This interface define what methods command builders need to implement. + */ +class command_builder { + public: + /** + * Virtual destructor. + */ + virtual ~command_builder() {} + + /** + * Add a command to the builder. + * + * @param[in] id The id of the command. + * @param[in] com The command. + */ + virtual void add_command(uint32_t id, objects::command::ptr com) { + (void)id; + (void)com; + } +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_COMMAND_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/command_by_id_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/command_by_id_builder.hh new file mode 100644 index 00000000000..9365bff379c --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/command_by_id_builder.hh @@ -0,0 +1,53 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_COMMAND_BY_ID_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_COMMAND_BY_ID_BUILDER_HH + +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/command_builder.hh" +#include "com/centreon/broker/notification/objects/command.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class command_by_id_builder command_by_id_builder.hh + * "com/centreon/broker/notification/builders/command_by_id_builder.hh" + * @brief Command builder by id. + * + * This class build a map of commands by their id. + */ +class command_by_id_builder : public command_builder { + public: + command_by_id_builder(QHash& table); + + virtual void add_command(uint32_t id, objects::command::ptr com); + + private: + QHash& _table; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_COMMAND_BY_ID_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_builder.hh new file mode 100644 index 00000000000..a4ede94d182 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_builder.hh @@ -0,0 +1,64 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_COMPOSED_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_COMPOSED_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class composed_builder composed_builder.hh + * "com/centreon/broker/notification/builders/composed_builder.hh" + * @tparam T The builder type for the underlying builders. + * @brief Base for composed builders. + * + * This class provides facilities for composed builders. + */ +template +class composed_builder : public T { + public: + typedef std::vector vector_type; + typedef typename vector_type::iterator iterator; + typedef typename vector_type::const_iterator const_iterator; + + composed_builder() {} + virtual ~composed_builder() {} + + void push_back(T& builder) { _builders.push_back(&builder); } + + iterator begin() { return (_builders.begin()); } + + const_iterator begin() const { return (_builders.begin()); } + + iterator end() { return (_builders.end()); } + + const_iterator end() const { return (_builders.end()); } + + private: + std::vector _builders; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_COMPOSED_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_command_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_command_builder.hh new file mode 100644 index 00000000000..8ead0221dac --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_command_builder.hh @@ -0,0 +1,49 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_COMPOSED_COMMAND_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_COMPOSED_COMMAND_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/command_builder.hh" +#include "com/centreon/broker/notification/builders/composed_builder.hh" +#include "com/centreon/broker/notification/objects/command.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class composed_command_builder composed_command_builder.hh + * "com/centreon/broker/notification/builders/composed_command_builder.hh" + * @brief Composed command builder. + * + * This class forward its method call to several other builders. + */ +class composed_command_builder : public composed_builder { + public: + composed_command_builder(); + + virtual void add_command(uint32_t id, objects::command::ptr com); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_COMPOSED_COMMAND_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_contact_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_contact_builder.hh new file mode 100644 index 00000000000..81cb91bda58 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_contact_builder.hh @@ -0,0 +1,52 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_COMPOSED_CONTACT_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_COMPOSED_CONTACT_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/composed_builder.hh" +#include "com/centreon/broker/notification/builders/contact_builder.hh" +#include "com/centreon/broker/notification/objects/contact.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class composed_contact_builder composed_contact_builder.hh + * "com/centreon/broker/notification/builders/composed_contact_builder.hh" + * @brief Composed contact builder. + * + * This class forward its method call to several other builders. + */ +class composed_contact_builder : public composed_builder { + public: + composed_contact_builder(); + + virtual void add_contact(uint32_t id, objects::contact::ptr con); + virtual void add_contact_info(uint32_t contact_id, + std::string const& key, + std::string const& value); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_COMPOSED_CONTACT_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_dependency_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_dependency_builder.hh new file mode 100644 index 00000000000..d85d000f651 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_dependency_builder.hh @@ -0,0 +1,58 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_COMPOSED_DEPENDENCY_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_COMPOSED_DEPENDENCY_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/composed_builder.hh" +#include "com/centreon/broker/notification/builders/dependency_builder.hh" +#include "com/centreon/broker/notification/objects/dependency.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class composed_dependency_builder composed_dependency_builder.hh + * "com/centreon/broker/notification/builders/composed_dependency_builder.hh" + * @brief Composed dependency builder. + * + * This class forward its method call to several other builders. + */ +class composed_dependency_builder + : public composed_builder { + public: + composed_dependency_builder(); + + virtual void add_dependency(uint32_t id, objects::dependency::ptr d); + virtual void dependency_node_id_parent_relation(uint32_t dep_id, + objects::node_id id); + virtual void dependency_node_id_child_relation(uint32_t dep_id, + objects::node_id id); + virtual void set_notification_failure_options(uint32_t dep_id, + std::string const& line); + virtual void set_execution_failure_options(uint32_t dep_id, + std::string const& line); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_COMPOSED_DEPENDENCY_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_node_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_node_builder.hh new file mode 100644 index 00000000000..7737f02bbdb --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_node_builder.hh @@ -0,0 +1,49 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_COMPOSED_NODE_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_COMPOSED_NODE_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/composed_builder.hh" +#include "com/centreon/broker/notification/builders/node_builder.hh" +#include "com/centreon/broker/notification/objects/node.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class composed_node_builder composed_node_builder.hh + * "com/centreon/broker/notification/builders/composed_node_builder.hh" + * @brief Composed node builder. + * + * This class forward its method call to several other builders. + */ +class composed_node_builder : public composed_builder { + public: + composed_node_builder(); + + virtual void add_node(objects::node::ptr node); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_COMPOSED_NODE_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_notification_method_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_notification_method_builder.hh new file mode 100644 index 00000000000..187cd97606d --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_notification_method_builder.hh @@ -0,0 +1,53 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_COMPOSED_NOTIFICATION_METHOD_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_COMPOSED_NOTIFICATION_METHOD_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/composed_builder.hh" +#include "com/centreon/broker/notification/builders/notification_method_builder.hh" +#include "com/centreon/broker/notification/objects/notification_method.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class composed_notification_method_builder + * composed_notification_method_builder.hh + * "com/centreon/broker/notification/builders/composed_notification_method_builder.hh" + * @brief Composed notification method builder. + * + * This class forward its method call to several other builders. + */ +class composed_notification_method_builder + : public composed_builder { + public: + composed_notification_method_builder(); + + virtual void add_notification_method( + uint32_t method_id, + objects::notification_method::ptr method); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_COMPOSED_NOTIFICATION_METHOD_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_notification_rule_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_notification_rule_builder.hh new file mode 100644 index 00000000000..3344a70238e --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_notification_rule_builder.hh @@ -0,0 +1,50 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_COMPOSED_NOTIFICATION_RULE_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_COMPOSED_NOTIFICATION_RULE_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/composed_builder.hh" +#include "com/centreon/broker/notification/builders/notification_rule_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class composed_notification_rule_builder + * composed_notification_rule_builder.hh + * "com/centreon/broker/notification/builders/composed_notification_rule_builder.hh" + * @brief Composed notification rule builder. + * + * This class forward its method call to several other builders. + */ +class composed_notification_rule_builder + : public composed_builder { + public: + composed_notification_rule_builder(); + + virtual void add_rule(uint32_t rule_id, objects::notification_rule::ptr rule); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_COMPOSED_NOTIFICATION_RULE_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_timeperiod_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_timeperiod_builder.hh new file mode 100644 index 00000000000..4efbfe1addc --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/composed_timeperiod_builder.hh @@ -0,0 +1,58 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_COMPOSED_TIMEPERIOD_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_COMPOSED_TIMEPERIOD_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/composed_builder.hh" +#include "com/centreon/broker/notification/builders/timeperiod_builder.hh" +#include "com/centreon/broker/time/timeperiod.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class composed_timeperiod_builder composed_timeperiod_builder.hh + * "com/centreon/broker/notification/builders/composed_timeperiod_builder.hh" + * @brief Composed timeperiod builder. + * + * This class forward its method call to several other builders. + */ +class composed_timeperiod_builder + : public composed_builder { + public: + composed_timeperiod_builder(); + virtual ~composed_timeperiod_builder() {} + + virtual void add_timeperiod(uint32_t id, time::timeperiod::ptr tperiod); + virtual void add_timeperiod_exception(uint32_t timeperiod_id, + std::string const& days, + std::string const& timerange); + virtual void add_timeperiod_exclude_relation(uint32_t timeperiod_id, + uint32_t exclude_id); + virtual void add_timeperiod_include_relation(uint32_t timeperiod_id, + uint32_t include_id); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_COMPOSED_TIMEPERIOD_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/contact_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/contact_builder.hh new file mode 100644 index 00000000000..3399fab048b --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/contact_builder.hh @@ -0,0 +1,73 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_CONTACT_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_CONTACT_BUILDER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/objects/contact.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class contact_builder contact_builder.hh + * "com/centreon/broker/notification/builders/contact_builder.hh" + * @brief Contact builder interface. + * + * This interface define what methods contact builders need to implement. + */ +class contact_builder { + public: + /** + * Virtual destructor. + */ + virtual ~contact_builder() {} + + /** + * Add a contact to the builder. + * + * @param[in] id The id of the contact. + * @param[in] con The contact. + */ + virtual void add_contact(uint32_t id, objects::contact::ptr con) { + (void)id; + (void)con; + } + + /** + * Add a contact info to the builder. + * + * @param[in] contact_id The id of the contact. + * @param[in] key The key of the contact info. + * @param[in] value The value of the contact info. + */ + virtual void add_contact_info(uint32_t contact_id, + std::string const& key, + std::string const& value) { + (void)contact_id; + (void)key; + (void)value; + } +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_CONTACT_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/contact_by_id_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/contact_by_id_builder.hh new file mode 100644 index 00000000000..68feb8d0b52 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/contact_by_id_builder.hh @@ -0,0 +1,56 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_CONTACT_BY_ID_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_CONTACT_BY_ID_BUILDER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/contact_builder.hh" +#include "com/centreon/broker/notification/objects/contact.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class contact_by_id_builder contact_by_id_builder.hh + * "com/centreon/broker/notification/builders/contact_by_id_builder.hh" + * @brief Contact by id builder. + */ +class contact_by_id_builder : public contact_builder { + public: + contact_by_id_builder( + QHash& table, + QHash >& contact_infos); + + void add_contact(uint32_t id, objects::contact::ptr con); + + void add_contact_info(uint32_t contact_id, + std::string const& key, + std::string const& value); + + private: + QHash& _table; + QHash >& _contact_infos; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_CONTACT_BY_ID_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/dependency_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/dependency_builder.hh new file mode 100644 index 00000000000..1cf4682d5ce --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/dependency_builder.hh @@ -0,0 +1,80 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_DEPENDENCY_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_DEPENDENCY_BUILDER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/objects/dependency.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class dependency_builder dependency_builder.hh + * "com/centreon/broker/notification/builders/dependency_builder.hh" + * @brief Dependency builder interface. + * + * This interface define what methods dependency builders need to implement. + */ +class dependency_builder { + public: + /** + * Virtual destructor. + */ + virtual ~dependency_builder() {} + + /** + * Add a dependency to the builder. + * + * @param[in] id The id of the dependency. + * @param[in] d The dependency. + */ + virtual void add_dependency(uint32_t id, objects::dependency::ptr d) { + (void)id; + (void)d; + } + virtual void dependency_node_id_parent_relation(uint32_t dep_id, + objects::node_id id) { + (void)dep_id; + (void)id; + } + virtual void dependency_node_id_child_relation(uint32_t dep_id, + objects::node_id id) { + (void)dep_id; + (void)id; + } + + virtual void set_notification_failure_options(uint32_t dep_id, + std::string const& line) { + (void)dep_id; + (void)line; + } + virtual void set_execution_failure_options(uint32_t dep_id, + std::string const& line) { + (void)dep_id; + (void)line; + } +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_DEPENDENCY_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/dependency_by_node_id_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/dependency_by_node_id_builder.hh new file mode 100644 index 00000000000..68a5aeb786d --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/dependency_by_node_id_builder.hh @@ -0,0 +1,62 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_DEPENDENCY_BY_NODE_ID_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_DEPENDENCY_BY_NODE_ID_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/dependency_builder.hh" +#include "com/centreon/broker/notification/objects/dependency.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class dependency_by_node_id_builder dependency_by_node_id_builder.hh + * "com/centreon/broker/notification/builders/dependency_by_node_id_builder.hh" + * @brief Dependency builder by node id. + * + * This class build a map of dependencies by their node id. + */ +class dependency_by_node_id_builder : public dependency_builder { + public: + dependency_by_node_id_builder( + QMultiHash& by_child_id, + QMultiHash& by_parent_id); + + virtual void add_dependency(uint32_t id, objects::dependency::ptr d); + virtual void dependency_node_id_parent_relation(uint32_t dep_id, + objects::node_id id); + virtual void dependency_node_id_child_relation(uint32_t dep_id, + objects::node_id id); + + private: + dependency_by_node_id_builder(); + + QHash _cache; + QMultiHash& _table_child_id; + QMultiHash& _table_parent_id; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_DEPENDENCY_BY_NODE_ID_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/global_macro_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/global_macro_builder.hh new file mode 100644 index 00000000000..0fe9e52a73e --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/global_macro_builder.hh @@ -0,0 +1,55 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_GLOBAL_MACRO_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_GLOBAL_MACRO_BUILDER_HH + +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/macro_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class global_macro_builder global_macro_builder.hh + * "com/centreon/broker/notification/builders/global_macro_builder.hh" + * @brief Global macro builder. + */ +class global_macro_builder : public macro_builder { + public: + global_macro_builder(QHash& global_macros, + int& date_format); + + virtual void add_global_macro(std::string const& macro_name, + std::string const& macro_value); + virtual void add_date_format(int format); + virtual void add_resource_macro(std::string const& macro_name, + std::string const& macro_value); + + private: + QHash& _global_macros; + int& _date_format; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_GLOBAL_MACRO_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/macro_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/macro_builder.hh new file mode 100644 index 00000000000..54182b20dd7 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/macro_builder.hh @@ -0,0 +1,78 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_MACRO_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_MACRO_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class macro_builder macro_builder.hh + * "com/centreon/broker/notification/builders/macro_builder.hh" + * @brief Macro builder interface. + * + * This interface define what methods macro builders need to implement. + */ +class macro_builder { + public: + /** + * Virtual destructor. + */ + virtual ~macro_builder() {} + + /** + * Add a global macro to the builder. + * + * @param[in] macro_name The macro name. + * @param[in] macro_value The macro value. + */ + virtual void add_global_macro(std::string const& macro_name, + std::string const& macro_value) { + (void)macro_name; + (void)macro_value; + } + + /** + * Add the date format of the macros to the builder. + * + * @param[in] format The date format. + */ + virtual void add_date_format(int format) { (void)format; } + + /** + * Add a resource macro to the builder. + * + * @param[in] macro_name The macro name. + * @param[in] macro_value The macro value. + */ + virtual void add_resource_macro(std::string const& macro_name, + std::string const& macro_value) { + (void)macro_name; + (void)macro_value; + } +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_NODE_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_builder.hh new file mode 100644 index 00000000000..916a0f1b807 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_builder.hh @@ -0,0 +1,54 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_NODE_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_NODE_BUILDER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/objects/node.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class node_builder node_builder.hh + * "com/centreon/broker/notification/builders/node_builder.hh" + * @brief Node builder interface. + * + * This interface define what methods node builders need to implement. + */ +class node_builder { + public: + /** + * Virtual destructor. + */ + virtual ~node_builder() {} + + /** + * Add a node to the builder. + * + * @param[in] node The node. + */ + virtual void add_node(objects::node::ptr node) { (void)node; } +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_NODE_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_by_node_id_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_by_node_id_builder.hh new file mode 100644 index 00000000000..283e262a0bf --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_by_node_id_builder.hh @@ -0,0 +1,54 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_NODE_BY_NODE_ID_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_NODE_BY_NODE_ID_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/node_builder.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class node_set_builder node_set_builder.hh + * "com/centreon/broker/notification/builders/node_set_builder.hh" + * @brief Build the set of node id. + * + * This class build the set of all the node id of the db. + */ +class node_by_node_id_builder : public node_builder { + public: + node_by_node_id_builder(QHash& map); + virtual ~node_by_node_id_builder() {} + + virtual void add_node(objects::node::ptr node); + + private: + node_by_node_id_builder(); + + QHash& _map; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_NODE_BY_NODE_ID_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_set_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_set_builder.hh new file mode 100644 index 00000000000..0c7f21073a5 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/node_set_builder.hh @@ -0,0 +1,54 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_NODE_SET_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_NODE_SET_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/node_builder.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class node_set_builder node_set_builder.hh + * "com/centreon/broker/notification/builders/node_set_builder.hh" + * @brief Build the set of node id. + * + * This class build the set of all the node id of the db. + */ +class node_set_builder : public node_builder { + public: + node_set_builder(QSet& set); + virtual ~node_set_builder() {} + + virtual void add_node(objects::node::ptr node); + + private: + node_set_builder(); + + QSet& _set; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_NODE_SET_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_method_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_method_builder.hh new file mode 100644 index 00000000000..228c2998f52 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_method_builder.hh @@ -0,0 +1,54 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_NOTIFICATION_METHOD_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_NOTIFICATION_METHOD_BUILDER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/objects/notification_method.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class notification_method_builder notification_method_builder.hh + * "com/centreon/broker/notification/builders/notification_method_builder.hh" + */ +class notification_method_builder { + public: + virtual ~notification_method_builder() {} + + /** + * Add a notification method to the builder. + * + * @param[in] method_id The id of the notification method. + * @param[in] method The method. + */ + virtual void add_notification_method( + uint32_t method_id, + objects::notification_method::ptr method) { + (void)method_id; + (void)method; + } +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_NOTIFICATION_METHOD_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_method_by_id_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_method_by_id_builder.hh new file mode 100644 index 00000000000..ee45278bf59 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_method_by_id_builder.hh @@ -0,0 +1,53 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_NOTIFICATION_METHOD_BY_ID_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_NOTIFICATION_METHOD_BY_ID_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/notification_method_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class notification_method_by_id_builder + * notification_method_by_id_builder.hh + * "com/centreon/broker/notification/builders/notification_method_by_id_builder.hh" + */ +class notification_method_by_id_builder : public notification_method_builder { + public: + notification_method_by_id_builder( + QHash& map); + + virtual void add_notification_method( + uint32_t method_id, + objects::notification_method::ptr method); + + private: + notification_method_by_id_builder(); + + QHash& _map; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_NOTIFICATION_METHOD_BY_ID_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_builder.hh new file mode 100644 index 00000000000..64b5ce58cb0 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_builder.hh @@ -0,0 +1,54 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_NOTIFICATION_RULE_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_NOTIFICATION_RULE_BUILDER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" +#include "com/centreon/broker/notification/objects/notification_rule.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class notification_rule_builder notification_rule_builder.hh + * "com/centreon/broker/notification/builders/notification_rule_builder.hh" + */ +class notification_rule_builder { + public: + virtual ~notification_rule_builder() {} + + /** + * Add a notification rule to the builder. + * + * @param[in] rule_id The id of the notification rule. + * @param[in] rule The rule. + */ + virtual void add_rule(uint32_t rule_id, + objects::notification_rule::ptr rule) { + (void)rule_id; + (void)rule; + } +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_NOTIFICATION_RULE_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_by_id_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_by_id_builder.hh new file mode 100644 index 00000000000..9a1c5bcbb87 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_by_id_builder.hh @@ -0,0 +1,50 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_NOTIFICATION_RULE_BY_ID_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_NOTIFICATION_RULE_BY_ID_BUILDER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/notification_rule_builder.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" +#include "com/centreon/broker/notification/objects/notification_rule.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class notification_rule_by_id_builder notification_rule_by_id_builder.hh + * "com/centreon/broker/notification/builders/notification_rule_by_id_builder.hh" + * @brief Notification rule by id builder. + */ +class notification_rule_by_id_builder : public notification_rule_builder { + public: + notification_rule_by_id_builder( + QHash& table); + + void add_rule(uint32_t id, objects::notification_rule::ptr con); + + private: + QHash& _table; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_NOTIFICATION_RULE_BY_ID_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_by_node_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_by_node_builder.hh new file mode 100644 index 00000000000..3c03ed7fb7f --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/notification_rule_by_node_builder.hh @@ -0,0 +1,51 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_NOTIFICATION_RULE_BY_NODE_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_NOTIFICATION_RULE_BY_NODE_BUILDER_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/notification_rule_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class notification_method_by_node_builder + * notification_method_by_node_builder.hh + * "com/centreon/broker/notification/builders/notification_method_by_node_builder.hh" + */ +class notification_rule_by_node_builder : public notification_rule_builder { + public: + notification_rule_by_node_builder( + QMultiHash& map); + + virtual void add_rule(uint32_t rule_id, objects::notification_rule::ptr rule); + + private: + notification_rule_by_node_builder(); + + QMultiHash& _map; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_NOTIFICATION_RULE_BY_NODE_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_builder.hh new file mode 100644 index 00000000000..b1a1eb4d1d9 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_builder.hh @@ -0,0 +1,96 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_TIMEPERIOD_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_TIMEPERIOD_BUILDER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/time/timeperiod.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class timeperiod_builder timeperiod_builder.hh + * "com/centreon/broker/notification/builders/timeperiod_builder.hh" + * @brief Timeperiod builder interface. + * + * This interface define what methods timeperiod builders need to implement. + */ +class timeperiod_builder { + public: + /** + * Virtual destructor. + */ + virtual ~timeperiod_builder() {} + + /** + * Add a timeperiod to the builder. + * + * @param[in] id The id of the timeperiod. + * @param[in] tperiod The timeperiod. + */ + virtual void add_timeperiod(uint32_t id, time::timeperiod::ptr tperiod) { + (void)id; + (void)tperiod; + } + /** + * Add a timeperiod exception to the builder. + * + * @param[in] timeperiod_id The id of the timeperiod. + * @param[in] days The days in the exception. + * @param[in] timerange The timerange of the exception. + */ + virtual void add_timeperiod_exception(uint32_t timeperiod_id, + std::string const& days, + std::string const& timerange) { + (void)timeperiod_id; + (void)days; + (void)timerange; + } + + /** + * Add a timeperiod exclude relation to the builder. + * + * @param[in] timeperiod_id The id of the timeperiod. + * @param[in] exclude_id The id of the timeperiod excluded. + */ + virtual void add_timeperiod_exclude_relation(uint32_t timeperiod_id, + uint32_t exclude_id) { + (void)timeperiod_id; + (void)exclude_id; + } + + /** + * Add a timeperiod include relation to the builder. + * + * @param[in] timeperiod_id The id of the timeperiod. + * @param[in] include_id The id of the timeperiod included. + */ + virtual void add_timeperiod_include_relation(uint32_t timeperiod_id, + uint32_t include_id) { + (void)timeperiod_id; + (void)include_id; + } +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_TIMEPERIOD_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_by_id_builder.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_by_id_builder.hh new file mode 100644 index 00000000000..f928c202d9b --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_by_id_builder.hh @@ -0,0 +1,49 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_TIMEPERIOD_BY_ID_BUILDER_HH +#define CCB_NOTIFICATION_BUILDERS_TIMEPERIOD_BY_ID_BUILDER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/timeperiod_builder.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" +#include "com/centreon/broker/time/timeperiod.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class timeperiod_by_id_builder timeperiod_by_id_builder.hh + * "com/centreon/broker/notification/builders/timeperiod_by_id_builder.hh" + * @brief Timeperiod by id builder. + */ +class timeperiod_by_id_builder : public timeperiod_builder { + public: + timeperiod_by_id_builder(QHash& table); + + void add_timeperiod(uint32_t id, time::timeperiod::ptr con); + + private: + QHash& _table; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_TIMEPERIOD_BY_ID_BUILDER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_linker.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_linker.hh new file mode 100644 index 00000000000..e98f5b54855 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/builders/timeperiod_linker.hh @@ -0,0 +1,59 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_BUILDERS_TIMEPERIOD_LINKER_HH +#define CCB_NOTIFICATION_BUILDERS_TIMEPERIOD_LINKER_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/timeperiod_builder.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" +#include "com/centreon/broker/time/timeperiod.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class timeperiod_linker timeperiod_linker.hh + * "com/centreon/broker/notification/builders/timeperiod_linker.hh" + * @brief Timeperiod linker. + * + * Links the timeperiod together. + */ +class timeperiod_linker : public timeperiod_builder { + public: + timeperiod_linker(); + + void add_timeperiod(uint32_t id, time::timeperiod::ptr con); + + void add_timeperiod_exception(uint32_t timeperiod_id, + std::string const& days, + std::string const& timerange); + void add_timeperiod_exclude_relation(uint32_t timeperiod_id, + uint32_t exclude_id); + void add_timeperiod_include_relation(uint32_t timeperiod_id, + uint32_t include_id); + + private: + QHash _table; +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_BUILDERS_TIMEPERIOD_LINKER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/connector.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/connector.hh new file mode 100644 index 00000000000..9c43dd9e696 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/connector.hh @@ -0,0 +1,68 @@ +/* +** Copyright 2014-2015 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_SQL_CONNECTOR_HH +#define CCB_SQL_CONNECTOR_HH + +#include +#include +#include "com/centreon/broker/io/endpoint.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/node_cache.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class connector connector.hh + * "com/centreon/broker/notification/connector.hh" + * @brief Connect to a database. + * + * Send events to a notification cache database. + */ +class connector : public io::endpoint { + public: + connector(std::shared_ptr cache); + connector(connector const& c); + ~connector(); + connector& operator=(connector const& c); + void connect_to(std::string const& type, + std::string const& host, + unsigned short port, + std::string const& user, + std::string const& password, + std::string const& centreon_db, + bool check_replication = true); + std::shared_ptr open(); + + private: + bool _check_replication; + std::string _centreon_db; + std::string _host; + std::string _password; + unsigned short _port; + std::string _type; + std::string _user; + std::shared_ptr _cache; + node_cache _node_cache; +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_SQL_CONNECTOR_HH diff --git a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/factory.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/factory.hh similarity index 68% rename from centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/factory.hh rename to centreon-broker/notification/inc/com/centreon/broker/notification/factory.hh index 54c29b010d8..ff63640732d 100644 --- a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/factory.hh +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/factory.hh @@ -1,5 +1,5 @@ /* -** Copyright 2011-2013 Centreon +** 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. @@ -16,35 +16,35 @@ ** For more information : contact@centreon.com */ -#ifndef CCB_UNIFIED_SQL_FACTORY_HH -#define CCB_UNIFIED_SQL_FACTORY_HH +#ifndef CCB_NOTIFICATION_FACTORY_HH +#define CCB_NOTIFICATION_FACTORY_HH #include "com/centreon/broker/io/factory.hh" #include "com/centreon/broker/namespace.hh" CCB_BEGIN() -namespace unified_sql { +namespace notification { /** - * @class factory factory.hh "com/centreon/broker/unified_sql/factory.hh" - * @brief Storage layer factory. + * @class factory factory.hh "com/centreon/broker/notification/factory.hh" + * @brief Notification layer factory. * - * Build unified_sql layer objects. + * Build Notification layer objects. */ class factory : public io::factory { public: factory() = default; - factory(factory const&) = delete; + factory(factory const& other) = delete; ~factory() = default; - factory& operator=(factory const&) = delete; - bool has_endpoint(config::endpoint& cfg, io::extension* ext); + factory& operator=(factory const& other) = delete; + bool has_endpoint(config::endpoint& cfg); io::endpoint* new_endpoint(config::endpoint& cfg, bool& is_acceptor, std::shared_ptr cache = std::shared_ptr()) const; }; -} // namespace unified_sql +} // namespace notification CCB_END() -#endif // !CCB_UNIFIED_SQL_FACTORY_HH +#endif // !CCB_NOTIFICATION_FACTORY_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/command_loader.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/command_loader.hh new file mode 100644 index 00000000000..9f11b990caa --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/command_loader.hh @@ -0,0 +1,47 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_LOADERS_COMMAND_LOADER_HH +#define CCB_NOTIFICATION_LOADERS_COMMAND_LOADER_HH + +#include "com/centreon/broker/mysql.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/command_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class command_loader command_loader.hh + * "com/centreon/broker/notification/loaders/command_loader.hh" + * @brief Loader for command objects. + * + * This loader loads the commands from the database. + */ +class command_loader { + public: + command_loader(); + + void load(mysql* db, command_builder* output); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_LOADERS_COMMAND_LOADER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/contact_loader.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/contact_loader.hh new file mode 100644 index 00000000000..b7608835829 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/contact_loader.hh @@ -0,0 +1,48 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_LOADERS_CONTACT_LOADER_HH +#define CCB_NOTIFICATION_LOADERS_CONTACT_LOADER_HH + +#include +#include "com/centreon/broker/mysql.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/contact_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class contact_loader contact_loader.hh + * "com/centreon/broker/notification/loaders/contact_loader.hh" + * @brief Loader for contact objects. + * + * This loader loads the contacts from the database. + */ +class contact_loader { + public: + contact_loader(); + + void load(mysql* db, contact_builder* output); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_LOADERS_CONTACT_LOADER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/dependency_loader.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/dependency_loader.hh new file mode 100644 index 00000000000..026dbf851a1 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/dependency_loader.hh @@ -0,0 +1,56 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_LOADERS_DEPENDENCY_LOADER_HH +#define CCB_NOTIFICATION_LOADERS_DEPENDENCY_LOADER_HH + +#include "com/centreon/broker/mysql.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/dependency_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class dependency_loader dependency_loader.hh + * "com/centreon/broker/notification/loaders/dependency_loader.hh" + * @brief Loader for dependency objects. + * + * This loader loads the dependencies from the database. + */ +class dependency_loader { + public: + dependency_loader(); + + void load(mysql* db, dependency_builder* output); + + private: + void _load_relations(mysql* ms, dependency_builder& output); + // void _load_relation( + // QSqlQuery& query, dependency_builder& output, + // std::string const& relation_id_name, + // std::string const& table, + // void (dependency_builder::*register_method) + // (uint32_t, uint32_t)); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_LOADERS_DEPENDENCY_LOADER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/escalation_loader.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/escalation_loader.hh new file mode 100644 index 00000000000..0ab10a0a821 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/escalation_loader.hh @@ -0,0 +1,61 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_LOADERS_ESCALATION_LOADER_HH +#define CCB_NOTIFICATION_LOADERS_ESCALATION_LOADER_HH + +#include +#include +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/escalation_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class escalation_loader escalation_loader.hh + * "com/centreon/broker/notification/loaders/escalation_loader.hh" + * @brief Loader for escalation objects. + * + * This loader loads the escalations from the database. + */ +class escalation_loader { + public: + escalation_loader(); + + void load(QSqlDatabase* db, escalation_builder* output); + + private: + std::vector _rows; + + void _load_relations(QSqlQuery& query, escalation_builder& output); + void _load_relation(QSqlQuery& query, + escalation_builder& output, + std::string const& relation_id_name, + std::string const& table, + void (escalation_builder::*register_method)(uint32_t, + uint32_t)); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_LOADERS_ESCALATION_LOADER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/macro_loader.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/macro_loader.hh new file mode 100644 index 00000000000..8565abdfeff --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/macro_loader.hh @@ -0,0 +1,47 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_LOADERS_MACRO_LOADER_HH +#define CCB_NOTIFICATION_LOADERS_MACRO_LOADER_HH + +#include "com/centreon/broker/mysql.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/macro_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class macro_loader macro_loader.hh + * "com/centreon/broker/notification/loaders/macro_loader.hh" + * @brief Loader for macro objects. + * + * This loader loads the macros from the database. + */ +class macro_loader { + public: + macro_loader(); + + void load(mysql* db, macro_builder* output); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_LOADERS_MACRO_LOADER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/node_loader.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/node_loader.hh new file mode 100644 index 00000000000..ac824c5c05f --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/node_loader.hh @@ -0,0 +1,48 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_LOADERS_NODE_LOADER_HH +#define CCB_NOTIFICATION_LOADERS_NODE_LOADER_HH + +#include +#include "com/centreon/broker/mysql.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/node_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class node_loader node_loader.hh + * "com/centreon/broker/notification/loaders/node_loader.hh" + * @brief Loader for node objects. + * + * This loader loads the nodes from the database. + */ +class node_loader { + public: + node_loader(); + + void load(mysql* db, node_builder* output); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_LOADERS_NODE_LOADER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/notification_method_loader.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/notification_method_loader.hh new file mode 100644 index 00000000000..369a913b68e --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/notification_method_loader.hh @@ -0,0 +1,48 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_LOADERS_NOTIFICATION_METHOD_LOADER_HH +#define CCB_NOTIFICATION_LOADERS_NOTIFICATION_METHOD_LOADER_HH + +#include +#include "com/centreon/broker/mysql.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/notification_method_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class notification_method_loader notification_method_loader.hh + * "com/centreon/broker/notification/loaders/notification_method_loader.hh" + * @brief Loader for notification method objects. + * + * This loader loads the notifcation methods from the database. + */ +class notification_method_loader { + public: + notification_method_loader(); + + void load(mysql* db, notification_method_builder* output); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_LOADERS_NOTIFICATION_METHOD_LOADER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/notification_rule_loader.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/notification_rule_loader.hh new file mode 100644 index 00000000000..61e34a45770 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/notification_rule_loader.hh @@ -0,0 +1,48 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_LOADERS_NOTIFICATION_RULE_LOADER_HH +#define CCB_NOTIFICATION_LOADERS_NOTIFICATION_RULE_LOADER_HH + +#include +#include "com/centreon/broker/mysql.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/notification_rule_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class notification_rule_loader notification_rule_loader.hh + * "com/centreon/broker/notification/loaders/notification_rule_loader.hh" + * @brief Loader for notification rules. + * + * This loader loads the notifcation rules from the database. + */ +class notification_rule_loader { + public: + notification_rule_loader(); + + void load(mysql* db, notification_rule_builder* output); +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_LOADERS_NOTIFICATION_RULE_LOADER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/timeperiod_loader.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/timeperiod_loader.hh new file mode 100644 index 00000000000..42dfaba80e7 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/loaders/timeperiod_loader.hh @@ -0,0 +1,49 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_LOADERS_TIMEPERIOD_LOADER_HH +#define CCB_NOTIFICATION_LOADERS_TIMEPERIOD_LOADER_HH + +#include "com/centreon/broker/mysql.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/timeperiod_builder.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class timeperiod_loader timeperiod_loader.hh + * "com/centreon/broker/notification/loaders/timeperiod_loader.hh" + * @brief Loader for timeperiod objects. + * + * This loader loads the timeperiods from the database. + */ +class timeperiod_loader { + public: + timeperiod_loader(); + + void load(mysql* ms, timeperiod_builder* output); + + private: +}; + +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_LOADERS_TIMEPERIOD_LOADER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/macro_context.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/macro_context.hh new file mode 100644 index 00000000000..a3a8a6367e0 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/macro_context.hh @@ -0,0 +1,64 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_MACRO_CONTEXT_HH +#define CCB_NOTIFICATION_MACRO_CONTEXT_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/action.hh" +#include "com/centreon/broker/notification/node_cache.hh" +#include "com/centreon/broker/notification/objects/contact.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" +#include "com/centreon/broker/notification/state.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class macro_context macro_context.hh + * "com/centreon/broker/notification/macro_context.hh" + * @brief This holds the context of a macro. + * + * Like the id of the node being notified, the contact being notified, etc. + */ +class macro_context { + public: + macro_context(objects::node_id id, + objects::contact const& cnt, + state const& st, + node_cache const& cache, + action const& act); + + objects::node_id get_id() const; + objects::contact const& get_contact() const; + state const& get_state() const; + node_cache const& get_cache() const; + action const& get_action() const; + + private: + objects::node_id _id; + objects::contact const& _cnt; + state const& _st; + node_cache const& _cache; + action const& _act; +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_MACRO_CONTEXT_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/macro_generator.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/macro_generator.hh new file mode 100644 index 00000000000..3e932e1f875 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/macro_generator.hh @@ -0,0 +1,71 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_MACRO_GENERATOR_HH +#define CCB_NOTIFICATION_MACRO_GENERATOR_HH + +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/macro_context.hh" +#include "com/centreon/broker/notification/node_cache.hh" +#include "com/centreon/broker/notification/objects/contact.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" +#include "com/centreon/broker/notification/state.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class macro_generator macro_generator.hh + * "com/centreon/broker/notification/macro_generator.hh" + * @brief Generates the macros. + */ +class macro_generator { + public: + typedef QHash macro_container; + macro_generator(); + + void generate(macro_container& container, + objects::node_id id, + objects::contact const& cnt, + state const& st, + node_cache const& cache, + action const& act) const; + + private: + static bool _get_global_macros(std::string const& macro_name, + state const& st, + std::string& result); + bool _get_x_macros(std::string const& macro_name, + macro_context const& context, + std::string& result) const; + static bool _get_custom_macros(std::string const& macro_name, + objects::node_id id, + node_cache const& cache, + std::string& result); + + typedef QHash x_macro_map; + static x_macro_map _map; + static void _fill_x_macro_map(x_macro_map& map); +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_MACRO_GENERATOR_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/macro_getters.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/macro_getters.hh new file mode 100644 index 00000000000..d9c68bd06e4 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/macro_getters.hh @@ -0,0 +1,480 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_MACRO_GETTERS_HH +#define CCB_NOTIFICATION_MACRO_GETTERS_HH + +#include +#include +#include +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/macro_context.hh" +#include "com/centreon/broker/notification/utilities/get_datetime_string.hh" + +CCB_BEGIN() + +namespace notification { + +// Utilities to remove references from type. +template +struct remove_all { + typedef T type; +}; +template +struct remove_all : remove_all {}; +template +struct remove_all : remove_all {}; +/** + * Set the precision of a stringstream. + * + * @tparam precision The precision. + * + * @param[out] ost The stringstream to modify. + */ +template +void set_precision(std::ostringstream& ost) { + ost << std::fixed << std::setprecision(precision); +} + +/** + * @brief Does not set the precision of a stringstream. + * + * Specialization of set_precision for precision = 0; + * + * @param[out] ost The stringstream to modify. + */ +template <> +void inline set_precision<0>(std::ostringstream& ost) { + (void)ost; +} + +/** + * Write a type into string. + * + * @tparam T The type. + * @tparam precision The precision one wants, 0 for none. + * + * @param[in] value The value. + * + * @return The value of the macro. + */ +template +std::string to_string(T const& value) { + std::ostringstream ost; + set_precision(ost); + ost << value; + return (ost.str()); +} + +/** + * @brief Write a type into a string. + * + * Specialization for std::string and 0 precision. + * + * @param[in] value The value of the string. + * + * @return The value of the macro. + */ +template <> +std::string inline to_string(std::string const& value) { + return (value); +} + +/** + * Get the member of a host as a string. + * + * @tparam T The type of the host object. + * @tparam U The type of the member. + * @tparam Member The member. + * @tparam precision The precision of the string, 0 for none. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_host_member_as_string(macro_context const& context) { + return (to_string( + context.get_cache().get_host(context.get_id()).get_node().*member)); +} + +/** + * Get the member of a service as a string. + * + * @tparam T The type of the service object. + * @tparam U The type of the member. + * @tparam Member The member. + * @tparam precision The precision of the string, 0 for none. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_service_member_as_string(macro_context const& context) { + return (to_string( + context.get_cache().get_service(context.get_id()).get_node().*member)); +} + +/** + * Get the member of a host status as a string. + * + * @tparam T The type of the host status object. + * @tparam U The type of the member. + * @tparam Member The member. + * @tparam precision The precision of the string, 0 for none. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_host_status_member_as_string(macro_context const& context) { + return (to_string( + context.get_cache().get_host(context.get_id()).get_status().*member)); +} + +/** + * Get the member of a service status as a string. + * + * @tparam T The type of the service status object. + * @tparam U The type of the member. + * @tparam Member The member. + * @tparam precision The precision of the string, 0 for none. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_service_status_member_as_string(macro_context const& context) { + return (to_string( + context.get_cache().get_service(context.get_id()).get_status().*member)); +} + +/** + * Get the member of a previous host status as a string. + * + * @tparam T The type of the previous host status object. + * @tparam U The type of the member. + * @tparam Member The member. + * @tparam precision The precision of the string, 0 for none. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_host_prevstatus_member_as_string(macro_context const& context) { + return (to_string( + context.get_cache().get_host(context.get_id()).get_prev_status().* + member)); +} + +/** + * Get the member of a previous service status as a string. + * + * @tparam T The type of the previous service status object. + * @tparam U The type of the member. + * @tparam Member The member. + * @tparam precision The precision of the string, 0 for none. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_service_prevstatus_member_as_string( + macro_context const& context) { + return (to_string( + context.get_cache().get_service(context.get_id()).get_prev_status().* + member)); +} + +/** + * Get the output of a host. + * + * @tparam get_long_output True if we want the long output, false if we want + * the short one. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_host_output(macro_context const& context + __attribute__((unused))) { + return ""; +} + +template <> +std::string get_host_output(macro_context const& context); + +template <> +std::string get_host_output(macro_context const& context); + +/** + * Get the output of a service. + * + * @tparam get_long_output True if we want the long output, false if we want + * the short one. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_service_output(macro_context const& context + __attribute__((unused))) { + return ""; +} + +template <> +std::string get_service_output(macro_context const& context); + +template <> +std::string get_service_output(macro_context const& context); + +/** + * Get the date or time string. + * + * @tparam date_type The type of the date. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_datetime_string(macro_context const& context) { + return (utilities::get_datetime_string( + ::time(NULL), 48, date_type, context.get_state().get_date_format())); +} + +/** + * Get the total number of services associated with the host. + * + * @tparam service_state The state of the services we want to count: -1 for + * all. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_total_host_services(macro_context const& context) { + QList services = + context.get_state().get_all_services_of_host(context.get_id().to_host()); + if (service_state != -1) { + size_t count = 0; + for (QList::iterator it(services.begin()), + end(services.end()); + it != end; ++it) + if ((*it)->get_hard_state() == objects::node_state(service_state)) + ++count; + return (to_string(count)); + } else + return (to_string(services.count())); +} + +/** + * Get the total number of hosts with a given state. + * + * @tparam host_state The state of the hosts we want to count. -1 for all that + * are not up. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_total_hosts(macro_context const& context) { + return (to_string( + context.get_state().get_all_hosts_in_state(host_state).size())); +} + +/** + * Get the total number of services with a given state. + * + * @tparam service_state The state of the services we want to count. -1 for + * all that are not ok. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_total_services(macro_context const& context) { + return (to_string( + context.get_state().get_all_services_in_state(service_state).size())); +} + +/** + * Get the total number of hosts unhandled with a given state. + * + * @tparam host_state The state of the hosts we want to count. -1 for all that + * are not up. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_total_hosts_unhandled(macro_context const& context) { + size_t count = 0; + node_cache const& cache = context.get_cache(); + state const& st = context.get_state(); + QList list = st.get_all_hosts_in_state(host_state); + for (QList::const_iterator it = list.begin(), + end = list.end(); + it != end; ++it) { + if (!cache.node_acknowledged((*it)->get_node_id()) && + !cache.node_in_downtime((*it)->get_node_id())) + ++count; + } + return (to_string(count)); +} + +/** + * Get the total number of services unhandled with a given state. + * + * @tparam service_state The state of the services we want to count. -1 for + * all that are not ok. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_total_services_unhandled(macro_context const& context) { + size_t count = 0; + node_cache const& cache = context.get_cache(); + state const& st = context.get_state(); + QList list = st.get_all_services_in_state(service_state); + for (QList::const_iterator it = list.begin(), + end = list.end(); + it != end; ++it) { + if (!cache.node_acknowledged((*it)->get_node_id()) && + !cache.node_in_downtime((*it)->get_node_id())) + ++count; + } + return (to_string(count)); +} + +/** + * Get the member of a contact as a string. + * + * @tparam U The type of the member. + * @tparam Member The member. + * @tparam precision The precision of the string, 0 for none. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_contact_member(macro_context const& context) { + return (to_string::type, precision>( + (context.get_contact().*member)())); +} + +/** + * Get a contact info. + * + * @tparam f A function returning the name of the contact info. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_contact_info(macro_context const& context) { + QHash infos = + context.get_state().get_contact_infos(context.get_contact().get_id()); + return (infos.value(f())); +} + +/** + * Get the member of an action as a string. + * + * @tparam U The type of the member. + * @tparam Member The member. + * @tparam precision The precision of the string, 0 for none. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_action_member(macro_context const& context) { + return (to_string::type, precision>( + (context.get_action().*member)())); +} + +/** + * Get the address of the contact. + * + * @tparam number The address number (1 to 6). + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template +std::string get_address_of_contact(macro_context const& context) { + std::stringstream ss; + ss << "address" << number; + return (context.get_state() + .get_contact_infos(context.get_contact().get_id()) + .value(ss.str())); +} + +// Static, non template getters. +std::string get_host_state(macro_context const& context); + +std::string get_service_state(macro_context const& context); + +std::string get_last_host_state(macro_context const& context); + +std::string get_last_service_state(macro_context const& context); + +std::string get_host_state_type(macro_context const& context); + +std::string get_service_state_type(macro_context const& context); + +std::string null_getter(macro_context const& context); + +std::string get_host_duration(macro_context const& context); + +std::string get_service_duration(macro_context const& context); + +std::string get_host_duration_sec(macro_context const& context); + +std::string get_service_duration_sec(macro_context const& context); + +std::string get_node_downtime_number(macro_context const& context); + +std::string get_timet_string(macro_context const& context); + +std::string get_notification_type(macro_context const& context); +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_MACRO_GETTERS_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/node_cache.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/node_cache.hh new file mode 100644 index 00000000000..c44d992227a --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/node_cache.hh @@ -0,0 +1,102 @@ +/* +** Copyright 2011-2015 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_NODE_CACHE_HH +#define CCB_NOTIFICATION_NODE_CACHE_HH + +#include +#include +#include +#include +#include +#include "com/centreon/broker/bbdo/stream.hh" +#include "com/centreon/broker/compression/stream.hh" +#include "com/centreon/broker/file/stream.hh" +#include "com/centreon/broker/multiplexing/hooker.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/neb/acknowledgement.hh" +#include "com/centreon/broker/neb/custom_variable_status.hh" +#include "com/centreon/broker/neb/downtime.hh" +#include "com/centreon/broker/neb/host.hh" +#include "com/centreon/broker/neb/host_status.hh" +#include "com/centreon/broker/neb/service.hh" +#include "com/centreon/broker/neb/service_status.hh" +#include "com/centreon/broker/notification/object_cache.hh" +#include "com/centreon/broker/notification/objects/node.hh" +#include "com/centreon/broker/persistent_cache.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class node_cache node_cache.hh + * "com/centreon/broker/notification/node_cache.hh" + * @brief Contain and update a cache of node information. + * + * Used by and for the macro processing. Also contains/generates the current + * acknowledgements and downtimes. Load from a file at startup, + * unload at shutdown. + */ +class node_cache : public multiplexing::hooker { + public: + typedef object_cache host_node_state; + typedef object_cache service_node_state; + + node_cache(std::shared_ptr cache); + ~node_cache(); + node_cache(node_cache const& f); + node_cache& operator=(node_cache const& f); + + virtual void starting(); + virtual void stopping(); + virtual bool read(std::shared_ptr& d, time_t deadline); + virtual int write(std::shared_ptr const& d); + + using io::stream::update; + void update(neb::host const& hst); + void update(neb::host_status const& hs); + void update(neb::service const& svc); + void update(neb::service_status const& ss); + void update(neb::custom_variable_status const& cvs); + void update(neb::acknowledgement const& ack); + void update(neb::downtime const& dwn); + + host_node_state const& get_host(objects::node_id id) const; + service_node_state const& get_service(objects::node_id id) const; + + bool node_in_downtime(objects::node_id node) const; + uint32_t node_downtimes(objects::node_id node) const; + bool node_acknowledged(objects::node_id node) const; + + private: + void _save_cache(); + + QHash _host_node_states; + QHash _service_node_states; + QHash _acknowledgements; + QHash _downtimes; + QMultiHash _downtime_id_by_nodes; + QMutex _mutex; + + std::shared_ptr _cache; +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_NODE_CACHE_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/notification_scheduler.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/notification_scheduler.hh new file mode 100644 index 00000000000..66c50bde856 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/notification_scheduler.hh @@ -0,0 +1,85 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_NOTIFICATION_SCHEDULER_HH +#define CCB_NOTIFICATION_NOTIFICATION_SCHEDULER_HH + +#include +#include +#include +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/action.hh" +#include "com/centreon/broker/notification/run_queue.hh" + +CCB_BEGIN() + +namespace notification { +// Forward declaration. +class state; +class node_cache; + +/** + * @class notification_scheduler notification_scheduler.hh + * "com/centreon/broker/notification/notification_scheduler.hh" + * @brief The notification scheduler. + * + * Manage a thread as a notification scheduler. + */ +class notification_scheduler { + public: + notification_scheduler( + ::com::centreon::broker::notification::state& st, + ::com::centreon::broker::notification::node_cache& cache); + + void start(); + void exit() throw(); + void add_action_to_queue(time_t at, action a); + void remove_actions_of_node(objects::node_id id); + void wait(); + + protected: + void run(); + + private: + std::thread _thread; + + // only used by master + bool _started_flag; + + run_queue _queue; + bool _should_exit; + std::mutex _general_mutex; + std::condition_variable _general_condition; + + void _process_actions(); + void _schedule_actions( + std::vector > const& actions); + + notification_scheduler(notification_scheduler const& obj); + notification_scheduler& operator=(notification_scheduler const& obj); + + ::com::centreon::broker::notification::state& _state; + ::com::centreon::broker::notification::node_cache& _cache; +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_NOTIFICATION_SCHEDULER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/object_cache.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/object_cache.hh new file mode 100644 index 00000000000..f140e8fc6fc --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/object_cache.hh @@ -0,0 +1,170 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_OBJECT_CACHE_HH +#define CCB_NOTIFICATION_OBJECT_CACHE_HH + +#include +#include +#include +#include +#include "com/centreon/broker/io/data.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/neb/custom_variable_status.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class object_cache object_cache.hh + * "com/centreon/broker/notification/object_cache.hh" + * @tparam T The type of the object cached. + * @brief Contain a fixed size cache of a particular object. + */ +template +class object_cache { + public: + /** + * Default constructor + */ + object_cache() {} + /** + * Copy constructor + * @param[in] obj The object to copy. + */ + object_cache(object_cache const& obj) { + object_cache::operator=(obj); + } + + /** + * Assignment operator. + * + * @param[in] obj The obect to copy. + * + * @return A reference this object. + */ + object_cache& operator=( + object_cache const& obj) { + if (this != &obj) { + _node = obj._node; + _current_status = obj._current_status; + _prev_status = obj._prev_status; + _custom_variables = obj._custom_variables; + } + return (*this); + } + + /** + * Serialize the data of the object cache into a vector. + * + * @param[in] out The vector to fill. + */ + void serialize(std::deque >& out) const { + out.push_back(std::make_shared(_node)); + out.push_back(std::make_shared(_prev_status)); + out.push_back(std::make_shared(_current_status)); + for (std::unordered_map::const_iterator + it{_custom_variables.begin()}, + end{_custom_variables.end()}; + it != end; ++it) + out.push_back(std::make_shared(it->second)); + } + + /** + * Update the object cache. + * + * @param[in] n The data to update. + */ + void update(FullType const& n) { _node = n; } + + /** + * Update the object cache. + * + * @param[in] status The data to update. + */ + void update(StatusType const& status) { + _prev_status = _current_status; + _current_status = status; + } + + /** + * Update the object cache. + * + * @param[in] var The data to update. + */ + void update(neb::custom_variable_status const& var) { + std::string var_name{var.service_id ? "_SERVICE" : "_HOST"}; + var_name.append(var.name); + if (var.value.empty()) { + log_v2::notification()->debug( + "notification: removing custom variable '{}' from node ({}, {})", + var_name, var.host_id, var.service_id); + _custom_variables.erase(var_name); + } else { + log_v2::notification( + "notification: adding custom variable '{}' to node ({}, {})", + var_name, var.host_id, var.service_id); + _custom_variables.insert({var_name, var}); + } + } + + /** + * Get the node object. + * + * @return The node object. + */ + FullType const& get_node() const { return _node; } + + /** + * Get the status object. + * + * @return The status object. + */ + StatusType const& get_status() const { return (_current_status); } + + /** + * Get the prev status. + * + * @return The prev status. + */ + StatusType const& get_prev_status() const { return (_prev_status); } + + /** + * Get the custom vars of this node. + * + * @return The custome vars of this node. + */ + std::unordered_map const& + get_custom_vars() const { + return _custom_variables; + } + + private: + FullType _node; + StatusType _current_status; + StatusType _prev_status; + + std::unordered_map + _custom_variables; +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_NODE_CACHE_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/objects/command.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/command.hh new file mode 100644 index 00000000000..80c75cfff85 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/command.hh @@ -0,0 +1,85 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_COMMAND_HH +#define CCB_NOTIFICATION_COMMAND_HH + +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/neb/host_status.hh" +#include "com/centreon/broker/neb/service_status.hh" +#include "com/centreon/broker/notification/node_cache.hh" +#include "com/centreon/broker/notification/objects/contact.hh" +#include "com/centreon/broker/notification/objects/node.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" +#include "com/centreon/broker/notification/objects/notification_method.hh" +#include "com/centreon/broker/notification/objects/notification_rule.hh" +#include "com/centreon/broker/notification/utilities/ptr_typedef.hh" + +CCB_BEGIN() + +namespace notification { +// Forward declaration. +class action; +class state; + +namespace objects { +/** + * @class command command.hh + * "com/centreon/broker/notification/objects/command.hh" + * @brief Command object. + * + * The object containing a command. + */ +class command { + public: + DECLARE_SHARED_PTR(command); + + command(std::string const& base_command); + command(command const& obj); + command& operator=(command const& obj); + + bool get_enable_shell() const throw(); + void set_enable_shell(bool val); + std::string const& get_name() const throw(); + void set_name(std::string const& name); + + std::string resolve(contact::ptr const& contact, + node::ptr const& n, + node_cache const& cache, + state const& st, + action const& act); + + private: + command(); + + bool _enable_shell; + std::string _name; + std::string _base_command; + + static const QRegExp _macro_regex; + + // static _macro_init(); +}; +} // namespace objects +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_COMMAND_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/objects/contact.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/contact.hh new file mode 100644 index 00000000000..3453bc86743 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/contact.hh @@ -0,0 +1,62 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_CONTACT_HH +#define CCB_NOTIFICATION_CONTACT_HH + +#include +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/objects/defines.hh" +#include "com/centreon/broker/notification/utilities/ptr_typedef.hh" + +CCB_BEGIN() + +namespace notification { +namespace objects { +/** + * @class contact contact.hh + * "com/centreon/broker/notification/objects/contact.hh" + * @brief Contact object. + * + * The object containing a contact. + */ +class contact { + public: + DECLARE_SHARED_PTR(contact); + + contact(); + contact(contact const& obj); + contact& operator=(contact const& obj); + + uint32_t get_id() const throw(); + void set_id(uint32_t); + std::string const& get_description() const throw(); + void set_description(std::string const& desc); + + private: + uint32_t _id; + std::string _description; +}; +} // namespace objects +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_CONTACT_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/objects/defines.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/defines.hh new file mode 100644 index 00000000000..736933a51bc --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/defines.hh @@ -0,0 +1,59 @@ +/* +** Copyright 2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_OBJECTS_DEFINES_HH +#define CCB_NOTIFICATION_OBJECTS_DEFINES_HH + +#include "com/centreon/broker/namespace.hh" + +CCB_BEGIN() + +namespace notification { +namespace objects { +class node_state { + public: + enum state_type { + ok = 0, + host_up = 0, + host_down = 1, + host_unreachable = 2, + service_ok = 0, + service_warning = 1, + service_critical = 2, + service_unknown = 3 + }; + + node_state(); + node_state(state_type type); + node_state(short); + node_state(int); + node_state(node_state const& st); + node_state& operator=(node_state const& st); + bool operator==(node_state const& st) const throw(); + bool operator==(node_state::state_type type) const throw(); + + operator int() const throw(); + + state_type value; +}; +} // namespace objects +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_OBJECTS_DEFINES_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/objects/dependency.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/dependency.hh new file mode 100644 index 00000000000..b39624bb355 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/dependency.hh @@ -0,0 +1,114 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_DEPENDENCY_HH +#define CCB_NOTIFICATION_DEPENDENCY_HH + +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/utilities/ptr_typedef.hh" + +CCB_BEGIN() + +namespace notification { +namespace objects { +/** + * @class dependency dependency.hh + * "com/centreon/broker/notification/objects/dependency.hh" + * @brief Dependency object. + * + * The object containing a dependency. + */ +class dependency { + public: + DECLARE_SHARED_PTR(dependency); + + enum type { unknown = 0, host, service }; + + enum action_on { + none = 0, + host_up = (1 << 0), + host_down = (1 << 1), + host_unreachable = (1 << 2), + host_pending = (1 << 3), + service_ok = (1 << 4), + service_unknown = (1 << 5), + service_warning = (1 << 6), + service_critical = (1 << 7), + service_pending = (1 << 8) + }; + + enum dependency_kind { + unknown_dependency = 0, + notification_dependency, + execution_dependency + }; + + dependency(); + dependency(dependency const& obj); + dependency& operator=(dependency const& obj); + + bool is_host_dependency() const throw(); + void set_is_host_dependency(bool val) throw(); + bool is_service_dependency() const throw(); + void set_is_service_dependency(bool val) throw(); + + std::string const& get_period() const throw(); + void set_period(std::string const& val); + dependency_kind get_kind() const throw(); + void set_kind(dependency_kind val) throw(); + action_on get_execution_failure_options() const throw(); + void set_execution_failure_options(action_on val) throw(); + void set_execution_failure_option(action_on val) throw(); + bool is_execution_failure_option_set(action_on val) throw(); + bool get_inherits_parent() const throw(); + void set_inherits_parent(bool val) throw(); + action_on get_notification_failure_options() const throw(); + void set_notification_failure_options(action_on val) throw(); + void set_notification_failure_option(action_on val) throw(); + bool is_notification_failure_option_set(action_on val) const throw(); + + void parse_notification_failure_options(std::string const& line); + void parse_execution_failure_options(std::string const& line); + + private: + type _type; + std::string _dependency_period; + dependency_kind _dependency_type; + action_on _execution_failure_options; + bool _inherits_parent; + action_on _notification_failure_options; + + struct name_to_action { + const char* name; + action_on action; + }; + + static const name_to_action _service_actions[]; + static const name_to_action _host_actions[]; + + void _parse_failure_options(std::string const& line, + void (dependency::*func_to_call)(action_on)); +}; +} // namespace objects +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_DEPENDENCY_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/objects/node.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/node.hh new file mode 100644 index 00000000000..8608647a95d --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/node.hh @@ -0,0 +1,85 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_NODE_HH +#define CCB_NOTIFICATION_NODE_HH + +#include +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/objects/defines.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" +#include "com/centreon/broker/notification/utilities/ptr_typedef.hh" + +CCB_BEGIN() + +namespace notification { +namespace objects { +/** + * @class node node.hh "com/centreon/broker/notification/objects/node.hh" + * @brief A node object. + * + * The object containing a node of the notification module. + */ +class node { + public: + DECLARE_SHARED_PTR(node); + + node(); + node(node const& obj); + node& operator=(node const& obj); + + int get_notification_number() const throw(); + void set_notification_number(int value); + time_t get_last_notification_time() const throw(); + void set_last_notification_time(time_t value); + node_state get_hard_state() const throw(); + void set_hard_state(node_state value); + node_state get_soft_state() const throw(); + void set_soft_state(node_state value); + node_id get_node_id() const throw(); + void set_node_id(node_id) throw(); + std::set const& get_parents() const throw(); + void add_parent(node_id id); + void remove_parent(node_id id); + bool has_parent() const throw(); + bool get_notifications_enabled() const throw(); + void set_notifications_enabled(bool enable) throw(); + std::string const& get_notification_timeperiod() const throw(); + void set_notification_timeperiod(std::string const& tp); + double get_notification_interval() const throw(); + void set_notification_interval(double val) throw(); + + private: + int _notification_number; + bool _notifications_enabled; + double _notification_interval; + time_t _last_notification_time; + node_state _hard_state; + node_state _soft_state; + node_id _id; + std::set _parents; + std::string _notification_period; +}; +} // namespace objects +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_NODE_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/objects/node_id.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/node_id.hh new file mode 100644 index 00000000000..2fc2f1a97b0 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/node_id.hh @@ -0,0 +1,66 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_NODE_ID_HH +#define CCB_NOTIFICATION_NODE_ID_HH + +#include +#include "com/centreon/broker/namespace.hh" + +CCB_BEGIN() + +namespace notification { +namespace objects { +/** + * @class node_id node_id.hh + * "com/centreon/broker/notification/objects/node_id.hh" + * @brief Node id object. + * + * This object contains the id of a node: a host id and an associated + * service id. Both the host id or the service id can be zero for service + * associated with no hosts and inversely. + */ +class node_id { + public: + node_id(); + node_id(node_id const& obj); + node_id& operator=(node_id const& obj); + explicit node_id(uint32_t host_id, uint32_t service_id = 0); + bool operator<(node_id const& obj) const throw(); + bool operator==(node_id const& obj) const throw(); + bool operator!=(node_id const& obj) const throw(); + + uint32_t get_host_id() const throw(); + uint32_t get_service_id() const throw(); + bool is_host() const throw(); + bool is_service() const throw(); + node_id to_host() const throw(); + + private: + uint32_t _host_id; + uint32_t _service_id; +}; + +// QHash function for hash and sets. +uint qHash(objects::node_id id); +} // namespace objects +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_NODE_ID_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/objects/notification_method.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/notification_method.hh new file mode 100644 index 00000000000..7c6a651f197 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/notification_method.hh @@ -0,0 +1,85 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_NOTIFICATION_METHOD_HH +#define CCB_NOTIFICATION_NOTIFICATION_METHOD_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/action.hh" +#include "com/centreon/broker/notification/objects/defines.hh" +#include "com/centreon/broker/notification/utilities/ptr_typedef.hh" + +CCB_BEGIN() + +namespace notification { +namespace objects { +/** + * @class notification_method notification_method.hh + * "com/centreon/broker/notification/objects/notification_method.hh" + * @brief The notification method object. + * + */ +class notification_method { + public: + DECLARE_SHARED_PTR(notification_method); + + notification_method(); + notification_method(notification_method const& obj); + notification_method& operator=(notification_method const& obj); + + std::string const& get_name() const throw(); + void set_name(std::string const& val); + + uint32_t get_command_id() const throw(); + void set_command_id(uint32_t id) throw(); + + uint32_t get_interval() const throw(); + void set_interval(uint32_t val) throw(); + + std::string const& get_status() const throw(); + void set_status(std::string const& val); + + std::string const& get_types() const throw(); + void set_types(std::string const& val); + + uint32_t get_start() const throw(); + void set_start(uint32_t val) throw(); + + uint32_t get_end() const throw(); + void set_end(uint32_t val) throw(); + + bool should_be_notified_for(node_state state, bool is_service) const; + bool should_be_notified_for(action::action_type type) const; + bool should_be_notified_when_correlated() const; + + private: + std::string _name; + uint32_t _command_id; + uint32_t _interval; + std::string _status; + std::string _types; + uint32_t _start; + uint32_t _end; +}; +} // namespace objects +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_NOTIFICATION_METHOD_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/objects/notification_rule.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/notification_rule.hh new file mode 100644 index 00000000000..17ef2756a33 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/notification_rule.hh @@ -0,0 +1,73 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_NOTIFICATION_RULE_HH +#define CCB_NOTIFICATION_NOTIFICATION_RULE_HH + +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/objects/defines.hh" +#include "com/centreon/broker/notification/objects/node_id.hh" +#include "com/centreon/broker/notification/utilities/ptr_typedef.hh" + +CCB_BEGIN() + +namespace notification { +namespace objects { +/** + * @class notification_rule notification_rule.hh + * "com/centreon/broker/notification/objects/notification_rule.hh" + * @brief The notification rule object. + * + */ +class notification_rule { + public: + DECLARE_SHARED_PTR(notification_rule); + + notification_rule(); + notification_rule(notification_rule const& obj); + notification_rule& operator=(notification_rule const& obj); + + uint32_t get_id(); + void set_id(uint32_t id); + + uint32_t get_method_id() const throw(); + void set_method_id(uint32_t) throw(); + + uint32_t get_timeperiod_id() const throw(); + void set_timeperiod_id(uint32_t val) throw(); + + uint32_t get_contact_id() const throw(); + void set_contact_id(uint32_t val) throw(); + + node_id get_node_id() const throw(); + void set_node_id(node_id val) throw(); + + private: + uint32_t _id; + uint32_t _method_id; + uint32_t _timeperiod_id; + uint32_t _contact_id; + node_id _node_id; +}; +} // namespace objects +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_NOTIFICATION_RULE_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/objects/record.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/record.hh new file mode 100644 index 00000000000..95387e35dec --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/objects/record.hh @@ -0,0 +1,42 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_NODE_HH +#define CCB_NOTIFICATION_NODE_HH + +#include +#include "com/centreon/broker/namespace.hh" + +CCB_BEGIN() + +namespace notification { +namespace objects { + +struct record { + record(const char* name, uint32_t index) : name(name), index(index) {} + record() : name(NULL), index(0) {} + + const char* name; + uint32_t index; +}; +} // namespace objects +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_NODE_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/process.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/process.hh new file mode 100644 index 00000000000..b49f2d46bf1 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/process.hh @@ -0,0 +1,83 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_PROCESS_HH +#define CCB_NOTIFICATION_PROCESS_HH + +#include +#include +#include +#include +#include "com/centreon/broker/namespace.hh" + +namespace com { +namespace centreon { +namespace broker { +namespace notification { +// Forward declaration. +class process_manager; +/** + * @class process process.hh "com/centreon/broker/notification/process.hh" + * @brief Represent a process being executed. + */ +class process : public QObject { + Q_OBJECT + + public: + process(int timeout = 0); + + uint32_t get_timeout() const throw(); + bool is_running() const; + void kill(); + + bool exec(std::string const& program, process_manager* manager = NULL); + + bool is_timeout() const throw(); + + bool get_error(int& exit_code, std::string& error_output); + + public slots: + void start(QString const& command_line); + void error(); + void finished(); + void timeouted(); + + signals: + void finished(process&); + void timeouted(process&); + + private: + process(process const&); + process& operator=(process const&); + + uint32_t _timeout; + time_t _start_time; + std::unique_ptr _process; + + bool _in_error; + QProcess::ProcessError _error; + QProcess::ExitStatus _status; + int _exit_code; + std::string _error_output; +}; +} // namespace notification +} // namespace broker +} // namespace centreon +} // namespace com + +#endif // !CCB_NOTIFICATION_PROCESS_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/process_manager.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/process_manager.hh new file mode 100644 index 00000000000..704c1041d75 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/process_manager.hh @@ -0,0 +1,70 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_PROCESS_MANAGER_HH +#define CCB_NOTIFICATION_PROCESS_MANAGER_HH + +#include +#include +#include +#include +#include +#include +#include "com/centreon/broker/notification/process.hh" + +namespace com { +namespace centreon { +namespace broker { +namespace notification { +/** + * @class process_manager process_manager.hh + * "com/centreon/broker/notification/processprocess_manager.hh" + * @brief Manage the processes. + */ +class process_manager : public QObject { + Q_OBJECT + + public: + static process_manager& instance(); + static void release(); + + void create_process(std::string const& command, uint32_t timeout = 0); + + QThread& get_thread(); + + public slots: + void process_finished(process&); + void process_timeouted(process&); + + private: + static process_manager* _instance_ptr; + process_manager(); + process_manager(process_manager const&); + process_manager& operator=(process_manager const&); + + std::recursive_mutex _process_list_mutex; + std::set _process_list; + + std::unique_ptr _thread; +}; +} // namespace notification +} // namespace broker +} // namespace centreon +} // namespace com + +#endif // !CCB_NOTIFICATION_PROCESS_MANAGER_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/run_queue.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/run_queue.hh new file mode 100644 index 00000000000..67524cd24da --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/run_queue.hh @@ -0,0 +1,73 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_RUN_QUEUE_HH +#define CCB_NOTIFICATION_RUN_QUEUE_HH + +#include +#include +#include +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/action.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class run_queue run_queue.hh + * "com/centreon/broker/notification/run_queue.hh" + * @brief A run queue of actions. + * + * This class is optimized to search an action by time and by node. + */ +class run_queue { + public: + typedef std::multimap action_map; + typedef action_map::iterator iterator; + typedef action_map::const_iterator const_iterator; + + run_queue(); + run_queue(run_queue const& obj); + run_queue& operator=(run_queue const& obj); + void move_to_queue(run_queue& obj, time_t until); + + void run(time_t at, action a); + void remove_first(); + void remove(action const& a); + + iterator begin(); + const_iterator begin() const; + iterator end(); + const_iterator end() const; + + std::vector get_actions_of_node(objects::node_id id); + + time_t get_first_time() const throw(); + + private: + action_map _action_by_time; + std::multimap _action_by_node; + std::set _action_set; + + void _rebuild_set(); +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_RUN_QUEUE_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/state.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/state.hh new file mode 100644 index 00000000000..469ccf06652 --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/state.hh @@ -0,0 +1,102 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_STATE_HH +#define CCB_NOTIFICATION_STATE_HH + +#include +#include +#include +#include +#include +#include +#include +#include "com/centreon/broker/mysql.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/notification/builders/node_set_builder.hh" +#include "com/centreon/broker/notification/loaders/command_loader.hh" +#include "com/centreon/broker/notification/loaders/contact_loader.hh" +#include "com/centreon/broker/notification/loaders/dependency_loader.hh" +#include "com/centreon/broker/notification/loaders/macro_loader.hh" +#include "com/centreon/broker/notification/loaders/node_loader.hh" +#include "com/centreon/broker/notification/loaders/notification_method_loader.hh" +#include "com/centreon/broker/notification/loaders/notification_rule_loader.hh" +#include "com/centreon/broker/notification/loaders/timeperiod_loader.hh" +#include "com/centreon/broker/notification/notification_scheduler.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class state state.hh "com/centreon/broker/notification/state.hh" + * @brief Regroup the objects loaded from the database. + */ +class state { + public: + state(); + state(state const& obj); + state& operator=(state const& obj); + + void update_objects_from_db(mysql& centreon_db); + + std::unique_ptr read_lock(); + std::unique_ptr write_lock(); + + objects::node::ptr get_node_by_id(objects::node_id) const; + time::timeperiod::ptr get_timeperiod_by_id(uint32_t id) const; + QList get_notification_rules_by_node( + objects::node_id id) const; + objects::notification_method::ptr get_notification_method_by_id( + uint32_t id) const; + objects::notification_rule::ptr get_notification_rule_by_id( + uint32_t id) const; + objects::contact::ptr get_contact_by_id(uint32_t id) const; + QHash get_contact_infos(uint32_t id) const; + objects::command::ptr get_command_by_id(uint32_t id) const; + QHash const& get_global_macros() const; + QList get_all_services_of_host(objects::node_id id) const; + QList get_all_hosts_in_state(short state) const; + QList get_all_services_in_state(short state) const; + int get_date_format() const; + + private: + QSet _nodes; + QHash _node_by_id; + QHash _commands; + QHash _contacts; + QHash > _contact_infos; + QMultiHash + _dependency_by_child_id; + QMultiHash + _dependency_by_parent_id; + QHash _timeperiod_by_id; + QHash _notification_methods; + QMultiHash + _notification_rules_by_node; + QHash _notification_rule_by_id; + + int _date_format; + QHash _global_constant_macros; + + QReadWriteLock _state_mutex; +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_STATE_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/stream.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/stream.hh new file mode 100644 index 00000000000..535a21f327e --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/stream.hh @@ -0,0 +1,96 @@ +/* +** Copyright 2014-2015 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_STREAM_HH +#define CCB_NOTIFICATION_STREAM_HH + +#include +#include +#include +#include +#include +//# include +//# include +#include +#include +#include +#include "com/centreon/broker/io/stream.hh" +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/neb/acknowledgement.hh" +#include "com/centreon/broker/neb/downtime.hh" +#include "com/centreon/broker/notification/node_cache.hh" +#include "com/centreon/broker/notification/process_manager.hh" +#include "com/centreon/broker/notification/state.hh" + +CCB_BEGIN() + +namespace notification { +/** + * @class stream stream.hh "com/centreon/broker/notification/stream.hh" + * @brief Notification stream. + * + * Stream events into the notification database. + */ +class stream : public io::stream { + public: + stream(std::string const& type, + std::string const& host, + unsigned short port, + std::string const& user, + std::string const& password, + std::string const& centreon_db, + bool check_replication, + node_cache& cache); + stream(stream const& s); + ~stream(); + static void initialize(); + bool read(std::shared_ptr& d, time_t deadline); + void update(); + int write(std::shared_ptr const& d); + + private: + stream& operator=(stream const& s); + void _open_db(std::unique_ptr& db, + std::string const& t, + std::string const& host, + unsigned short port, + std::string const& user, + std::string const& password, + std::string const& db_name, + bool check_replication); + // void _clone_db( + // std::unique_ptr& db, + // std::unique_ptr const& db_to_clone, + // QString const& id); + void _update_objects_from_db(); + void _process_service_status_event(neb::service_status const& event); + void _process_host_status_event(neb::host_status const& event); + void _process_ack(neb::acknowledgement const& event); + void _process_downtime(neb::downtime const& event); + + std::unique_ptr _centreon_db; + std::unique_ptr _notif_scheduler; + + state _state; + node_cache& _node_cache; +}; +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_STREAM_HH diff --git a/centreon-broker/notification/inc/com/centreon/broker/notification/utilities/get_datetime_string.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/utilities/get_datetime_string.hh new file mode 100644 index 00000000000..c096d48ed6c --- /dev/null +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/utilities/get_datetime_string.hh @@ -0,0 +1,54 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_NOTIFICATION_UTILITIES_GET_DATETIME_STRING_HH +#define CCB_NOTIFICATION_UTILITIES_GET_DATETIME_STRING_HH + +#include +#include "com/centreon/broker/namespace.hh" + +CCB_BEGIN() + +namespace notification { +namespace utilities { + +std::string get_datetime_string(time_t raw_time, + int max_length, + int type, + int format); + +enum date_type { + long_date_time = 0, + short_date_time = 1, + short_date = 2, + short_time = 3, + http_date_time = 4 +}; + +enum date_format { + date_format_us = 0, + date_format_euro = 1, + date_format_iso8601 = 2, + date_format_strict_iso8601 +}; +} // namespace utilities +} // namespace notification + +CCB_END() + +#endif // !CCB_NOTIFICATION_UTILITIES_GET_DATETIME_STRING_HH diff --git a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/internal.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/utilities/ptr_typedef.hh similarity index 63% rename from centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/internal.hh rename to centreon-broker/notification/inc/com/centreon/broker/notification/utilities/ptr_typedef.hh index e588dcaf65b..9c49aefbfcd 100644 --- a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/internal.hh +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/utilities/ptr_typedef.hh @@ -1,5 +1,5 @@ /* -** Copyright 2013 Centreon +** Copyright 2011-2014 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -16,19 +16,11 @@ ** For more information : contact@centreon.com */ -#ifndef CCB_UNIFIED_SQL_INTERNAL_HH -#define CCB_UNIFIED_SQL_INTERNAL_HH +#ifndef CCB_NOTIFICATION_UTILITIES_PTR_TYPEDEF_HH +#define CCB_NOTIFICATION_UTILITIES_PTR_TYPEDEF_HH -#include "bbdo/events.hh" -#include "bbdo/rebuild.pb.h" -#include "com/centreon/broker/io/protobuf.hh" +#include -CCB_BEGIN() +#define DECLARE_SHARED_PTR(klass) typedef std::shared_ptr ptr -namespace unified_sql { -using pb_rebuild = io::protobuf; -} - -CCB_END() - -#endif // !CCB_UNIFIED_SQL_INTERNAL_HH +#endif //! CCB_NOTIFICATION_UTILITIES_PTR_TYPEDEF_HH diff --git a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/events.hh b/centreon-broker/notification/inc/com/centreon/broker/notification/utilities/qhash_func.hh similarity index 63% rename from centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/events.hh rename to centreon-broker/notification/inc/com/centreon/broker/notification/utilities/qhash_func.hh index f1a8a3a6368..bc16abe496e 100644 --- a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/events.hh +++ b/centreon-broker/notification/inc/com/centreon/broker/notification/utilities/qhash_func.hh @@ -1,5 +1,5 @@ /* -** Copyright 2013 Centreon +** Copyright 2011-2013 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -16,12 +16,13 @@ ** For more information : contact@centreon.com */ -#ifndef CCB_UNIFIED_SQL_EVENTS_HH -#define CCB_UNIFIED_SQL_EVENTS_HH +#ifndef CCB_NOTIFICATION_QHASH_FUNC_HH +#define CCB_NOTIFICATION_QHASH_FUNC_HH -#include "com/centreon/broker/unified_sql/metric.hh" -#include "com/centreon/broker/unified_sql/rebuild.hh" -#include "com/centreon/broker/unified_sql/remove_graph.hh" -#include "com/centreon/broker/unified_sql/status.hh" +#include +#include -#endif // !CCB_UNIFIED_SQL_EVENTS_HH +// QHash function for std::string +uint qHash(std::string const& str); + +#endif // !CCB_NOTIFICATION_QHASH_FUNC_HH diff --git a/centreon-broker/notification/mysql_v3.sql b/centreon-broker/notification/mysql_v3.sql new file mode 100644 index 00000000000..8ee79398dc1 --- /dev/null +++ b/centreon-broker/notification/mysql_v3.sql @@ -0,0 +1,91 @@ +-- ------------------------------------ +-- -- +-- Centreon Broker's database schema -- +-- -- +-- -- +-- Notification -- +-- ------------------------------------ + +-- cfg_notification_methods +-- cfg_notification_rules +-- rt_notification_rules + +-- +-- Notification methods. +-- +CREATE TABLE cfg_notification_methods ( + method_id int NOT NULL auto_increment, + name varchar (255) NOT NULL, + + command_id int NOT NULL, + `interval` int default NULL, + status varchar (32) default NULL, + types varchar (32) default NULL, + start int default NULL, + end int default NULL, + + PRIMARY KEY (method_id), + UNIQUE (name), + FOREIGN KEY (command_id) REFERENCES cfg_commands (command_id) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET utf8; + +-- +-- Notification rules (configuration). +-- +CREATE TABLE cfg_notification_rules ( + rule_id int NOT NULL auto_increment, + + owner_id int NOT NULL, + method_id int NOT NULL, + host_id int default NULL, + service_id int default NULL, + hg_id int default NULL, + sg_id int default NULL, + contact_id int default NULL, + timeperiod_id int default NULL, + enabled boolean NOT NULL default 1, + + PRIMARY KEY (rule_id), + FOREIGN KEY (owner_id) REFERENCES cfg_contacts (contact_id) + ON DELETE RESTRICT, + FOREIGN KEY (method_id) REFERENCES cfg_notification_methods (method_id) + ON DELETE CASCADE, + FOREIGN KEY (host_id) REFERENCES cfg_hosts (host_id) + ON DELETE CASCADE, + FOREIGN KEY (service_id) REFERENCES cfg_services (service_id) + ON DELETE CASCADE, + FOREIGN KEY (hg_id) REFERENCES cfg_hostgroups (hg_id) + ON DELETE CASCADE, + FOREIGN KEY (sg_id) REFERENCES cfg_servicegroups (sg_id) + ON DELETE CASCADE, + FOREIGN KEY (contact_id) REFERENCES cfg_contacts (contact_id) + ON DELETE CASCADE, + FOREIGN KEY (timeperiod_id) REFERENCES cfg_timeperiods (tp_id) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET utf8; + +-- +-- Notification rules (expanded). +-- +CREATE TABLE rt_notification_rules ( + rule_id int NOT NULL, + method_id int NOT NULL, + timeperiod_id int default NULL, + contact_id int NOT NULL, + host_id int NOT NULL, + service_id int default NULL, + + FOREIGN KEY (rule_id) REFERENCES cfg_notification_rules (rule_id) + ON DELETE CASCADE, + FOREIGN KEY (method_id) REFERENCES cfg_notification_methods (method_id) + ON DELETE CASCADE, + FOREIGN KEY (timeperiod_id) REFERENCES cfg_timeperiods (tp_id) + ON DELETE CASCADE, + FOREIGN KEY (contact_id) REFERENCES cfg_contacts (contact_id) + ON DELETE CASCADE, + FOREIGN KEY (host_id) REFERENCES cfg_hosts (host_id) + ON DELETE CASCADE, + FOREIGN KEY (service_id) REFERENCES cfg_services (service_id) + ON DELETE CASCADE +) ENGINE=InnoDB CHARACTER SET utf8; diff --git a/centreon-broker/notification/src/action.cc b/centreon-broker/notification/src/action.cc new file mode 100644 index 00000000000..62e1b0a6341 --- /dev/null +++ b/centreon-broker/notification/src/action.cc @@ -0,0 +1,468 @@ +/* +** Copyright 2009-2015 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/action.hh" +#include "com/centreon/broker/notification/process_manager.hh" +#include "com/centreon/broker/notification/state.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; +using namespace com::centreon::broker::time; + +/** + * Default constructor. + */ +action::action() + : _act(action::unknown), + _forwarded_action(action::unknown), + _id(), + _notification_rule_id(0), + _notification_number(0), + _at(0), + _first_time_of_notification(0) {} + +/** + * Copy constructor. + * + * @param[in] obj The object to be copied. + */ +action::action(action const& obj) { + action::operator=(obj); +} + +/** + * Assignment operator. + * + * @param[in] obj The object to be copied. + * + * @return A reference to this object. + */ +action& action::operator=(action const& obj) { + if (this != &obj) { + _act = obj._act; + _id = obj._id; + _notification_rule_id = obj._notification_rule_id; + _notification_number = obj._notification_number; + _at = obj._at; + _forwarded_action = obj._forwarded_action; + _first_time_of_notification = obj._first_time_of_notification; + } + return (*this); +} + +/** + * Equality operator. + * + * @param[in] obj The object from which to test equality. + * + * @return True if the two objects are equal. + */ +bool action::operator==(action const& obj) const { + return (_act == obj._act && _id == obj._id && + _notification_rule_id == obj._notification_rule_id && + _notification_number == obj._notification_number && _at == obj._at && + _forwarded_action == obj._forwarded_action && + _first_time_of_notification == obj._first_time_of_notification); +} + +/** + * Comparison operator. + * + * @param[in] obj The compared object. + * + * @return True if this object is less than the other. + */ +bool action::operator<(action const& obj) const { + if (_act != obj._act) + return (_act < obj._act); + else if (_id != obj._id) + return (_id < obj._id); + else if (_notification_rule_id != obj._notification_rule_id) + return (_notification_rule_id < obj._notification_rule_id); + else if (_notification_number != obj._notification_number) + return (_notification_number < obj._notification_number); + else if (_at != obj._at) + return (_at < obj._at); + else if (_first_time_of_notification != obj._first_time_of_notification) + return (_first_time_of_notification < obj._first_time_of_notification); + else + return (_forwarded_action < obj._forwarded_action); +} + +/** + * Get the type of this action. + * + * @return[in] The type of this action. + */ +action::action_type action::get_type() const throw() { + return (_act); +} + +/** + * Set the type of this action. + * + * @param[in] type The type of this action. + */ +void action::set_type(action_type type) throw() { + _act = type; +} + +/** + * Get the forwarded type. + * + * @return The forwarded type. + */ +action::action_type action::get_forwarded_type() const throw() { + return (_forwarded_action); +} + +/** + * Set the forwarded type. + * + * @param[in] type The forwarded type. + */ +void action::set_forwarded_type(action_type type) throw() { + _forwarded_action = type; +} + +/** + * Get the node id associated with this action. + * + * @return The node id associated with this action. + */ +node_id action::get_node_id() const throw() { + return (_id); +} + +/** + * Set the node id associated with this actions. + * + * @param[in] id The node id associated with this action. + */ +void action::set_node_id(objects::node_id id) throw() { + _id = id; +} + +/** + * Get the notification rule ID. + * + * @return Notification rule ID. + */ +uint32_t action::get_notification_rule_id() const throw() { + return (_notification_rule_id); +} + +/** + * Set the notification rule ID. + * + * @param[in] id Notification rule ID. + */ +void action::set_notification_rule_id(uint32_t id) throw() { + _notification_rule_id = id; + return; +} + +/** + * Get the notification number. + * + * @return Current notification number. + */ +uint32_t action::get_notification_number() const throw() { + return (_notification_number); +} + +/** + * Set the notification number. + * + * @param[in] num Notification number. + */ +void action::set_notification_number(uint32_t num) throw() { + _notification_number = num; + return; +} + +/** + * Get the scheduled time of this action. + * + * @return The scheduled time of this action. + */ +time_t action::get_at() const throw() { + return (_at); +} + +/** + * Set the scheduled time of this action. + * + * @param[in] at The scheduled time of this action. + */ +void action::set_at(time_t at) throw() { + _at = at; +} + +/** + * Get the first notification time. + * + * @return The first notification time. + */ +time_t action::get_first_notification_time() const throw() { + return (_first_time_of_notification); +} + +/** + * Set the first notification time. + * + * @param[in] t The new first notification time. + */ +void action::set_first_notification_time(time_t t) throw() { + _first_time_of_notification = t; +} + +/** + * @brief Process the action. + * + * What is done changes based on the type of this notification. + * + * @param[in] state The notification state of the engine. + * @param[in] cache The data cache of the module. + * @param[out] spawned_actions The actions to add to the queue after the + * processing. + * + */ +void action::process_action( + state& st, + node_cache& cache, + std::vector >& spawned_actions) const { + if (_act == unknown || _id == node_id()) + return; + + if (_act == notification_processing) + _spawn_notification_attempts(st, spawned_actions); + else + _process_notification(st, cache, spawned_actions); +} + +/** + * @brief Spawn the notification attempts from a notification processing. + * + * A notification processing spawn one notification attempt for each rule + * associated to a particular node. + * + * @param[in] st The notification state of the engine. + * @param[out] spawned_actions The actions to add to the queue after the + * processing. + */ +void action::_spawn_notification_attempts( + state& st, + std::vector >& spawned_actions) const { + log_v2::notification()->debug( + "notification: spawning notification action for node ({}, {})", + _id.get_host_id(), _id.get_service_id()); + + // Spawn an action for each rules. + QList rules = st.get_notification_rules_by_node(_id); + for (QList::iterator it(rules.begin()), + end(rules.end()); + it != end; ++it) { + // Build action (viability checks will be made later. + action a; + a.set_node_id(_id); + a.set_type(_forwarded_action); + a.set_notification_rule_id((*it)->get_id()); + a.set_notification_number(1); + + // Choose running time. + time_t at; + timeperiod::ptr tp = st.get_timeperiod_by_id((*it)->get_timeperiod_id()); + if (tp) + at = tp->get_next_valid(::time(NULL)); + else + at = ::time(NULL); + spawned_actions.push_back(std::make_pair(at, a)); + spawned_actions.back().second.set_first_notification_time(at); + } + return; +} + +/** + * Process a notification attempt. + * + * @param[in] st The notification state of the engine. + * @param[in] cache The data cache of the module. + * @param[out] spawned_actions The action to add to the queue after the + * processing. + */ +void action::_process_notification( + state& st, + node_cache& cache, + std::vector >& spawned_actions) const { + log_v2::notification()->debug( + "notification: processing action for rule {} of node ({}, {})", + _notification_rule_id, _id.get_host_id(), _id.get_service_id()); + + // Check action viability. + log_v2::notification()->debug( + "notification: checking action viability for node ({}, {})", + _id.get_host_id(), _id.get_service_id()); + + // Check the node's existence. + node::ptr n(st.get_node_by_id(_id)); + if (!n) { + log_v2::notification()->debug( + "notification: node ({}, {}) was not declared, notification attempt is " + "not viable", + _id.get_host_id(), _id.get_service_id()); + return; + } + + // Get all the necessary data. + notification_rule::ptr rule = + st.get_notification_rule_by_id(_notification_rule_id); + if (!rule) { + log_v2::notification()->error( + "notification: aborting notification attempt on node ({}, {}): rule {} " + "does not exist", + _id.get_host_id(), _id.get_service_id(), _notification_rule_id); + return; + } + + timeperiod::ptr tp = st.get_timeperiod_by_id(rule->get_timeperiod_id()); + if (!tp) + log_v2::notification()->error( + "notification: could not find timeperiod {} during notification " + "attempt on node ({}, {}), so any time will be valid", + rule->get_timeperiod_id(), _id.get_host_id(), _id.get_service_id()); + + notification_method::ptr method = + st.get_notification_method_by_id(rule->get_method_id()); + if (!method) { + log_v2::notification()->error( + "notification: aborting notification attempt on node ({}, {}): method " + "{} does not exist", + _id.get_host_id(), _id.get_service_id(), rule->get_method_id()); + return; + } + + contact::ptr cnt = st.get_contact_by_id(rule->get_contact_id()); + if (!cnt) { + log_v2::notification()->error( + "notification: aborting notification attempt on node ({}, {}): contact " + "{} does not exist", + _id.get_host_id(), _id.get_service_id(), rule->get_contact_id()); + return; + } + + command::ptr cmd = st.get_command_by_id(method->get_command_id()); + if (!cmd) { + log_v2::notification()->error( + "notification: aborting notification attempt on node ({}, {}): command " + "{} does not exist", + _id.get_host_id(), _id.get_service_id(), method->get_command_id()); + return; + } + + // Check the existence of correlated parent. + if (n->has_parent() && !method->should_be_notified_when_correlated()) { + log_v2::notification()->debug( + "notification: node ({}, {}) has parent issue, notification attempt is " + "not viable", + _id.get_host_id(), _id.get_service_id()); + return; + } + + // Check if the state is valid. + if (!method->should_be_notified_for(n->get_hard_state(), + n->get_node_id().is_service())) { + log_v2::notification()->debug( + "notification: node ({}, {}) should not be notified for state {} " + "according to method {}", + _id.get_host_id(), _id.get_service_id(), + static_cast(n->get_hard_state()), rule->get_method_id()); + return; + } + + // Check if the notification type is valid. + if (!method->should_be_notified_for(_act)) { + log_v2::notification()->debug( + "notification: node ({}, {}) should not be notified for action type {} " + "according to method {}", + _id.get_host_id(), _id.get_service_id(), static_cast(_act), + rule->get_method_id()); + return; + } + + // See if the timeperiod is valid. + time_t now = ::time(NULL); + if (tp && !tp->is_valid(now)) { + log_v2::notification()->debug( + "notification: notification attempt on node ({}, {}) is not in a valid " + "timeperiod, rescheduling it at the next valid time", + _id.get_host_id(), _id.get_service_id()); + spawned_actions.push_back(std::make_pair(tp->get_next_valid(now), *this)); + return; + } + + bool should_send_the_notification = true; + action next = *this; + next.set_notification_number(_notification_number + 1); + + // See if the node is in downtime. + if (_act == notification_attempt && cache.node_in_downtime(_id) == true) { + log_v2::notification()->debug( + "notification: node ({}, {}) is in downtime, notification won't be " + "sent", + _id.get_host_id(), _id.get_service_id()); + should_send_the_notification = false; + } + + // See if the node has been acknowledged. + if (_act == notification_attempt && cache.node_acknowledged(_id) == true) { + log_v2::notification()->debug( + "notification: node ({},{}) is acknowledged, notification won't be " + "sent", + _id.get_host_id(), _id.get_service_id()); + should_send_the_notification = false; + } + + // See if this notification time is between the start and end. + if (now < (_first_time_of_notification + method->get_start()) || + (now >= (_first_time_of_notification + method->get_end()) && + method->get_end())) { + log_v2::notification()->debug( + "notification: notification time of node ({}, {}) is '{}' and not in " + "the method's valid range ([{}-{}])", + _id.get_host_id(), _id.get_service_id(), now, + _first_time_of_notification + method->get_start(), + _first_time_of_notification + method->get_end()); + should_send_the_notification = false; + } + + // Send the notification. + if (should_send_the_notification) { + std::string resolved_command = cmd->resolve(cnt, n, cache, st, *this); + log_v2::notification()->info( + "notification: launching notification command on node ({}, {}): {}", + _id.get_host_id(), _id.get_service_id(), resolved_command); + process_manager& manager = process_manager::instance(); + manager.create_process(resolved_command); + } + + // Create the next notification. + if (_act == notification_attempt) + spawned_actions.push_back( + std::make_pair(now + method->get_interval(), next)); +} diff --git a/centreon-broker/notification/src/builders/command_by_id_builder.cc b/centreon-broker/notification/src/builders/command_by_id_builder.cc new file mode 100644 index 00000000000..31b972ec8a0 --- /dev/null +++ b/centreon-broker/notification/src/builders/command_by_id_builder.cc @@ -0,0 +1,42 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/command_by_id_builder.hh" +#include "com/centreon/broker/notification/utilities/qhash_func.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Construct the object. + * + * @param[in,out] table The table to fill. + */ +command_by_id_builder::command_by_id_builder( + QHash& table) + : _table(table) {} + +/** + * Add a command to the builder. + * + * @param[in] id The id of the command. + * @param[in] com The command. + */ +void command_by_id_builder::add_command(uint32_t id, command::ptr com) { + _table[id] = com; +} diff --git a/centreon-broker/notification/src/builders/composed_command_builder.cc b/centreon-broker/notification/src/builders/composed_command_builder.cc new file mode 100644 index 00000000000..a5694594d02 --- /dev/null +++ b/centreon-broker/notification/src/builders/composed_command_builder.cc @@ -0,0 +1,39 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/composed_command_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor + */ +composed_command_builder::composed_command_builder() {} + +/** + * Add a command to the builder. + * + * @param[in] id The id of the command. + * @param[in] com The command. + */ +void composed_command_builder::add_command(uint32_t id, command::ptr com) { + for (composed_builder::iterator it(begin()), it_end(end()); + it != it_end; ++it) + (*it)->add_command(id, com); +} diff --git a/centreon-broker/notification/src/builders/composed_contact_builder.cc b/centreon-broker/notification/src/builders/composed_contact_builder.cc new file mode 100644 index 00000000000..a55feeb0c93 --- /dev/null +++ b/centreon-broker/notification/src/builders/composed_contact_builder.cc @@ -0,0 +1,54 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/composed_contact_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor + */ +composed_contact_builder::composed_contact_builder() {} + +/** + * Add a contact to the builder. + * + * @param[in] id The id of the contact. + * @param[in] con The contact. + */ +void composed_contact_builder::add_contact(uint32_t id, contact::ptr con) { + for (composed_builder::iterator it(begin()), end_it(end()); + it != end_it; ++it) + (*it)->add_contact(id, con); +} + +/** + * Add a contact info to the builder. + * + * @param[in] contact_id The id of the contact. + * @param[in] key The key of the contact info. + * @param[in] value The value of the contact info. + */ +void composed_contact_builder::add_contact_info(uint32_t contact_id, + std::string const& key, + std::string const& value) { + for (composed_builder::iterator it(begin()), end_it(end()); + it != end_it; ++it) + (*it)->add_contact_info(contact_id, key, value); +} diff --git a/centreon-broker/notification/src/builders/composed_dependency_builder.cc b/centreon-broker/notification/src/builders/composed_dependency_builder.cc new file mode 100644 index 00000000000..4a890925029 --- /dev/null +++ b/centreon-broker/notification/src/builders/composed_dependency_builder.cc @@ -0,0 +1,71 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/composed_dependency_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor + */ +composed_dependency_builder::composed_dependency_builder() {} + +void composed_dependency_builder::add_dependency(uint32_t id, + dependency::ptr d) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->add_dependency(id, d); +} + +void composed_dependency_builder::dependency_node_id_parent_relation( + uint32_t dep_id, + node_id id) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->dependency_node_id_parent_relation(dep_id, id); +} + +void composed_dependency_builder::dependency_node_id_child_relation( + uint32_t dep_id, + node_id id) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->dependency_node_id_child_relation(dep_id, id); +} + +void composed_dependency_builder::set_notification_failure_options( + uint32_t dep_id, + std::string const& line) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->set_notification_failure_options(dep_id, line); +} + +void composed_dependency_builder::set_execution_failure_options( + uint32_t dep_id, + std::string const& line) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->set_execution_failure_options(dep_id, line); +} diff --git a/centreon-broker/notification/src/builders/composed_node_builder.cc b/centreon-broker/notification/src/builders/composed_node_builder.cc new file mode 100644 index 00000000000..f7371b260b8 --- /dev/null +++ b/centreon-broker/notification/src/builders/composed_node_builder.cc @@ -0,0 +1,38 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/composed_node_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor + */ +composed_node_builder::composed_node_builder() {} + +/** + * Add a node to the builder. + * + * @param[in] node The node. + */ +void composed_node_builder::add_node(node::ptr node) { + for (composed_builder::iterator it(begin()), it_end(end()); + it != it_end; ++it) + (*it)->add_node(node); +} diff --git a/centreon-broker/notification/src/builders/composed_notification_method_builder.cc b/centreon-broker/notification/src/builders/composed_notification_method_builder.cc new file mode 100644 index 00000000000..a4fe5e89be9 --- /dev/null +++ b/centreon-broker/notification/src/builders/composed_notification_method_builder.cc @@ -0,0 +1,42 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/composed_notification_method_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor + */ +composed_notification_method_builder::composed_notification_method_builder() {} + +/** + * Add a notification method to the builder. + * + * @param[in] method_id The id of the notification method. + * @param[in] method The method. + */ +void composed_notification_method_builder::add_notification_method( + uint32_t method_id, + notification_method::ptr method) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->add_notification_method(method_id, method); +} diff --git a/centreon-broker/notification/src/builders/composed_notification_rule_builder.cc b/centreon-broker/notification/src/builders/composed_notification_rule_builder.cc new file mode 100644 index 00000000000..3b92a16a142 --- /dev/null +++ b/centreon-broker/notification/src/builders/composed_notification_rule_builder.cc @@ -0,0 +1,42 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/composed_notification_rule_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor + */ +composed_notification_rule_builder::composed_notification_rule_builder() {} + +/** + * Add a notification rule to the builder. + * + * @param[in] rule_id The id of the notification rule. + * @param[in] rule The rule. + */ +void composed_notification_rule_builder::add_rule( + uint32_t rule_id, + objects::notification_rule::ptr rule) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->add_rule(rule_id, rule); +} diff --git a/centreon-broker/notification/src/builders/composed_timeperiod_builder.cc b/centreon-broker/notification/src/builders/composed_timeperiod_builder.cc new file mode 100644 index 00000000000..f35b0eaf94f --- /dev/null +++ b/centreon-broker/notification/src/builders/composed_timeperiod_builder.cc @@ -0,0 +1,88 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/composed_timeperiod_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::time; + +/** + * Default constructor + */ +composed_timeperiod_builder::composed_timeperiod_builder() {} + +/** + * Add a timeperiod to the builder. + * + * @param[in] id The id of the timeperiod. + * @param[in] tperiod The timeperiod. + */ +void composed_timeperiod_builder::add_timeperiod(uint32_t id, + timeperiod::ptr tperiod) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->add_timeperiod(id, tperiod); +} + +/** + * Add a timeperiod exception to the builder. + * + * @param[in] timeperiod_id The id of the timeperiod. + * @param[in] days The days in the exception. + * @param[in] timerange The timerange of the exception. + */ +void composed_timeperiod_builder::add_timeperiod_exception( + uint32_t timeperiod_id, + std::string const& days, + std::string const& timerange) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->add_timeperiod_exception(timeperiod_id, days, timerange); +} + +/** + * Add a timeperiod exclude relation to the builder. + * + * @param[in] timeperiod_id The id of the timeperiod. + * @param[in] exclude_id The id of the timeperiod excluded. + */ +void composed_timeperiod_builder::add_timeperiod_exclude_relation( + uint32_t timeperiod_id, + uint32_t exclude_id) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->add_timeperiod_exclude_relation(timeperiod_id, exclude_id); +} + +/** + * Add a timeperiod include relation to the builder. + * + * @param[in] timeperiod_id The id of the timeperiod. + * @param[in] include_id The id of the timeperiod included. + */ +void composed_timeperiod_builder::add_timeperiod_include_relation( + uint32_t timeperiod_id, + uint32_t include_id) { + for (composed_builder::iterator it(begin()), + it_end(end()); + it != it_end; ++it) + (*it)->add_timeperiod_include_relation(timeperiod_id, include_id); +} diff --git a/centreon-broker/notification/src/builders/contact_by_id_builder.cc b/centreon-broker/notification/src/builders/contact_by_id_builder.cc new file mode 100644 index 00000000000..93bcf6e7cfc --- /dev/null +++ b/centreon-broker/notification/src/builders/contact_by_id_builder.cc @@ -0,0 +1,57 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/contact_by_id_builder.hh" +#include "com/centreon/broker/notification/utilities/qhash_func.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + * + * @param[in] table The table to fill. + */ +contact_by_id_builder::contact_by_id_builder( + QHash& table, + QHash >& contact_infos) + : _table(table), _contact_infos(contact_infos) {} + +/** + * Add a contact to the builder. + * + * @param[in] id The id of the contact. + * @param[in] con The contact to add. + */ +void contact_by_id_builder::add_contact(uint32_t id, + objects::contact::ptr con) { + _table[id] = con; +} + +/** + * Add a contact info to the builder. + * + * @param[in] contact_id The id of the contact. + * @param[in] key The key of the contact info. + * @param[in] value The value of the contact info. + */ +void contact_by_id_builder::add_contact_info(uint32_t contact_id, + std::string const& key, + std::string const& value) { + _contact_infos[contact_id].insert(key, value); +} diff --git a/centreon-broker/notification/src/builders/dependency_by_node_id_builder.cc b/centreon-broker/notification/src/builders/dependency_by_node_id_builder.cc new file mode 100644 index 00000000000..3f33a1ca4ff --- /dev/null +++ b/centreon-broker/notification/src/builders/dependency_by_node_id_builder.cc @@ -0,0 +1,52 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/dependency_by_node_id_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Construct the object. + * + * @param[in,out] by_child_id The table of dependency by child id to fill. + * @param[in,out] by_parent_id The table of dependency by parent id to fill. + */ +dependency_by_node_id_builder::dependency_by_node_id_builder( + QMultiHash& by_child_id, + QMultiHash& by_parent_id) + : _table_child_id(by_child_id), _table_parent_id(by_parent_id) {} + +void dependency_by_node_id_builder::add_dependency(uint32_t id, + dependency::ptr d) { + _cache[id] = d; +} + +void dependency_by_node_id_builder::dependency_node_id_parent_relation( + uint32_t dep_id, + node_id id) { + if (_cache.contains(dep_id)) + _table_parent_id.insert(id, _cache[dep_id]); +} + +void dependency_by_node_id_builder::dependency_node_id_child_relation( + uint32_t dep_id, + node_id id) { + if (_cache.contains(dep_id)) + _table_child_id.insert(id, _cache[dep_id]); +} diff --git a/centreon-broker/notification/src/builders/global_macro_builder.cc b/centreon-broker/notification/src/builders/global_macro_builder.cc new file mode 100644 index 00000000000..9845a1b2acf --- /dev/null +++ b/centreon-broker/notification/src/builders/global_macro_builder.cc @@ -0,0 +1,58 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/global_macro_builder.hh" +#include "com/centreon/broker/notification/utilities/qhash_func.hh" + +using namespace com::centreon::broker::notification; + +global_macro_builder::global_macro_builder( + QHash& global_macros, + int& date_format) + : _global_macros(global_macros), _date_format(date_format) {} + +/** + * Add a macro to the builder. + * + * @param[in] macro_name The macro name. + * @param[in] macro_value The macro value. + */ +void global_macro_builder::add_global_macro(std::string const& macro_name, + std::string const& macro_value) { + _global_macros.insert(macro_name, macro_value); +} + +/** + * Add a date format to the builder. + * + * @param[in] format The date format to add. + */ +void global_macro_builder::add_date_format(int format) { + _date_format = format; +} + +/** + * Add a resource macro to the builder + * + * @param[in] macro_name The macro name. + * @param[in] macro_value The macro value. + */ +void global_macro_builder::add_resource_macro(std::string const& macro_name, + std::string const& macro_value) { + _global_macros.insert(macro_name, macro_value); +} diff --git a/centreon-broker/notification/src/builders/node_by_node_id_builder.cc b/centreon-broker/notification/src/builders/node_by_node_id_builder.cc new file mode 100644 index 00000000000..3e65b8a19e0 --- /dev/null +++ b/centreon-broker/notification/src/builders/node_by_node_id_builder.cc @@ -0,0 +1,40 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/node_by_node_id_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Construct the object. + * + * @param[in,out] set The set to fill. + */ +node_by_node_id_builder::node_by_node_id_builder( + QHash& map) + : _map(map) {} + +/** + * Add a node to the builder. + * + * @param[in] node The node. + */ +void node_by_node_id_builder::add_node(node::ptr node) { + _map.insert(node->get_node_id(), node); +} diff --git a/centreon-broker/notification/src/builders/node_set_builder.cc b/centreon-broker/notification/src/builders/node_set_builder.cc new file mode 100644 index 00000000000..465e431084c --- /dev/null +++ b/centreon-broker/notification/src/builders/node_set_builder.cc @@ -0,0 +1,38 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/node_set_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Construct the object. + * + * @param[in,out] set The set to fill. + */ +node_set_builder::node_set_builder(QSet& set) : _set(set) {} + +/** + * Add a node to the builder. + * + * @param[in] node The node. + */ +void node_set_builder::add_node(node::ptr node) { + _set.insert(node->get_node_id()); +} diff --git a/centreon-broker/notification/src/builders/notification_method_by_id_builder.cc b/centreon-broker/notification/src/builders/notification_method_by_id_builder.cc new file mode 100644 index 00000000000..d1c1c16735c --- /dev/null +++ b/centreon-broker/notification/src/builders/notification_method_by_id_builder.cc @@ -0,0 +1,43 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/notification_method_by_id_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Constructor. + * + * @param[in] map The map to fill. + */ +notification_method_by_id_builder::notification_method_by_id_builder( + QHash& map) + : _map(map) {} + +/** + * Add a notification method to the builder. + * + * @param[in] method_id The id of the notification method. + * @param[in] method The method. + */ +void notification_method_by_id_builder::add_notification_method( + uint32_t method_id, + notification_method::ptr method) { + _map[method_id] = method; +} diff --git a/centreon-broker/notification/src/builders/notification_rule_by_id_builder.cc b/centreon-broker/notification/src/builders/notification_rule_by_id_builder.cc new file mode 100644 index 00000000000..6a93bd859e3 --- /dev/null +++ b/centreon-broker/notification/src/builders/notification_rule_by_id_builder.cc @@ -0,0 +1,43 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/notification_rule_by_id_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + * + * @param[in] table The table to fill. + */ +notification_rule_by_id_builder::notification_rule_by_id_builder( + QHash& table) + : _table(table) {} + +/** + * Add a rule to the builder. + * + * @param[in] id The id of the rule. + * @param[in] con The rule to add. + */ +void notification_rule_by_id_builder::add_rule( + uint32_t id, + objects::notification_rule::ptr con) { + _table[id] = con; +} diff --git a/centreon-broker/notification/src/builders/notification_rule_by_node_builder.cc b/centreon-broker/notification/src/builders/notification_rule_by_node_builder.cc new file mode 100644 index 00000000000..ba80b37dcd2 --- /dev/null +++ b/centreon-broker/notification/src/builders/notification_rule_by_node_builder.cc @@ -0,0 +1,44 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/notification_rule_by_node_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Constructor. + * + * @param[in] map The map to fill. + */ +notification_rule_by_node_builder::notification_rule_by_node_builder( + QMultiHash& map) + : _map(map) {} + +/** + * Add a rule to the builder. + * + * @param[in] id The id of the rule. + * @param[in] con The rule to add. + */ +void notification_rule_by_node_builder::add_rule( + uint32_t rule_id, + objects::notification_rule::ptr rule) { + (void)rule_id; + _map.insert(rule->get_node_id(), rule); +} diff --git a/centreon-broker/notification/src/builders/timeperiod_by_id_builder.cc b/centreon-broker/notification/src/builders/timeperiod_by_id_builder.cc new file mode 100644 index 00000000000..9c374742df6 --- /dev/null +++ b/centreon-broker/notification/src/builders/timeperiod_by_id_builder.cc @@ -0,0 +1,42 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/timeperiod_by_id_builder.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::time; + +/** + * Default constructor. + * + * @param[in] table The table to fill. + */ +timeperiod_by_id_builder::timeperiod_by_id_builder( + QHash& table) + : _table(table) {} + +/** + * Add a timeperiod to the builder. + * + * @param[in] id The id of the timeperiod. + * @param[in] con The timeperiod to add. + */ +void timeperiod_by_id_builder::add_timeperiod(uint32_t id, + timeperiod::ptr con) { + _table[id] = con; +} diff --git a/centreon-broker/notification/src/builders/timeperiod_linker.cc b/centreon-broker/notification/src/builders/timeperiod_linker.cc new file mode 100644 index 00000000000..32fb0a75252 --- /dev/null +++ b/centreon-broker/notification/src/builders/timeperiod_linker.cc @@ -0,0 +1,98 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/builders/timeperiod_linker.hh" +#include "com/centreon/broker/exceptions/msg.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::time; + +/** + * Default constructor. + */ +timeperiod_linker::timeperiod_linker() {} + +/** + * Add a timeperiod to the builder. + * + * @param[in] id The id of the timeperiod. + * @param[in] con The timeperiod to add. + */ +void timeperiod_linker::add_timeperiod(uint32_t id, timeperiod::ptr con) { + _table[id] = con; +} + +/** + * Add a timeperiod exception to the builder. + * + * @param[in] timeperiod_id The id of the timeperiod. + * @param[in] days The days in the exception. + * @param[in] timerange The timerange of the exception. + */ +void timeperiod_linker::add_timeperiod_exception(uint32_t timeperiod_id, + std::string const& days, + std::string const& timerange) { + QHash::iterator found = + _table.find(timeperiod_id); + if (found == _table.end()) + throw(exceptions::msg() << "timeperiod_linker: couldn't find timeperiod '" + << timeperiod_id << "'' for exception"); + (*found)->add_exception(days, timerange); +} + +/** + * Add a timeperiod exclude relation to the builder. + * + * @param[in] timeperiod_id The id of the timeperiod. + * @param[in] exclude_id The id of the timeperiod excluded. + */ +void timeperiod_linker::add_timeperiod_exclude_relation(uint32_t timeperiod_id, + uint32_t exclude_id) { + QHash::iterator found = + _table.find(timeperiod_id); + QHash::iterator excluded = + _table.find(exclude_id); + if (found == _table.end()) + throw(exceptions::msg() << "timeperiod_linker: couldn't find timeperiod '" + << timeperiod_id << "'' for exclusion"); + if (excluded == _table.end()) + throw(exceptions::msg() << "timeperiod_linker: couldn't find timeperiod '" + << exclude_id << "'' for excluded timeperiod"); + (*found)->add_excluded(*excluded); +} + +/** + * Add a timeperiod include relation to the builder. + * + * @param[in] timeperiod_id The id of the timeperiod. + * @param[in] include_id The id of the timeperiod included. + */ +void timeperiod_linker::add_timeperiod_include_relation(uint32_t timeperiod_id, + uint32_t include_id) { + QHash::iterator found = + _table.find(timeperiod_id); + QHash::iterator included = + _table.find(include_id); + if (found == _table.end()) + throw(exceptions::msg() << "timeperiod_linker: couldn't find timeperiod '" + << timeperiod_id << "'' for inclusion"); + if (included == _table.end()) + throw(exceptions::msg() << "timeperiod_linker: couldn't find timeperiod '" + << include_id << "'' for included timeperiod"); + (*found)->add_excluded(*included); +} diff --git a/centreon-broker/notification/src/connector.cc b/centreon-broker/notification/src/connector.cc new file mode 100644 index 00000000000..1e043212e09 --- /dev/null +++ b/centreon-broker/notification/src/connector.cc @@ -0,0 +1,119 @@ +/* +** 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/notification/connector.hh" +#include "com/centreon/broker/notification/stream.hh" + +using namespace com::centreon::broker; +using namespace com::centreon::broker::notification; + +/************************************** + * * + * Public Methods * + * * + **************************************/ + +/** + * Constructor. + */ +connector::connector(std::shared_ptr cache) + : io::endpoint(false), _cache(cache), _node_cache(_cache) {} + +/** + * Copy constructor. + * + * @param[in] c Object to copy. + */ +connector::connector(connector const& c) + : io::endpoint(c), + _check_replication(c._check_replication), + _centreon_db(c._centreon_db), + _host(c._host), + _password(c._password), + _port(c._port), + _type(c._type), + _user(c._user), + _cache(c._cache), + _node_cache(c._node_cache) {} + +/** + * Destructor. + */ +connector::~connector() {} + +/** + * Assignment operator. + * + * @param[in] c Object to copy. + * + * @return This object. + */ +connector& connector::operator=(connector const& c) { + if (this != &c) { + io::endpoint::operator=(c); + _check_replication = c._check_replication; + _centreon_db = c._centreon_db; + _host = c._host; + _password = c._password; + _port = c._port; + _type = c._type; + _user = c._user; + _cache = c._cache; + _node_cache = c._node_cache; + } + return (*this); +} + +/** + * Set connection parameters. + * + * @param[in] type Database type. + * @param[in] host Database host. + * @param[in] port Database port. + * @param[in] user User. + * @param[in] password Password. + * @param[in] centreon_db Database name. + * @param[in] check_replication true to check replication status. + */ +void connector::connect_to(std::string const& type, + std::string const& host, + unsigned short port, + std::string const& user, + std::string const& password, + std::string const& centreon_db, + bool check_replication) { + _check_replication = check_replication; + _centreon_db = centreon_db; + _host = host; + _password = password; + _port = port; + _type = type; + _user = user; + return; +} + +/** + * Connect to a notification cache DB and return a notification stream. + * + * @return Notification stream object. + */ +std::shared_ptr connector::open() { + return (std::shared_ptr( + new stream(_type, _host, _port, _user, _password, _centreon_db, + _check_replication, _node_cache))); +} diff --git a/centreon-broker/notification/src/factory.cc b/centreon-broker/notification/src/factory.cc new file mode 100644 index 00000000000..ef5de6abde8 --- /dev/null +++ b/centreon-broker/notification/src/factory.cc @@ -0,0 +1,121 @@ +/* +** Copyright 2011-2016 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/factory.hh" +#include +#include "com/centreon/broker/config/parser.hh" +#include "com/centreon/broker/notification/connector.hh" +#include "com/centreon/exceptions/msg_fmt.hh" + +using namespace com::centreon::broker; +using namespace com::centreon::broker::notification; +using namespace com::centreon::exceptions; + +/************************************** + * * + * Local Objects * + * * + **************************************/ + +/** + * Find a parameter in configuration. + * + * @param[in] cfg Configuration object. + * @param[in] key Property to get. + * + * @return Property value. + */ +static std::string const& find_param(config::endpoint const& cfg, + std::string const& key) { + std::map::const_iterator it{cfg.params.find(key)}; + if (cfg.params.end() == it) + throw msg_fmt("notification: no '{}' defined for endpoint '{}'", key, + cfg.name); + return it->second; +} + +/************************************** + * * + * Public Methods * + * * + **************************************/ + +/** + * Check if an endpoint match a configuration. + * + * @param[in] cfg Endpoint configuration. + * + * @return True if the endpoint match the configuration. + */ +bool factory::has_endpoint(config::endpoint& cfg) { + bool is_notif(!cfg.type.compare("notification", Qt::CaseInsensitive)); + if (is_notif) { + cfg.params["cache"] = "yes"; + cfg.cache_enabled = true; + } + return (is_notif); +} + +/** + * Create an endpoint. + * + * @param[in] cfg Endpoint configuration. + * @param[out] is_acceptor Will be set to false. + * @param[in] cache The persistent cache for this module. + * + * @return New endpoint. + */ +io::endpoint* factory::new_endpoint( + config::endpoint& cfg, + bool& is_acceptor, + std::shared_ptr cache) const { + // Find DB type. + std::string type(find_param(cfg, "db_type")); + + // Find DB host. + std::string host(find_param(cfg, "db_host")); + + // Find DB port. + unsigned short port{ + static_cast(std::stol(find_param(cfg, "db_port")))}; + + // Find DB user. + std::string user{find_param(cfg, "db_user")}; + + // Find DB password. + std::string password{find_param(cfg, "db_password")}; + + // Find DB name. + std::string db_name{find_param(cfg, "db_name")}; + + // Check replication status ? + bool check_replication{true}; + { + std::map::const_iterator it{ + cfg.params.find("check_replication")}; + if (it != cfg.params.end()) + check_replication = config::parser::parse_boolean(it->second); + } + + // Connector. + std::unique_ptr c{ + new notification::connector(cache)}; + c->connect_to(type, host, port, user, password, db_name, check_replication); + is_acceptor = false; + return c.release(); +} diff --git a/centreon-broker/notification/src/loaders/command_loader.cc b/centreon-broker/notification/src/loaders/command_loader.cc new file mode 100644 index 00000000000..e5ecd2134e7 --- /dev/null +++ b/centreon-broker/notification/src/loaders/command_loader.cc @@ -0,0 +1,66 @@ +/* +** 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/notification/loaders/command_loader.hh" +#include "com/centreon/broker/exceptions/msg.hh" +#include "com/centreon/broker/notification/objects/command.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +command_loader::command_loader() {} + +/** + * Load the commands from the database. + * + * @param[in] ms An open connection to the database. + * @param[out] output A command builder object to register the commands. + */ +void command_loader::load(mysql* ms, command_builder* output) { + // If we don't have any db or output, don't do anything. + if (!ms || !output) + return; + log_v2::notification()->debug( + "notification: loading commands from the database"); + + // Performance improvement, as we never go back. + // query.setForwardOnly(true); + + // Load the commands + std::promise promise; + ms->run_query_and_get_result( + "SELECT command_id, connector_id, command_name, command_line," + " command_type, enable_shell" + " FROM cfg_commands", + &promise); + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) { + uint32_t id = res.value_as_u32(0); + std::string base_command = res.value_as_str(3); + command::ptr com(new command(base_command)); + com->set_name(res.value_as_str(2)); + com->set_enable_shell(res.value_as_bool(5)); + + output->add_command(id, com); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load commands from database: " << e.what(); + } +} diff --git a/centreon-broker/notification/src/loaders/contact_loader.cc b/centreon-broker/notification/src/loaders/contact_loader.cc new file mode 100644 index 00000000000..8addcef3bf6 --- /dev/null +++ b/centreon-broker/notification/src/loaders/contact_loader.cc @@ -0,0 +1,81 @@ +/* +** 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/notification/loaders/contact_loader.hh" +#include +#include +#include "com/centreon/broker/exceptions/msg.hh" +#include "com/centreon/broker/notification/objects/contact.hh" + +using namespace com::centreon::broker; +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +contact_loader::contact_loader() {} + +/** + * Load the contacts from the database. + * + * @param[in] db An open connection to the database. + * @param[out] output A contact builder object to register the contacts. + */ +void contact_loader::load(mysql* ms, contact_builder* output) { + // If we don't have any db or output, don't do anything. + if (!ms || !output) + return; + log_v2::notification()->debug( + "notification: loading contacts from the database"); + + // Load the contacts. + std::promise promise; + ms->run_query_and_get_result( + "SELECT contact_id, description FROM cfg_contacts", &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) { + contact::ptr cont(new contact); + uint32_t id = res.value_as_u32(0); + cont->set_id(id); + cont->set_description(res.value_as_str(1)); + output->add_contact(id, cont); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load contacts from database: " << e.what(); + } + + // Load the infos of this contact. + promise = std::promise(); + ms->run_query_and_get_result( + "SELECT contact_id, info_key, info_value FROM cfg_contacts_infos", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + + while (ms->fetch_row(res)) { + output->add_contact_info(res.value_as_u32(0), res.value_as_str(1), + res.value_as_str(2)); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load contacts infos from database: " + << e.what(); + } +} diff --git a/centreon-broker/notification/src/loaders/dependency_loader.cc b/centreon-broker/notification/src/loaders/dependency_loader.cc new file mode 100644 index 00000000000..30f17e171fb --- /dev/null +++ b/centreon-broker/notification/src/loaders/dependency_loader.cc @@ -0,0 +1,208 @@ +/* +** 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/notification/loaders/dependency_loader.hh" +#include +#include +#include +#include "com/centreon/broker/exceptions/msg.hh" +#include "com/centreon/broker/notification/objects/dependency.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +dependency_loader::dependency_loader() {} + +/** + * Load the dependencies from the database. + * + * @param[in] db An open connection to the database. + * @param[out] output A dependency builder object to register the + * dependencies. + */ +void dependency_loader::load(mysql* ms, dependency_builder* output) { + // If we don't have any db or output, don't do anything. + if (!ms || !output) + return; + + log_v2::notification()->debug( + "notification: loading dependencies from the database"); + + // We do not know the type of a dependency until far latter. + // Cache the options until we know enough to correctly parse them. + std::vector> dep_execution_failure_options; + std::vector> dep_notification_failure_options; + + // Performance improvement, as we never go back. + // query.setForwardOnly(true); + + // Load the dependencies. + std::promise promise; + ms->run_query_and_get_result( + "SELECT dep_id, inherits_parent," + " execution_failure_criteria," + " notification_failure_criteria" + " FROM cfg_dependencies", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) { + dependency::ptr dep(new dependency); + uint32_t id = res.value_as_u32(0); + dep->set_inherits_parent(res.value_as_bool(1)); + dep_execution_failure_options.push_back( + std::make_pair(id, res.value_as_str(2))); + dep_notification_failure_options.push_back( + std::make_pair(id, res.value_as_str(3))); + + output->add_dependency(id, dep); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load dependencies from database: " << e.what(); + } + + // Get the relations of the dependencies. It will also give us their type. + _load_relations(ms, *output); + + // We now know the types of the dependencies: we can parse the failure + // options. + for (std::vector>::const_iterator + it(dep_execution_failure_options.begin()), + end(dep_execution_failure_options.end()); + it != end; ++it) + output->set_execution_failure_options(it->first, it->second); + for (std::vector>::const_iterator + it(dep_notification_failure_options.begin()), + end(dep_notification_failure_options.end()); + it != end; ++it) + output->set_notification_failure_options(it->first, it->second); +} + +/** + * Load the relations from the database. + * + * @param[in] query A query object linked to the db. + * @param[out] output An output dependency builder to load the relations. + */ +void dependency_loader::_load_relations(mysql* ms, dependency_builder& output) { + std::promise promise; + ms->run_query_and_get_result( + "SELECT dependency_dep_id, host_host_id" + " FROM cfg_dependencies_hostchildren_relations", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) + output.dependency_node_id_child_relation(res.value_as_u32(0), + node_id(res.value_as_u32(1))); + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load host/child dependencies from database: " + << e.what(); + } + + promise = std::promise(); + ms->run_query_and_get_result( + "SELECT dependency_dep_id, host_host_id" + " FROM cfg_dependencies_hostparents_relations", + &promise); + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) + output.dependency_node_id_parent_relation(res.value_as_u32(0), + node_id(res.value_as_u32(1))); + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load host/parent dependencies from database: " + << e.what(); + } + + promise = std::promise(); + ms->run_query_and_get_result( + "SELECT dependency_dep_id, service_service_id, host_host_id" + " FROM cfg_dependencies_servicechildren_relations", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) + output.dependency_node_id_child_relation( + res.value_as_u32(0), + node_id(res.value_as_u32(2), res.value_as_u32(1))); + } catch (std::exception const& e) { + throw exceptions::msg() << "notification: cannot load service/child " + "dependencies from database: " + << e.what(); + } + + promise = std::promise(); + ms->run_query_and_get_result( + "SELECT dependency_dep_id, service_service_id, host_host_id" + " FROM cfg_dependencies_serviceparents_relations", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) + output.dependency_node_id_parent_relation( + res.value_as_u32(0), + node_id(res.value_as_u32(2), res.value_as_u32(1))); + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load service/parent dependencies" + " from database: " + << e.what(); + } +} + +/** + * Load a relation between two ids, one of which is dependency_dep_id, from a + * table in the database. + * + * @param[in,out] query A query object linked to the db. + * @param[out] output The output dependency builder. + * @param[in] relation_id_name The name of the second relation + * identifier. + * @param[in] table The table to load the relations from. + * @param[in] register_method The dependency builder method to call to + * register the escalation. + */ +// void dependency_loader::_load_relation( +// QSqlQuery& query, +// dependency_builder& output, +// std::string const& relation_id_name, +// std::string const& table, +// void (dependency_builder::*register_method)(uint32_t, unsigned +// int)) { +// std::stringstream ss; +// ss << "SELECT dependency_dep_id, " << relation_id_name << " FROM " << table; +// if (!query.exec(ss.str().c_str())) +// throw (exceptions::msg() +// << "notification: cannot select " << table << " in loader: " +// << query.lastError().text()); +// +// while (query.next()) { +// uint32_t id = query.value(0).toUInt(); +// uint32_t associated_id = query.value(1).toUInt(); +// +// (output.*register_method)(id, associated_id); +// } +//} diff --git a/centreon-broker/notification/src/loaders/escalation_loader.cc b/centreon-broker/notification/src/loaders/escalation_loader.cc new file mode 100644 index 00000000000..a82ecb1c7ee --- /dev/null +++ b/centreon-broker/notification/src/loaders/escalation_loader.cc @@ -0,0 +1,141 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/loaders/escalation_loader.hh" +#include +#include +#include +#include "com/centreon/broker/exceptions/msg.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +escalation_loader::escalation_loader() {} + +/** + * Load the escalations from the database. + * + * @param[in] db An open connection to the database. + * @param[out] output An escalation builder object to register the + * escalations. + */ +void escalation_loader::load(QSqlDatabase* db, escalation_builder* output) { + // If we don't have any db or output, don't do anything. + if (!db || !output) + return; + + QSqlQuery query(*db); + + // Performance improvement, as we never go back. + query.setForwardOnly(true); + + // Load the escalations. + if (!query.exec("SELECT esc_id, esc_name, esc_alias, first_notification," + "last_notification, notification_interval, escalation_period," + "escalation_options1, escalation_options2" + " FROM escalation")) + throw(exceptions::msg() + << "Notification: cannot select escalation in loader: " + << query.lastError().text()); + + while (query.next()) { + escalation::ptr esc(new escalation); + uint32_t id = query.value(0).toUInt(); + + esc->set_first_notification(query.value(3).toUInt()); + esc->set_last_notification(query.value(4).toUInt()); + esc->set_notification_interval(query.value(5).toUInt()); + esc->set_escalation_period(query.value(6).toString().toStdString()); + esc->parse_host_escalation_options(query.value(7).toString().toStdString()); + esc->parse_service_escalation_options( + query.value(7).toString().toStdString()); + + output->add_escalation(id, esc); + } + + // Load relations + _load_relations(query, *output); +} + +void escalation_loader::_load_relations(QSqlQuery& query, + escalation_builder& output) { + // Load the escalation to node id relations. + if (!query.exec("SELECT escalation_esc_id, host_host_id" + " FROM escalation_host_relation")) + throw(exceptions::msg() + << "Notification: cannot select escalation_host_relation in loader: " + << query.lastError().text()); + while (query.next()) + output.connect_escalation_node_id(query.value(0).toUInt(), + node_id(query.value(1).toUInt())); + + if (!query.exec("SELECT escalation_esc_id, host_host_id, service_service_id" + " FROM escalation_service_relation")) + throw(exceptions::msg() + << "Notification: cannot select escalation_host_relation in loader: " + << query.lastError().text()); + while (query.next()) + output.connect_escalation_node_id( + query.value(0).toUInt(), + node_id(query.value(1).toUInt(), query.value(2).toUInt())); + + // Load the escalation to contactgroup relations. + _load_relation(query, output, "contactgroup_cg_id", + "escalation_contactgroup_relation", + &escalation_builder::connect_escalation_contactgroup); + // Load the escalation to hostgroup relations. + _load_relation(query, output, "hostgroup_hg_id", + "escalation_hostgroup_relation", + &escalation_builder::connect_escalation_hostgroup); + // Load the escalation to servicegroup relation. + _load_relation(query, output, "servicegroup_sg_id", + "escalation_servicegroup_relation", + &escalation_builder::connect_escalation_servicegroup); +} + +/** + * Load a relation between two ids, one of which is escalation_esc_id, from a + * table in the database. + * + * @param[in,out] query A query object linked to the db. + * @param[out] output The output escalation builder. + * @param[in] relation_id_name The name of the second relation + * identifier. + * @param[in] table The table to load the relations from. + * @param[in] register_method The escalation builder method to call to + * register the escalation. + */ +void escalation_loader::_load_relation( + QSqlQuery& query, + escalation_builder& output, + std::string const& relation_id_name, + std::string const& table, + void (escalation_builder::*register_method)(uint32_t, uint32_t)) { + std::stringstream ss; + ss << "SELECT escalation_esc_id, " << relation_id_name << " FROM " << table; + if (!query.exec(ss.str().c_str())) + throw(exceptions::msg() << "Notification: cannot select " << table + << " in loader: " << query.lastError().text()); + + while (query.next()) { + uint32_t id = query.value(0).toUInt(); + uint32_t associated_id = query.value(1).toUInt(); + + (output.*register_method)(id, associated_id); + } +} diff --git a/centreon-broker/notification/src/loaders/macro_loader.cc b/centreon-broker/notification/src/loaders/macro_loader.cc new file mode 100644 index 00000000000..6a45fb46792 --- /dev/null +++ b/centreon-broker/notification/src/loaders/macro_loader.cc @@ -0,0 +1,139 @@ +/* +** 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/notification/loaders/macro_loader.hh" +#include +#include +#include +#include "com/centreon/broker/exceptions/msg.hh" +#include "com/centreon/broker/notification/utilities/get_datetime_string.hh" + +using namespace com::centreon::broker::notification; + +/** + * Default constructor. + */ +macro_loader::macro_loader() {} + +/** + * Load the macros from the database. + * + * @param[in] ms An open connection to the database. + * @param[out] output A macro builder object to register the macros. + */ +void macro_loader::load(mysql* ms, macro_builder* output) { + // If we don't have any db or output, don't do anything. + if (!ms || !output) + return; + log_v2::notification()->debug( + "notification: loading macros from the database"); + + // Performance improvement, as we never go back. + // query.setForwardOnly(true); + + // Load global, constant macro. + /*if (!query.exec( + "SELECT admin_email, admin_pager, cfg_file, status_file," + " state_retention_file, object_cache_file, temp_file," + " log_file, command_file, host_perfdata_file, " + " service_perfdata_file, temp_path, date_format" + " FROM cfg_engine")) + throw (exceptions::msg() + << "notification: cannot load global monitoring options from + database: " + << query.lastError().text()); + if (!query.next()) { + log_v2::notification()->info("notification: could not find default + monitoring options, some global macros will be empty"); + } + else { + output->add_global_macro( + "ADMINEMAIL", + query.value(0).toString().toStdString()); + output->add_global_macro( + "ADMINPAGER", + query.value(1).toString().toStdString()); + output->add_global_macro( + "MAINCONFIGFILE", + query.value(2).toString().toStdString()); + output->add_global_macro( + "STATUSDATAFILE", + query.value(3).toString().toStdString()); + output->add_global_macro( + "RETENTIONDATAFILE", + query.value(4).toString().toStdString()); + output->add_global_macro( + "OBJECTCACHEFILE", + query.value(5).toString().toStdString()); + output->add_global_macro( + "TEMPFILE", + query.value(6).toString().toStdString()); + output->add_global_macro( + "LOGFILE", + query.value(7).toString().toStdString()); + output->add_global_macro("RESOURCEFILE", "resource.cfg"); + output->add_global_macro( + "COMMANDFILE", + query.value(8).toString().toStdString()); + output->add_global_macro( + "HOSTPERFDATAFILE", + query.value(9).toString().toStdString()); + output->add_global_macro( + "SERVICEPERFDATAFILE", + query.value(10).toString().toStdString()); + output->add_global_macro( + "TEMPPATH", + query.value(11).toString().toStdString()); + QString date_format = query.value(12).toString(); + if (date_format == "euro") + output->add_date_format(utilities::date_format_euro); + else if (date_format == "iso8601") + output->add_date_format(utilities::date_format_iso8601); + else if (date_format == "strict-iso8601") + output->add_date_format(utilities::date_format_strict_iso8601); + else + output->add_date_format(utilities::date_format_us); + }*/ + + // Load global resource macros. + std::promise promise; + ms->run_query_and_get_result( + "SELECT resource_name, resource_line" + " FROM cfg_resources" + " WHERE resource_activate = '1'", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) { + // Remove leading and trailing $$ + std::string macro_name = res.value_as_str(0); + // Remove leading and trailing $$ + macro_name.erase(0, 1); + macro_name.erase(macro_name.size() - 1); + log_v2::notification()->debug( + "notification: loading resource macro ({}) from database", + macro_name); + output->add_resource_macro(macro_name, res.value_as_str(1)); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load resource macros from database: " + << e.what(); + } +} diff --git a/centreon-broker/notification/src/loaders/node_loader.cc b/centreon-broker/notification/src/loaders/node_loader.cc new file mode 100644 index 00000000000..ea200c54c47 --- /dev/null +++ b/centreon-broker/notification/src/loaders/node_loader.cc @@ -0,0 +1,89 @@ +/* +** 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/notification/loaders/node_loader.hh" +#include +#include +#include "com/centreon/broker/exceptions/msg.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +node_loader::node_loader() {} + +/** + * Load the nodes from the database. + * + * @param[in] ms An open connection to the database. + * @param[out] output A node builder object to register the nodes. + */ +void node_loader::load(mysql* ms, node_builder* output) { + // If we don't have any db or output, don't do anything. + if (!ms || !output) + return; + log_v2::notification()->debug( + "notification: loading nodes from the database"); + + // Performance improvement, as we never go back. + // query.setForwardOnly(true); + + // Load hosts. + std::promise promise; + ms->run_query_and_get_result("SELECT host_id FROM cfg_hosts", &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) { + uint32_t host_id = res.value_as_u32(0); + node::ptr n(new node); + n->set_node_id(node_id(host_id)); + log_v2::notification()->debug( + "notification: loading host {} from database", host_id); + output->add_node(n); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load hosts from database: " << e.what(); + } + + promise = std::promise(); + // Load services. + ms->run_query_and_get_result( + "SELECT hsr.host_host_id, hsr.service_service_id" + " FROM cfg_hosts_services_relations AS hsr" + " LEFT JOIN cfg_services AS s" + " ON hsr.service_service_id=s.service_id", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) { + uint32_t host_id = res.value_as_u32(0); + uint32_t service_id = res.value_as_u32(1); + node::ptr n(new node); + n->set_node_id(node_id(host_id, service_id)); + log_v2::notification()->debug( + "notification: loading service ({}, {}) from database", host_id, + service_id); + output->add_node(n); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load services from database: " << e.what(); + } +} diff --git a/centreon-broker/notification/src/loaders/notification_method_loader.cc b/centreon-broker/notification/src/loaders/notification_method_loader.cc new file mode 100644 index 00000000000..9d3db00a846 --- /dev/null +++ b/centreon-broker/notification/src/loaders/notification_method_loader.cc @@ -0,0 +1,69 @@ +/* +** 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/notification/loaders/notification_method_loader.hh" +#include +#include +#include "com/centreon/broker/exceptions/msg.hh" +#include "com/centreon/broker/notification/objects/notification_method.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +notification_method_loader::notification_method_loader() {} + +void notification_method_loader::load(mysql* ms, + notification_method_builder* output) { + // If we don't have any db or output, don't do anything. + if (!ms || !output) + return; + + log_v2::notification()->debug( + "notification: loading notification methods from the database"); + + // Performance improvement, as we never go back. + // query.setForwardOnly(true); + + std::promise promise; + ms->run_query_and_get_result( + "SELECT method_id, name, command_id, `interval`, status, " + " types, start, end " + " FROM cfg_notification_methods", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) { + notification_method::ptr nm(new notification_method); + nm->set_name(res.value_as_str(1)); + nm->set_command_id(res.value_as_u32(2)); + nm->set_interval(res.value_as_u32(3)); + nm->set_status(res.value_as_str(4)); + nm->set_types(res.value_as_str(5)); + nm->set_start(res.value_as_u32(6)); + nm->set_end(res.value_as_u32(7)); + log_v2::notification()->debug("notification: new method {} ('{}')", + res.value_as_u32(0), nm->get_name()); + output->add_notification_method(res.value_as_u32(0), nm); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load notification methods from database: " + << e.what(); + } +} diff --git a/centreon-broker/notification/src/loaders/notification_rule_loader.cc b/centreon-broker/notification/src/loaders/notification_rule_loader.cc new file mode 100644 index 00000000000..79d868f8110 --- /dev/null +++ b/centreon-broker/notification/src/loaders/notification_rule_loader.cc @@ -0,0 +1,68 @@ +/* +** 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/notification/loaders/notification_rule_loader.hh" +#include +#include +#include "com/centreon/broker/exceptions/msg.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +notification_rule_loader::notification_rule_loader() {} + +void notification_rule_loader::load(mysql* ms, + notification_rule_builder* output) { + // If we don't have any db or output, don't do anything. + if (!ms || !output) + return; + + log_v2::notification()->debug( + "notification: loading notification rules from the database"); + + // Performance improvement, as we never go back. + // query.setForwardOnly(true); + + std::promise promise; + ms->run_query_and_get_result( + "SELECT rule_id, method_id, timeperiod_id, contact_id, " + " host_id, service_id" + " FROM rt_notification_rules", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) { + notification_rule::ptr rule(new notification_rule); + rule->set_id(res.value_as_u32(0)); + rule->set_method_id(res.value_as_u32(1)); + rule->set_timeperiod_id(res.value_as_u32(2)); + rule->set_contact_id(res.value_as_u32(3)); + rule->set_node_id(node_id(res.value_as_u32(4), res.value_as_u32(5))); + log_v2::notification()->debug( + "notification: new rule {} affecting node ({}, {}) using method {}", + rule->get_id(), rule->get_node_id().get_host_id(), + rule->get_node_id().get_service_id(), rule->get_method_id()); + output->add_rule(res.value_as_u32(0), rule); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load notification rules from database: " + << e.what(); + } +} diff --git a/centreon-broker/notification/src/loaders/timeperiod_loader.cc b/centreon-broker/notification/src/loaders/timeperiod_loader.cc new file mode 100644 index 00000000000..f44828e449f --- /dev/null +++ b/centreon-broker/notification/src/loaders/timeperiod_loader.cc @@ -0,0 +1,133 @@ +/* +** 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/notification/loaders/timeperiod_loader.hh" +#include "com/centreon/broker/exceptions/msg.hh" +#include "com/centreon/broker/notification/builders/timeperiod_builder.hh" +#include "com/centreon/broker/time/timeperiod.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::time; + +timeperiod_loader::timeperiod_loader() {} + +/** + * Load the timeperiods from the database. + * + * @param[in] ms An open connection to the database. + * @param[out] output A timeperiod builder object to register the + * timeperiods. + */ +void timeperiod_loader::load(mysql* ms, timeperiod_builder* output) { + // If we don't have any db or output, don't do anything. + if (!ms || !output) + return; + log_v2::notification()->debug( + "notification: loading timeperiods from the database"); + + // Performance improvement, as we never go back. + // query.setForwardOnly(true); + + // Load the timeperiods. + std::promise promise; + ms->run_query_and_get_result( + "SELECT tp_id, tp_name, tp_alias, tp_sunday, tp_monday," + " tp_tuesday, tp_wednesday, tp_thursday, tp_friday," + " tp_saturday sunday" + " FROM cfg_timeperiods", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) { + timeperiod::ptr tperiod(new timeperiod); + uint32_t timeperiod_id = res.value_as_u32(0); + tperiod->set_name(res.value_as_str(1)); + tperiod->set_alias(res.value_as_str(2)); + tperiod->set_timerange(res.value_as_str(3), 0); + tperiod->set_timerange(res.value_as_str(4), 1); + tperiod->set_timerange(res.value_as_str(5), 2); + tperiod->set_timerange(res.value_as_str(6), 3); + tperiod->set_timerange(res.value_as_str(7), 4); + tperiod->set_timerange(res.value_as_str(8), 5); + tperiod->set_timerange(res.value_as_str(9), 6); + + output->add_timeperiod(timeperiod_id, tperiod); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load timeperiods from database: " << e.what(); + } + + // Load the timeperiod exceptions. + promise = std::promise(); + ms->run_query_and_get_result( + "SELECT exception_id, timeperiod_id, days, timerange" + " FROM cfg_timeperiods_exceptions", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) { + uint32_t timeperiod_id = res.value_as_u32(1); + std::string days = res.value_as_str(2); + std::string timerange = res.value_as_str(3); + output->add_timeperiod_exception(timeperiod_id, days, timerange); + } + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load timeperiods exceptions from database: " + << e.what(); + } + + // Load the timeperiod exclude relations. + promise = std::promise(); + ms->run_query_and_get_result( + "SELECT exclude_id, timeperiod_id, timeperiod_exclude_id" + " FROM cfg_timeperiods_exclude_relations", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) + output->add_timeperiod_exclude_relation(res.value_as_u32(1), + res.value_as_u32(0)); + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load timeperiods exclusions from database: " + << e.what(); + } + + // Load the timeperiod include relations. + promise = std::promise(); + ms->run_query_and_get_result( + "SELECT include_id, timeperiod_id, timeperiod_include_id" + " FROM cfg_timeperiods_include_relations", + &promise); + + try { + database::mysql_result res(promise.get_future().get()); + while (ms->fetch_row(res)) + output->add_timeperiod_include_relation(res.value_as_u32(1), + res.value_as_u32(0)); + } catch (std::exception const& e) { + throw exceptions::msg() + << "notification: cannot load timeperiods inclusions from database: " + << e.what(); + } +} diff --git a/centreon-broker/notification/src/macro_context.cc b/centreon-broker/notification/src/macro_context.cc new file mode 100644 index 00000000000..7c46547978c --- /dev/null +++ b/centreon-broker/notification/src/macro_context.cc @@ -0,0 +1,82 @@ +/* +** Copyright 2011-2014 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/macro_context.hh" + +using namespace com::centreon::broker::notification; + +/** + * Macro context constructor. + * + * @param[in] id Id of the node being notified. + * @param[in] cnt Contact being notified. + * @param[in] st Notification engine's state. + * @param[in] cache Node cache. + * @param[in] act The notification action. + */ +macro_context::macro_context(objects::node_id id, + objects::contact const& cnt, + state const& st, + node_cache const& cache, + action const& act) + : _id(id), _cnt(cnt), _st(st), _cache(cache), _act(act) {} + +/** + * Get the if of the node being notified. + * + * @return The id of the node being notified. + */ +objects::node_id macro_context::get_id() const { + return (_id); +} + +/** + * Get the contact being notified. + * + * @return The notified contact. + */ +objects::contact const& macro_context::get_contact() const { + return (_cnt); +} + +/** + * Get the state of the engine. + * + * @return The engine's state. + */ +state const& macro_context::get_state() const { + return (_st); +} + +/** + * Get the node cache. + * + * @return The node cache. + */ +node_cache const& macro_context::get_cache() const { + return (_cache); +} + +/** + * Get the notification action. + * + * @return The notification action. + */ +action const& macro_context::get_action() const { + return (_act); +} diff --git a/centreon-broker/notification/src/macro_generator.cc b/centreon-broker/notification/src/macro_generator.cc new file mode 100644 index 00000000000..472963bcd82 --- /dev/null +++ b/centreon-broker/notification/src/macro_generator.cc @@ -0,0 +1,447 @@ +/* +** Copyright 2011-2015 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/macro_generator.hh" +#include +#include +#include "com/centreon/broker/exceptions/msg.hh" +#include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/notification/macro_getters.hh" +#include "com/centreon/broker/notification/utilities/get_datetime_string.hh" +#include "com/centreon/broker/notification/utilities/qhash_func.hh" + +using namespace com::centreon::broker; +using namespace com::centreon::broker::notification; + +// Used for contact macros. +const char* get_email_key() { + return "email"; +} +const char* get_pager_key() { + return "pager"; +} + +macro_generator::x_macro_map macro_generator::_map; + +/** + * Default constructor. + */ +macro_generator::macro_generator() { + if (_map.empty()) + _fill_x_macro_map(_map); +} + +/** + * Generate macros. + * + * @param[in,out] container A container of asked macro, which will be filled + * as a result. + * @param[in] id The id of the node for which we create macros. + * @param[in] cnt The contact. + * @param[in] st The state. + * @param[in] cache The node cache. + * @param[in] act The notification action. + */ +void macro_generator::generate(macro_container& container, + objects::node_id id, + objects::contact const& cnt, + state const& st, + node_cache const& cache, + action const& act) const { + objects::node::ptr node = st.get_node_by_id(id); + if (!node) + throw(exceptions::msg() + << "notification: can't find the node (" << id.get_host_id() << ", " + << id.get_service_id() << ") while generating its macros"); + objects::node::ptr host = node; + if (id.is_service()) + host = st.get_node_by_id(objects::node_id(id.get_host_id())); + if (!host) + throw(exceptions::msg() << "notification: can't find the host " + << id.get_host_id() << " while generating macros"); + + for (macro_container::iterator it(container.begin()), end(container.end()); + it != end; ++it) { + log_v2::notification()->debug("notification: searching macro {}", it.key()); + if (_get_global_macros(it.key(), st, it.value())) + continue; + else if (_get_x_macros(it.key(), macro_context(id, cnt, st, cache, act), + it.value())) + continue; + else if (_get_custom_macros(it.key(), id, cache, it.value())) + continue; + else { + log_v2::notification()->debug( + "notification: macro '{}' was not found for node ({}, {})", it.key(), + id.get_host_id(), id.get_service_id()); + it->clear(); + } + } +} + +/** + * Get this macro if it's a global macro. + * + * @param[in] macro_name The name of the macro. + * @param[in] st The state. + * @param[out] result The result, filled if the macro is global. + * @return True if this macro was found in the global macros. + */ +bool macro_generator::_get_global_macros(std::string const& macro_name, + state const& st, + std::string& result) { + QHash const& global_macros = st.get_global_macros(); + QHash::const_iterator found = + global_macros.find(macro_name); + if (found == global_macros.end()) + return (false); + result = *found; + return (true); +} + +/** + * Get standard nagios macros. + * + * @param[in] macro_name The macro name. + * @param[in] contact The macro context. + * @param[out] result The result, filled if the macro is standard. + * + * @return True if the macro was found in the standard macros. + */ +bool macro_generator::_get_x_macros(std::string const& macro_name, + macro_context const& context, + std::string& result) const { + x_macro_map::const_iterator found = _map.find(macro_name); + if (found == _map.end()) + return (false); + else { + result = (*found)(context); + return (true); + } +} + +/** + * Get custom macros. + * + * @param[in] macro_name The macro name. + * @param[in] id The id of the node being notified. + * @param[in] cache The node cache. + * @param[out] result The result, filled if the macro is a custom macro. + * + * @return True if the macro was found in the custom macros. + */ +bool macro_generator::_get_custom_macros(std::string const& macro_name, + objects::node_id id, + node_cache const& cache, + std::string& result) { + std::unordered_map const* + custom_vars; + if (id.is_host()) + custom_vars = &cache.get_host(id).get_custom_vars(); + else + custom_vars = &cache.get_service(id).get_custom_vars(); + + std::unordered_map::const_iterator + found{custom_vars->find(macro_name)}; + if (found != custom_vars->end()) { + result = found->second.value; + return true; + } else + return false; +} + +/** + * Fill the macro generator map with functions used to generate macros. + * + * @param[in] map The map to fill. + */ +void macro_generator::_fill_x_macro_map(x_macro_map& map) { + // Time macros. + map.insert("LONGDATETIME", &get_datetime_string); + map.insert("SHORTDATETIME", &get_datetime_string); + map.insert("DATE", &get_datetime_string); + map.insert("TIME", &get_datetime_string); + map.insert("TIMET", &get_timet_string); + + // Host specific macros. + map.insert("HOSTNAME", &get_host_member_as_string); + map.insert( + "HOSTALIAS", + &get_host_member_as_string); + map.insert("HOSTADDRESS", &get_host_member_as_string); + map.insert("HOSTSTATE", &get_host_state); + map.insert("HOSTSTATEID", &get_host_status_member_as_string< + neb::host_service_status, short, + &neb::host_service_status::current_state, 0>); + map.insert("LASTHOSTSTATE", &get_last_host_state); + map.insert("LASTHOSTSTATEID", + &get_host_prevstatus_member_as_string< + neb::host_service_status, short, + &neb::host_service_status::current_state, 0>); + map.insert("HOSTSTATETYPE", &get_host_state_type); + map.insert("HOSTATTEMPT", + &get_host_status_member_as_string< + neb::host_service_status, short, + &neb::host_service_status::current_check_attempt, 0>); + map.insert("MAXHOSTATTEMPTS", + &get_host_status_member_as_string< + neb::host_service_status, short, + &neb::host_service_status::max_check_attempts, 0>); + // Event and problem id macros are ignored. + map.insert("HOSTEVENTID", &null_getter); + map.insert("LASTHOSTEVENTID", &null_getter); + map.insert("HOSTPROBLEMID", &null_getter); + map.insert("LASTHOSTPROBLEMID", &null_getter); + map.insert( + "HOSTLATENCY", + &get_host_status_member_as_string); + map.insert("HOSTEXECUTIONTIME", + &get_host_status_member_as_string< + neb::host_service_status, double, + &neb::host_service_status::execution_time, 3>); + map.insert("HOSTDURATION", get_host_duration); + map.insert("HOSTDURATIONSEC", get_host_duration_sec); + map.insert("HOSTDOWNTIME", &get_node_downtime_number); + map.insert("HOSTPERCENTCHANGE", + &get_host_status_member_as_string< + neb::host_service_status, double, + &neb::host_service_status::percent_state_change, 2>); + map.insert("HOSTGROUPNAME", &null_getter); + map.insert("HOSTGROUPNAMES", &null_getter); + map.insert( + "LASTHOSTCHECK", + &get_host_status_member_as_string); + map.insert("LASTHOSTSTATECHANGE", + &get_host_status_member_as_string< + neb::host_service_status, timestamp, + &neb::host_service_status::last_state_change, 0>); + map.insert( + "LASTHOSTUP", + &get_host_status_member_as_string); + map.insert( + "LASTHOSTDOWN", + &get_host_status_member_as_string); + map.insert("LASTHOSTUNREACHABLE", + &get_host_status_member_as_string< + neb::host_status, timestamp, + &neb::host_status::last_time_unreachable, 0>); + map.insert("HOSTOUTPUT", &get_host_output); + map.insert("LONGHOSTOUTPUT", &get_host_output); + map.insert( + "HOSTPERFDATA", + &get_host_status_member_as_string); + map.insert("HOSTCHECKCOMMAND", + &get_host_status_member_as_string< + neb::host_service_status, std::string, + &neb::host_service_status::check_command, 0>); + // Hst ack macros are deprecated and ignored. + map.insert("HOSTACKAUTHOR", &null_getter); + map.insert("HOSTACKAUTHORNAME", &null_getter); + map.insert("HOSTACKAUTHORALIAS", &null_getter); + map.insert("HOSTACKCOMMENT", &null_getter); + map.insert("TOTALHOSTSERVICES", &get_total_host_services<-1>); + map.insert("TOTALHOSTSERVICESOK", + &get_total_host_services); + map.insert("TOTALHOSTSERVICESWARNING", + &get_total_host_services); + map.insert("TOTALHOSTSERVICESUNKNOWN", + &get_total_host_services); + map.insert("TOTALHOSTSERVICESCRITICAL", + &get_total_host_services); + + // Service macros + map.insert("SERVICEDESC", &get_service_status_member_as_string< + neb::service_status, std::string, + &neb::service_status::service_description, 0>); + map.insert("SERVICESTATE", &get_service_state); + map.insert("SERVICESTATEID", + &get_service_status_member_as_string< + neb::host_service_status, short, + &neb::host_service_status::current_state, 0>); + map.insert("LASTSERVICESTATE", &get_last_service_state); + map.insert("LASTSERVICESTATEID", + &get_service_prevstatus_member_as_string< + neb::host_service_status, short, + &neb::host_service_status::current_state, 0>); + map.insert("SERVICESTATETYPE", &get_service_state_type); + map.insert("SERVICEATTEMPT", + &get_service_status_member_as_string< + neb::host_service_status, short, + &neb::host_service_status::current_check_attempt, 0>); + map.insert("MAXSERVICEATTEMPTS", + &get_service_status_member_as_string< + neb::host_service_status, short, + &neb::host_service_status::max_check_attempts, 0>); + map.insert("SERVICEISVOLATILE", + &get_service_member_as_string); + // Event id are ignored. + map.insert("SERVICEEVENTID", &null_getter); + map.insert("LASTSERVICEEVENTID", &null_getter); + map.insert("SERVICEPROBLEMID", &null_getter); + map.insert("LASTSERVICEPROBLEMID", &null_getter); + map.insert( + "SERVICELATENCY", + &get_service_status_member_as_string); + map.insert("SERVICEEXECUTIONTIME", + &get_service_status_member_as_string< + neb::host_service_status, double, + &neb::host_service_status::execution_time, 3>); + map.insert("SERVICEDURATION", &get_service_duration); + map.insert("SERVICEDURATIONSEC", &get_service_duration_sec); + // XXX map.insert( + // "SERVICEDOWNTIME", + // &get_service_status_member_as_string< + // neb::host_service_status, + // short, + // &neb::host_service_status::scheduled_downtime_depth, + // 0>); + map.insert("SERVICEPERCENTCHANGE", + &get_service_status_member_as_string< + neb::host_service_status, double, + &neb::host_service_status::percent_state_change, 2>); + map.insert("SERVICEGROUPNAME", &null_getter); + map.insert("SERVICEGROUPNAMES", &null_getter); + map.insert("LASTSERVICECHECK", &get_service_status_member_as_string< + neb::host_service_status, timestamp, + &neb::host_service_status::last_check, 0>); + map.insert("LASTSERVICESTATECHANGE", + &get_service_status_member_as_string< + neb::host_service_status, timestamp, + &neb::host_service_status::last_state_change, 0>); + map.insert( + "LASTSERVICEOK", + &get_service_status_member_as_string); + map.insert("LASTSERVICEWARNING", + &get_service_status_member_as_string< + neb::service_status, timestamp, + &neb::service_status::last_time_warning, 0>); + map.insert("LASTSERVICEUNKNOWN", + &get_service_status_member_as_string< + neb::service_status, timestamp, + &neb::service_status::last_time_unknown, 0>); + map.insert("LASTSERVICECRITICAL", + &get_service_status_member_as_string< + neb::service_status, timestamp, + &neb::service_status::last_time_critical, 0>); + map.insert("SERVICEOUTPUT", &get_service_output); + map.insert("LONGSERVICEOUTPUT", &get_service_output); + map.insert("SERVICEPERFDATA", &get_service_status_member_as_string< + neb::host_service_status, std::string, + &neb::host_service_status::perf_data, 0>); + map.insert("SERVICECHECKCOMMAND", + &get_service_status_member_as_string< + neb::host_service_status, std::string, + &neb::host_service_status::check_command, 0>); + // Deprecated, ignored. + map.insert("SERVICEACKAUTHOR", &null_getter); + map.insert("SERVICEACKAUTHORNAME", &null_getter); + map.insert("SERVICEACKAUTHORALIAS", &null_getter); + map.insert("SERVICEACKCOMMENT", &null_getter); + + // Counting macros. + map.insert("TOTALHOSTSUP", &get_total_hosts); + map.insert("TOTALHOSTSDOWN", + &get_total_hosts); + map.insert("TOTALHOSTSUNREACHABLE", + &get_total_hosts); + map.insert("TOTALHOSTSDOWNUNHANDLED", + &get_total_hosts_unhandled); + map.insert("TOTALHOSTSUNREACHABLEUNHANDLED", + &get_total_hosts_unhandled); + map.insert("TOTALHOSTPROBLEMS", &get_total_hosts<-1>); + map.insert("TOTALHOSTPROBLEMSUNHANDLED", &get_total_hosts_unhandled<-1>); + map.insert("TOTALSERVICESOK", + &get_total_services); + map.insert("TOTALSERVICESWARNING", + &get_total_services); + map.insert("TOTALSERVICESCRITICAL", + &get_total_services); + map.insert("TOTALSERVICESUNKNOWN", + &get_total_services); + map.insert( + "TOTALSERVICESWARNINGUNHANDLED", + &get_total_services_unhandled); + map.insert( + "TOTALSERVICESCRITICALUNHANDLED", + &get_total_services_unhandled); + map.insert( + "TOTALSERVICESUNKNOWNUNHANDLED", + &get_total_services_unhandled); + map.insert("TOTALSERVICEPROBLEMS", &get_total_services<-1>); + map.insert("TOTALSERVICEPROBLEMSUNHANDLED", + &get_total_services_unhandled<-1>); + + // Groups macros. + map.insert("HOSTGROUPALIAS", &null_getter); + map.insert("HOSTGROUPMEMBERS", &null_getter); + map.insert("SERVICEGROUPALIAS", &null_getter); + map.insert("SERVICEGROUPMEMBERS", &null_getter); + + // Contact macros. + map.insert("CONTACTNAME", + &get_contact_member); + map.insert("CONTACTALIAS", + &get_contact_member); + map.insert("CONTACTEMAIL", &get_contact_info); + map.insert("CONTACTPAGER", &get_contact_info); + map.insert("CONTACTADDRESS1", &get_address_of_contact<1>); + map.insert("CONTACTADDRESS2", &get_address_of_contact<2>); + map.insert("CONTACTADDRESS3", &get_address_of_contact<3>); + map.insert("CONTACTADDRESS4", &get_address_of_contact<4>); + map.insert("CONTACTADDRESS5", &get_address_of_contact<5>); + map.insert("CONTACTADDRESS6", &get_address_of_contact<6>); + map.insert("CONTACTGROUPALIAS", &null_getter); + map.insert("CONTACTGROUPMEMBERS", &null_getter); + + // Notification macro. + map.insert("NOTIFICATIONTYPE", &get_notification_type); + map.insert("NOTIFICATIONRECIPIENTS", + &get_contact_member); + map.insert("HOSTNOTIFICATIONNUMBER", + &get_action_member); + map.insert("SERVICENOTIFICATIONNUMBER", + &get_action_member); + // We will manage notification escalation/downtime macros + // when we will manage escalations and downtimes. + map.insert("NOTIFICATIONISESCALATED", &null_getter); + map.insert("NOTIFICATIONCOMMENT", &null_getter); + // For now, notification author macros are ignored. + map.insert("NOTIFICATIONAUTHOR", &null_getter); + map.insert("NOTIFICATIONAUTHORNAME", &null_getter); + map.insert("NOTIFICATIONAUTHORALIAS", &null_getter); + // Notification id rightfully ignored. + map.insert("HOSTNOTIFICATIONID", &null_getter); + map.insert("SERVICENOTIFICATIONID", &null_getter); +} diff --git a/centreon-broker/notification/src/macro_getters.cc b/centreon-broker/notification/src/macro_getters.cc new file mode 100644 index 00000000000..348f8119f78 --- /dev/null +++ b/centreon-broker/notification/src/macro_getters.cc @@ -0,0 +1,368 @@ +/* +** Copyright 2014-2015,2018 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/macro_getters.hh" + +using namespace com::centreon::broker; + +/** + * @brief Get the output of a host. + * + * Specialization for short output. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template <> +std::string notification::get_host_output(macro_context const& context) { + std::string output{ + context.get_cache().get_host(context.get_id()).get_status().output}; + return output.substr(0, output.find_first_of('\n')); +} + +/** + * @brief Get the output of a host. + * + * Specialization for long output. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template <> +std::string notification::get_host_output(macro_context const& context) { + std::string output{ + context.get_cache().get_host(context.get_id()).get_status().output}; + size_t found = output.find_first_of('\n'); + if (found != std::string::npos) + return output.substr(found + 1, std::string::npos); + return ""; +} + +/** + * @brief Get the output of a service. + * + * Specialization for short output. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template <> +std::string notification::get_service_output( + macro_context const& context) { + std::string output{ + context.get_cache().get_service(context.get_id()).get_status().output}; + return output.substr(0, output.find_first_of('\n')); +} + +/** + * @brief Get the output of a service. + * + * Specialization for long output. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +template <> +std::string notification::get_service_output( + macro_context const& context) { + std::string output{ + context.get_cache().get_service(context.get_id()).get_status().output}; + size_t found = output.find_first_of('\n'); + if (found != std::string::npos) + return output.substr(found + 1, std::string::npos); + return ""; +} + +/** + * Get the state of a host. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_host_state( + macro_context const& context) { + short state = + context.get_cache().get_host(context.get_id()).get_status().current_state; + if (state == objects::node_state::host_up) + return ("UP"); + else if (state == objects::node_state::host_down) + return ("DOWN"); + else + return ("UNREACHABLE"); +} + +/** + * Get the state of a service. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_service_state( + macro_context const& context) { + short state = context.get_cache() + .get_service(context.get_id()) + .get_status() + .current_state; + if (state == objects::node_state::service_ok) + return ("OK"); + else if (state == objects::node_state::service_warning) + return ("WARNING"); + else if (state == objects::node_state::service_critical) + return ("CRITICAL"); + else + return ("UNKNOWN"); +} + +/** + * Get the last state of a host. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_last_host_state( + macro_context const& context) { + short state = + context.get_cache().get_host(context.get_id()).get_status().current_state; + if (state == objects::node_state::host_up) + return ("UP"); + else if (state == objects::node_state::host_down) + return ("DOWN"); + else + return ("UNREACHABLE"); +} + +/** + * Get the last state of a service. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_last_service_state( + macro_context const& context) { + short state = context.get_cache() + .get_service(context.get_id()) + .get_prev_status() + .current_state; + if (state == objects::node_state::service_ok) + return ("OK"); + else if (state == objects::node_state::service_warning) + return ("WARNING"); + else if (state == objects::node_state::service_critical) + return ("CRITICAL"); + else + return ("UNKNOWN"); +} + +/** + * Get the state type of a host. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_host_state_type( + macro_context const& context) { + if (context.get_cache().get_host(context.get_id()).get_status().state_type == + 1) + return ("HARD"); + else + return ("SOFT"); +} + +/** + * Ge the state type of service. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_service_state_type( + macro_context const& context) { + if (context.get_cache() + .get_service(context.get_id()) + .get_status() + .state_type == 1) + return ("HARD"); + else + return ("SOFT"); +} + +/** + * Null getter, returns nothing. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::null_getter( + macro_context const& context) { + (void)context; + return (""); +} + +/** + * Get the duration of a host state change. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_host_duration( + macro_context const& context) { + time_t last_state_change = context.get_cache() + .get_host(context.get_id()) + .get_status() + .last_state_change; + // Get duration. + time_t now(::time(NULL)); + unsigned long duration(now - last_state_change); + + // Break down duration. + uint32_t days(duration / (24 * 60 * 60)); + duration %= (24 * 60 * 60); + uint32_t hours(duration / (60 * 60)); + duration %= (60 * 60); + uint32_t minutes(duration / 60); + duration %= 60; + + // Stringify duration. + std::ostringstream oss; + oss << days << "d " << hours << "h " << minutes << "m " << duration << "s"; + return (oss.str()); +} + +/** + * Get the duration of a service state change. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_service_duration( + macro_context const& context) { + time_t last_state_change = context.get_cache() + .get_service(context.get_id()) + .get_status() + .last_state_change; + // Get duration. + time_t now(::time(NULL)); + unsigned long duration(now - last_state_change); + + // Break down duration. + uint32_t days(duration / (24 * 60 * 60)); + duration %= (24 * 60 * 60); + uint32_t hours(duration / (60 * 60)); + duration %= (60 * 60); + uint32_t minutes(duration / 60); + duration %= 60; + + // Stringify duration. + std::ostringstream oss; + oss << days << "d " << hours << "h " << minutes << "m " << duration << "s"; + return (oss.str()); +} + +/** + * Get the duration of a host state change in seconds. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_host_duration_sec( + macro_context const& context) { + time_t now(::time(NULL)); + unsigned long duration(now - context.get_cache() + .get_host(context.get_id()) + .get_status() + .last_state_change); + return (to_string(duration)); +} + +/** + * Get the number of downtime associated with a node. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_node_downtime_number( + macro_context const& context) { + unsigned long num = context.get_cache().node_downtimes(context.get_id()); + return (to_string(num)); +} + +/** + * Get the duration of a service state change in seconds. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_service_duration_sec( + macro_context const& context) { + time_t now(::time(NULL)); + unsigned long duration(now - context.get_cache() + .get_service(context.get_id()) + .get_status() + .last_state_change); + return (to_string(duration)); +} + +/** + * Get the actual time in seconds. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_timet_string( + macro_context const& context) { + (void)context; + return (to_string(::time(NULL))); +} + +/** + * Get the type of a notification. + * + * @param[in] context The context from where the macro is being executed. + * + * @return The value of the macro. + */ +std::string com::centreon::broker::notification::get_notification_type( + macro_context const& context) { + action::action_type type = context.get_action().get_type(); + if (type == action::notification_attempt) + return ("PROBLEM"); + else if (type == action::notification_up) + return ("RECOVERY"); + else if (type == action::notification_ack) + return ("ACKNOWLEDGEMENT"); + else if (type == action::notification_downtime) + return ("DOWNTIME"); + else + return ("UNKNOWN"); +} diff --git a/centreon-broker/notification/src/main.cc b/centreon-broker/notification/src/main.cc new file mode 100644 index 00000000000..9cc845406a0 --- /dev/null +++ b/centreon-broker/notification/src/main.cc @@ -0,0 +1,64 @@ +/* +** Copyright 2011-2015 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/exceptions/msg.hh" +#include "com/centreon/broker/io/protocols.hh" +#include "com/centreon/broker/notification/factory.hh" + +using namespace com::centreon::broker; + +// Load count. +static uint32_t instances(0); + +extern "C" { +/** + * Module version symbol. Used to check for version mismatch. + */ +char const* broker_module_version = CENTREON_BROKER_VERSION; + +/** + * Module deinitialization routine. + */ +void broker_module_deinit() { + // Decrement instance number. + if (!--instances) { + // Deregister notification layer. + io::protocols::instance().unreg("notification"); + } +} + +/** + * Module initialization routine. + * + * @param[in] arg Configuration object. + */ +void broker_module_init(void const* arg) { + (void)arg; + + // Increment instance number. + if (!instances++) { + // Notification module. + log_v2::notification()->info("notification: module for Centreon Broker {}", + CENTREON_BROKER_VERSION); + + // Register Notification layer. + io::protocols::instance().reg( + "notification", std::make_shared(), 1, 7); + } +} +} diff --git a/centreon-broker/notification/src/node_cache.cc b/centreon-broker/notification/src/node_cache.cc new file mode 100644 index 00000000000..0b36240f603 --- /dev/null +++ b/centreon-broker/notification/src/node_cache.cc @@ -0,0 +1,391 @@ +/* +** Copyright 2014-2015,2017 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/node_cache.hh" +#include +#include +#include +#include +#include "com/centreon/broker/exceptions/msg.hh" +#include "com/centreon/broker/io/events.hh" +#include "com/centreon/broker/misc/string.hh" +#include "com/centreon/broker/multiplexing/engine.hh" +#include "com/centreon/broker/neb/custom_variable.hh" +#include "com/centreon/broker/neb/internal.hh" +#include "com/centreon/broker/notification/utilities/qhash_func.hh" + +using namespace com::centreon::broker; +using namespace com::centreon::broker::notification; + +/** + * Constructor. + * + * @param[in] cache The persistent cache used by the node cache. + */ +node_cache::node_cache(std::shared_ptr cache) + : _mutex(QMutex::NonRecursive), _cache(cache) { + multiplexing::engine::instance().hook(*this); +} + +/** + * Copy constructor. + * + * @param[in] obj The object to copy. + */ +node_cache::node_cache(node_cache const& obj) : multiplexing::hooker(obj) { + node_cache::operator=(obj); +} + +/** + * Destructor. + */ +node_cache::~node_cache() { + multiplexing::engine::instance().unhook(*this); +} + +/** + * Assignment operator. + * + * @param[in] obj The object to copy. + * + * @return A reference to his object. + */ +node_cache& node_cache::operator=(node_cache const& obj) { + if (this != &obj) { + _host_node_states = obj._host_node_states; + _service_node_states = obj._service_node_states; + _cache = obj._cache; + } + return (*this); +} + +/** + * Called when the engine starts. Used to load cache file. + */ +void node_cache::starting() { + // No cache, nothing to do. + if (_cache.get() == NULL) + return; + log_v2::notification()->debug("notification: loading the node cache {}", + _cache->get_cache_file()); + + std::shared_ptr data; + try { + while (true) { + _cache->get(data); + if (!data) + break; + write(data); + } + } catch (std::exception const& e) { + // Abnormal termination of the stream. + log_v2::notification()->error( + "notification: could not load the node cache {}: {}", + _cache->get_cache_file(), e.what()); + return; + } + log_v2::notification()->debug( + "notification: finished loading the node cache {} succesfully", + _cache->get_cache_file()); +} + +/** + * Called when the engine stops. Used to unload cache file. + */ +void node_cache::stopping() { + // No cache, nothing to do. + if (_cache.get() == NULL) + return; + log_v2::notification()->debug("notification: writing the node cache {}", + _cache->get_cache_file()); + + // Lock the mutex; + QMutexLocker lock(&_mutex); + + try { + // Start a transaction. + _cache->transaction(); + // Sache into the cache. + _save_cache(); + log_v2::notification()->debug( + "notification: finished writing the node cache {} succesfully", + _cache->get_cache_file()); + } catch (std::exception const& e) { + // Abnormal termination of the stream. + log_v2::notification()->error( + "notification: could not write the node cache {}: {}", + _cache->get_cache_file(), e.what()); + return; + } + log_v2::notification()->debug("notification: commiting the node cache '{}'", + _cache->get_cache_file()); + + try { + _cache->commit(); + } catch (std::exception const& e) { + log_v2::notification()->error( + "notification: could not commit the node cache '{}': {}", + _cache->get_cache_file(), e.what()); + } + + log_v2::notification()->debug( + "notification: commited the node cache '{}' succesfully", + _cache->get_cache_file()); +} + +/** + * Read events from the node cache. + * + * @param[out] d An output data event. + * @param[in] deadline Unused. + * + * @return Always return true. + */ +bool node_cache::read(std::shared_ptr& d, time_t deadline) { + (void)deadline; + d.reset(); + return true; +} + +/** + * Write event to the node cache. + * + * @param[in] data The data event. + * + * @return Number of event acknowledged. + */ +int node_cache::write(std::shared_ptr const& data) { + // Check that data exists. + if (!validate(data, "node_cache")) + return (1); + + uint32_t type = data->type(); + if (type == neb::host::static_type()) + update(*std::static_pointer_cast(data)); + else if (type == neb::host_status::static_type()) + update(*std::static_pointer_cast(data)); + else if (type == neb::service::static_type()) + update(*std::static_pointer_cast(data)); + else if (type == neb::service_status::static_type()) + update(*std::static_pointer_cast(data)); + else if (type == neb::custom_variable::static_type() || + type == neb::custom_variable_status::static_type()) + update(*std::static_pointer_cast(data)); + else if (type == neb::acknowledgement::static_type()) + update(*std::static_pointer_cast(data)); + else if (type == neb::downtime::static_type()) + update(*std::static_pointer_cast(data)); + + return 1; +} + +/** + * Update the node cache. + * + * @param[in] hst The data to update. + */ +void node_cache::update(neb::host const& hst) { + if (hst.host_id == 0) + return; + QMutexLocker lock(&_mutex); + _host_node_states[objects::node_id(hst.host_id)].update(hst); +} + +/** + * Update the node cache. + * + * @param[in] hst The data to update. + */ +void node_cache::update(neb::host_status const& hst) { + if (hst.host_id == 0) + return; + QMutexLocker lock(&_mutex); + _host_node_states[objects::node_id(hst.host_id)].update(hst); +} + +/** + * Update the node cache. + * + * @param[in] s The data to update. + */ +void node_cache::update(neb::service const& s) { + if (s.service_id == 0) + return; + QMutexLocker lock(&_mutex); + _service_node_states[objects::node_id(s.host_id, s.service_id)].update(s); +} + +/** + * Update the node cache. + * + * @param[in] sst The data to update. + */ +void node_cache::update(neb::service_status const& sst) { + if (sst.service_id == 0) + return; + QMutexLocker lock(&_mutex); + _service_node_states[objects::node_id(sst.host_id, sst.service_id)].update( + sst); +} + +/** + * Update the node cache. + * + * @param[in] cvs The data to update. + */ +void node_cache::update(neb::custom_variable_status const& cvs) { + if (cvs.host_id == 0) + return; + QMutexLocker lock(&_mutex); + if (cvs.service_id == 0) + _host_node_states[objects::node_id(cvs.host_id)].update(cvs); + else + _service_node_states[objects::node_id(cvs.host_id, cvs.service_id)].update( + cvs); +} + +/** + * Update the node cache. + * + * @param[in] ack The data to update. + */ +void node_cache::update(neb::acknowledgement const& ack) { + if (!ack.deletion_time.is_null()) + _acknowledgements.remove(objects::node_id(ack.host_id, ack.service_id)); + else + _acknowledgements[objects::node_id(ack.host_id, ack.service_id)] = ack; +} + +/** + * Update the node cache. + * + * @param[in] dwn The data to update. + */ +void node_cache::update(neb::downtime const& dwn) { + if (dwn.actual_end_time.is_null()) { + _downtimes[dwn.internal_id] = dwn; + _downtime_id_by_nodes.insert(objects::node_id(dwn.host_id, dwn.service_id), + dwn.internal_id); + } else { + _downtimes.remove(dwn.internal_id); + _downtime_id_by_nodes.remove(objects::node_id(dwn.host_id, dwn.service_id), + dwn.internal_id); + } +} + +/** + * Get a host from the node cache. + * + * @param[in] id The id of the host. + * + * @return The host from the node cache. + */ +node_cache::host_node_state const& node_cache::get_host( + objects::node_id id) const { + objects::node_id host_node_id(id.get_host_id()); + QHash::const_iterator found = + _host_node_states.find(host_node_id); + if (found == _host_node_states.end()) + throw(exceptions::msg() << "notification: host " << id.get_host_id() + << " was not found in cache"); + return (*found); +} + +/** + * Get a service from the service cache. + * + * @param[in] id The id of the service. + * + * @return The service from the node cache. + */ +node_cache::service_node_state const& node_cache::get_service( + objects::node_id id) const { + QHash::const_iterator found = + _service_node_states.find(id); + if (found == _service_node_states.end()) + throw(exceptions::msg() + << "notification: service (" << id.get_host_id() << ", " + << id.get_service_id() << " was not found in cache"); + return (*found); +} + +/** + * Is this node in downtime ? + * + * @param[in] node The node. + * + * @return True if this node is in downtime. + */ +bool node_cache::node_in_downtime(objects::node_id node) const { + return (_downtime_id_by_nodes.contains(node)); +} + +/** + * Return the number of active downtimes associated to a node. + * + * @param[in] node The node. + * + * @return Number of active downtimes associated to a node. + */ +uint32_t node_cache::node_downtimes(objects::node_id node) const { + return (_downtime_id_by_nodes.count(node)); +} + +/** + * Is this node acknowledged ? + * + * @param[in] node The node. + * + * @return True if this node was acknowledged. + */ +bool node_cache::node_acknowledged(objects::node_id node) const { + return (_acknowledgements.contains(node)); +} + +/** + * Prepare the serialization of all the data. + */ +void node_cache::_save_cache() { + std::deque > serialized_data; + + for (QHash::const_iterator + it = _host_node_states.begin(), + end = _host_node_states.end(); + it != end; ++it) + it->serialize(serialized_data); + for (QHash::const_iterator + it = _service_node_states.begin(), + end = _service_node_states.end(); + it != end; ++it) + it->serialize(serialized_data); + for (QHash::const_iterator + it = _acknowledgements.begin(), + end = _acknowledgements.end(); + it != end; ++it) + serialized_data.push_back(std::make_shared(*it)); + for (QHash::const_iterator it = _downtimes.begin(), + end = _downtimes.end(); + it != end; ++it) + serialized_data.push_back(std::make_shared(*it)); + + for (std::deque >::const_iterator + it = serialized_data.begin(), + end = serialized_data.end(); + it != end; ++it) + _cache->add(*it); +} diff --git a/centreon-broker/notification/src/notification_scheduler.cc b/centreon-broker/notification/src/notification_scheduler.cc new file mode 100644 index 00000000000..3497be873a3 --- /dev/null +++ b/centreon-broker/notification/src/notification_scheduler.cc @@ -0,0 +1,192 @@ +/* +** 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/notification/notification_scheduler.hh" +#include +#include +#include "com/centreon/broker/notification/node_cache.hh" +#include "com/centreon/broker/notification/state.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + * + * @param[in] st The state object. + * @param[in] cache The data cache object. + */ +notification_scheduler::notification_scheduler(state& st, node_cache& cache) + : _should_exit{false}, + _general_mutex{}, + _state(st), + _cache(cache), + _started_flag{false} {} + +/** + * Called by the notification thread when it starts. + */ +void notification_scheduler::run() { + while (1) { + // Lock the general mutex used by the notification scheduler. + std::unique_lock lock(_general_mutex); + + // Wait until the first action in the queue - or forever until awakened + // if the queue is empty. + time_t first_time = _queue.get_first_time(); + time_t now = ::time(NULL); + unsigned long wait_for = first_time == time_t(-1) + ? std::numeric_limits::max() + : (first_time >= now) ? (first_time - now) * 1000 + : 0; + log_v2::notification()->debug( + "notification: scheduler sleeping for {} seconds", wait_for / 1000.0); + + _general_condition.wait_for(lock, std::chrono::milliseconds(wait_for)); + + log_v2::notification()->debug("notification: scheduler waking up"); + + // The should exit flag was set - exit. + if (_should_exit) + break; + + // Process the actions and release the mutex. + _process_actions(); + } +} + +/** + * Start the notification scheduler and wait until it has started. + */ +void notification_scheduler::start() { + _thread = std::thread(¬ification_scheduler::run, this); + _started_flag = true; +} + +void notification_scheduler::wait() { + _thread.join(); + _started_flag = false; +} + +/** + * Ask gracefully for the notification thread to exit. + */ +void notification_scheduler::exit() throw() { + // Set the should exit flag. + { + std::lock_guard lock(_general_mutex); + _should_exit = true; + // Wake the notification scheduling thread. + _general_condition.notify_all(); + } +} + +/** + * @brief Add an action to the internal queue. + * + * Can be called outside or inside the notif thread context. + * + * @param at The time of the action. + * @param a The action. + */ +void notification_scheduler::add_action_to_queue(time_t at, action a) { + bool need_to_wake = false; + // Add the action to the queue. + { + std::lock_guard lock(_general_mutex); + // If we just replaced the first event, we need to wake the scheduling + // thread. + time_t first_time(_queue.get_first_time()); + if ((first_time > at) || ((time_t)-1 == first_time)) + need_to_wake = true; + _queue.run(at, a); + // Wake the notification scheduling thread if needed. + if (need_to_wake) + _general_condition.notify_all(); + } +} + +/** + * @brief Remove all the actions associated to a node. + * + * Called outside the notif thread context. + * + * @param[in] id The id of the node. + */ +void notification_scheduler::remove_actions_of_node(objects::node_id id) { + { + std::lock_guard lock(_general_mutex); + // Get all the action of a particular node. + time_t first_time = _queue.get_first_time(); + std::vector actions = _queue.get_actions_of_node(id); + // Iterate over the actions to remove them. + for (std::vector::iterator it(actions.begin()), + end(actions.end()); + it != end; ++it) + _queue.remove(**it); + // If we just deleted the first event, we need to wake + // the scheduling thread. + if (_queue.get_first_time() != first_time) + _general_condition.notify_all(); + } +} + +/** + * @brief Called repeatedly by the notification thread to process actions. + * + * This method releases the mutex as soon as possible to prevent long + * mutex locking. + */ +void notification_scheduler::_process_actions() { + // Move the global queue to a local queue and release the mutex. + // That way, we can add new actions in an external thread while this thread + // is processing those actions. + run_queue local_queue; + time_t now = ::time(NULL); + _queue.move_to_queue(local_queue, now); + _general_mutex.unlock(); + + // Iterate on the local queue. + for (run_queue::iterator it(local_queue.begin()), end(local_queue.end()); + it != end; ++it) { + // The action processing can add other actions to the queue. + std::vector > spawned_actions; + { + // Lock the state mutex. + std::unique_ptr lock(_state.read_lock()); + // Process the action. + it->second->process_action(_state, _cache, spawned_actions); + } + // Add the spawned action to the queue. + _schedule_actions(spawned_actions); + } +} + +/** + * Schedule several actions. + * + * @param[in] actions The actions to schedule. + */ +void notification_scheduler::_schedule_actions( + std::vector > const& actions) { + for (std::vector >::const_iterator + it(actions.begin()), + end(actions.end()); + it != end; ++it) + add_action_to_queue(it->first, it->second); +} diff --git a/centreon-broker/notification/src/objects/command.cc b/centreon-broker/notification/src/objects/command.cc new file mode 100644 index 00000000000..89e09b5ca72 --- /dev/null +++ b/centreon-broker/notification/src/objects/command.cc @@ -0,0 +1,186 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/objects/command.hh" +#include +#include +#include "com/centreon/broker/misc/string.hh" +#include "com/centreon/broker/notification/macro_generator.hh" +#include "com/centreon/broker/notification/state.hh" +#include "com/centreon/broker/notification/utilities/qhash_func.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +const QRegExp command::_macro_regex("\\$(\\w+)\\$"); + +// Forward declaration. +static void single_pass_replace(std::string& str, + macro_generator::macro_container const& macros); + +/** + * Constructor from a base command string. + * + * @param[in] base_command The command from which to construct this object. + */ +command::command(std::string const& base_command) + : _enable_shell(true), _base_command(base_command) {} + +/** + * Copy constructor. + * + * @param[in] obj The object to copy. + */ +command::command(command const& obj) { + command::operator=(obj); +} + +/** + * Assignment operator. + * + * @param[in] obj The object to copy. + * + * @return A reference to this object. + */ +command& command::operator=(command const& obj) { + if (this != &obj) { + _enable_shell = obj._enable_shell; + _name = obj._name; + _base_command = obj._base_command; + } + return (*this); +} + +/** + * Get the enable shell flag. + * + * @return True if we enable + */ +bool command::get_enable_shell() const throw() { + return (_enable_shell); +} + +/** + * Set the enable shell flag. + * + * @param[in] val The new value of the enable shell flag. + */ +void command::set_enable_shell(bool val) { + _enable_shell = val; +} + +/** + * Get the name of this command. + * + * @return The name of this command. + */ +std::string const& command::get_name() const throw() { + return (_name); +} + +/** + * Set the name of this command. + * + * @param[in] name The new name of this command. + */ +void command::set_name(std::string const& name) { + _name = name; +} + +/** + * Resolve this command. + * + * @return A string containing the resolved command. + */ +std::string command::resolve(contact::ptr const& cnt, + node::ptr const& n, + node_cache const& cache, + state const& st, + action const& act) { + // Match all the macros with the wonderful magic of RegExp. + QString base_command = QString::fromStdString(_base_command); + macro_generator::macro_container macros; + int index = 0; + while ((index = _macro_regex.indexIn(base_command, index)) != -1) { + macros.insert(_macro_regex.cap(1).toStdString(), ""); + index += _macro_regex.matchedLength(); + } + if (macros.empty()) + return (_base_command); + + log_v2::notification()->debug("notification: found {} macros", macros.size()); + + // Generate each macro. + try { + macro_generator generator; + generator.generate(macros, n->get_node_id(), *cnt, st, cache, act); + } catch (std::exception const& e) { + log_v2::notification()->error( + "notification: could not resolve some macro in command '{}': {}", _name, + e.what()); + } + + // Replace the macros by their values. + std::string resolved_command = _base_command; + single_pass_replace(resolved_command, macros); + + // If it needs to be launched into a shell, wrap it into a shell command. + // The command is correctly escaped in single quotes + // (no secure function doing that in our libraries, unfortunately). + // XXX: do the same for windows. + if (_enable_shell) { + misc::string::replace(resolved_command, "'", "'\''"); + resolved_command.insert(0, "sh -c '"); + resolved_command.append("'"); + } + + return (resolved_command); +} + +/** + * @brief Replace all the macros of the string in a single pass. + * + * Marginally faster, and don't mangle contents and values. + * + * @param[in] str The string. + * @param[in] macros The macros to replace. + */ +static void single_pass_replace( + std::string& str, + macro_generator::macro_container const& macros) { + std::vector > macro_list; + for (macro_generator::macro_container::iterator it(macros.begin()), + end(macros.end()); + it != end; ++it) { + std::string key("$"); + key.append(it.key()); + key.append("$"); + macro_list.push_back(std::make_pair(key, *it)); + } + + for (std::vector >::const_iterator + it(macro_list.begin()), + end(macro_list.end()); + it != end; ++it) { + size_t tmp(0); + while ((tmp = str.find(it->first, tmp)) != std::string::npos) { + str.replace(tmp, it->first.size(), it->second); + tmp += it->second.size(); + } + } +} diff --git a/centreon-broker/notification/src/objects/contact.cc b/centreon-broker/notification/src/objects/contact.cc new file mode 100644 index 00000000000..7e77eb8ae34 --- /dev/null +++ b/centreon-broker/notification/src/objects/contact.cc @@ -0,0 +1,87 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/objects/contact.hh" + +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + */ +contact::contact() : _id(0) {} + +/** + * Copy constructor. + * + * @param[in] obj The object to copy. + */ +contact::contact(contact const& obj) { + _id = obj._id; + _description = obj._description; +} + +/** + * Assignment operator. + * + * @param[in] obj The object to be copied. + * + * @return A reference to this object. + */ +contact& contact::operator=(contact const& obj) { + if (this != &obj) { + _id = obj._id; + _description = obj._description; + } + return (*this); +} + +/** + * Get the id of this contact. + * + * @return The id of this contact. + */ +uint32_t contact::get_id() const throw() { + return (_id); +} + +/** + * Set the id of this contact. + * + * @param[in] id The id of this contact. + */ +void contact::set_id(uint32_t id) { + _id = id; +} + +/** + * Get the description of this contact. + * + * @return The description of this contact. + */ +std::string const& contact::get_description() const throw() { + return (_description); +} + +/** + * Set the description of this contact. + * + * @param[in] desc The description of this contact. + */ +void contact::set_description(std::string const& desc) { + _description = desc; +} diff --git a/centreon-broker/notification/src/objects/defines.cc b/centreon-broker/notification/src/objects/defines.cc new file mode 100644 index 00000000000..c3aee53b89c --- /dev/null +++ b/centreon-broker/notification/src/objects/defines.cc @@ -0,0 +1,98 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/objects/defines.hh" + +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + */ +node_state::node_state() : value(ok) {} + +/** + * Copy constructor. + * + * @param[in] type The value to copy. + */ +node_state::node_state(state_type type) : value(type) {} + +/** + * Copy constructor. + * + * @param[in] type The value to copy. + */ +node_state::node_state(short val) : value((state_type)val) {} + +/** + * Copy constructor. + * + * @param[in] type The value to copy. + */ +node_state::node_state(int val) : value((state_type)val) {} + +/** + * Copy constructor. + * + * @param[in] type The value to copy. + */ +node_state::node_state(node_state const& st) : value(st.value) {} + +/** + * Assignment operator. + * + * @param[in] type The value to copy. + * + * @return A reference to this object. + */ +node_state& node_state::operator=(node_state const& st) { + if (this != &st) + value = st.value; + return (*this); +} + +/** + * Equality operator. + * + * @param[in] st The value to test for equality. + * + * @return True if equal. + */ +bool node_state::operator==(node_state const& st) const throw() { + return (value == st.value); +} + +/** + * Equality operator. + * + * @param[in] st The value to test for equality. + * + * @return True if equal. + */ +bool node_state::operator==(node_state::state_type type) const throw() { + return (value == type); +} + +/** + * Cast operator. + * + * @return The value casted to int. + */ +node_state::operator int() const throw() { + return ((int)(value)); +} diff --git a/centreon-broker/notification/src/objects/dependency.cc b/centreon-broker/notification/src/objects/dependency.cc new file mode 100644 index 00000000000..db3c48ddd48 --- /dev/null +++ b/centreon-broker/notification/src/objects/dependency.cc @@ -0,0 +1,275 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/objects/dependency.hh" +#include "com/centreon/broker/misc/string.hh" + +using namespace com::centreon::broker::notification::objects; + +const dependency::name_to_action dependency::_service_actions[] = { + {"o", service_ok}, + {"w", service_warning}, + {"u", service_unknown}, + {"c", service_critical}, + {"p", service_pending}}; + +const dependency::name_to_action dependency::_host_actions[] = { + {"o", host_up}, + {"d", host_down}, + {"u", host_unreachable}, + {"p", host_pending}}; + +/** + * Default constructor. + */ +dependency::dependency() + : _type(unknown), + _dependency_type(unknown_dependency), + _execution_failure_options(none), + _inherits_parent(false), + _notification_failure_options(none) {} + +/** + * Copy constructor. + * + * @param obj The object to copy. + */ +dependency::dependency(dependency const& obj) { + dependency::operator=(obj); +} + +/** + * Assignment operator. + * + * @param obj The object to copy. + * + * @return A reference to this object. + */ +dependency& dependency::operator=(dependency const& obj) { + if (this != &obj) { + _type = obj._type; + _dependency_period = obj._dependency_period; + _dependency_type = obj._dependency_type; + _execution_failure_options = obj._execution_failure_options; + _inherits_parent = obj._inherits_parent; + _notification_failure_options = obj._notification_failure_options; + } + return (*this); +} + +/** + * Return true if this dependency is a host dependency. + * + * @return True if this dependency is a host dependency. + */ +bool dependency::is_host_dependency() const throw() { + return (_type == host); +} + +/** + * Set if this dependency is a host dependency. + * + * @param val The new value of the host dependency flag. + */ +void dependency::set_is_host_dependency(bool val) throw() { + if (val) + _type = host; + else + _type = service; +} + +/** + * Return true if this dependency is a service dependency. + * + * @return True if this dependency is a service dependency. + */ +bool dependency::is_service_dependency() const throw() { + return (_type == service); +} + +/** + * Set if this dependency is a service dependency. + * + * @param val The new value of the service dependency flag. + */ +void dependency::set_is_service_dependency(bool val) throw() { + if (val) + _type = service; + else + _type = host; +} + +/** + * Get the period of the dependency. + * + * @return The name of period of the dependency. + */ +std::string const& dependency::get_period() const throw() { + return (_dependency_period); +} + +/** + * Set the period of the dependency. + * + * @param val The new value of the period of the dependency. + */ +void dependency::set_period(std::string const& val) { + _dependency_period = val; +} + +/** + * Get the kind of this dependency. + * + * @return The kind of this dependency. + */ +dependency::dependency_kind dependency::get_kind() const throw() { + return (_dependency_type); +} + +/** + * Set the kind of this dependency. + * + * @param val The new value of the kind of this dependency. + */ +void dependency::set_kind(dependency::dependency_kind val) throw() { + _dependency_type = val; +} + +/** + * Get the notification failure options. + * + * @return The notification failure options. + */ +dependency::action_on dependency::get_notification_failure_options() const + throw() { + return (_notification_failure_options); +} + +/** + * Set the notification failure options. + * + * @param val The new value of the notification failure options. + */ +void dependency::set_notification_failure_options(action_on val) throw() { + _notification_failure_options = val; +} + +/** + * Add a notification failure option to the set. + * + * @param val A notification failure option to add to the set. + */ +void dependency::set_notification_failure_option(action_on val) throw() { + _notification_failure_options = + (action_on)(_notification_failure_options | val); +} + +/** + * Check if a notification failure option is set. + * + * @param val The notification failure option to check. + * + * @return True if the notification failure option is set. + */ +bool dependency::is_notification_failure_option_set(action_on val) const + throw() { + return (_notification_failure_options & val); +} + +/** + * Return true if the dependency inherit from its parent. + * + * @return True if the dependency inherit from its parent. + */ +bool dependency::get_inherits_parent() const throw() { + return (_inherits_parent); +} + +/** + * Set if the dependency inherit from its parent. + * + * @param val The new value of the inherit from its parent flag. + */ +void dependency::set_inherits_parent(bool val) throw() { + _inherits_parent = val; +} + +dependency::action_on dependency::get_execution_failure_options() const + throw() { + return (_execution_failure_options); +} + +void dependency::set_execution_failure_options(action_on val) throw() { + _execution_failure_options = val; +} + +void dependency::set_execution_failure_option(action_on val) throw() { + _execution_failure_options = (action_on)(_execution_failure_options | val); +} + +bool dependency::is_execution_failure_option_set(action_on val) throw() { + return (_execution_failure_options & val); +} + +void dependency::parse_notification_failure_options(std::string const& line) { + _parse_failure_options(line, &dependency::set_notification_failure_option); +} + +void dependency::parse_execution_failure_options(std::string const& line) { + _parse_failure_options(line, &dependency::set_execution_failure_option); +} + +void dependency::_parse_failure_options( + std::string const& line, + void (dependency::*func_to_call)(action_on)) { + // The options are type dependent. If we don't know our own type, then + // we shouldn't try to parse anything to begin with. + if (_type == unknown) + return; + + if (line == "n") + set_notification_failure_options(none); + else { + std::vector tokens; + misc::string::split(line, tokens, ','); + + static int host_actions_size = + sizeof(_host_actions) / sizeof(_host_actions[0]); + static int service_actions_size = + sizeof(_service_actions) / sizeof(_service_actions[0]); + if (_type == host) { + for (std::vector::const_iterator it(tokens.begin()), + end(tokens.end()); + it != end; ++it) { + for (int i = 0; i < host_actions_size; ++i) { + if (*it == _host_actions[i].name) + (this->*func_to_call)(_host_actions[i].action); + } + } + } else { + for (std::vector::const_iterator it(tokens.begin()), + end(tokens.end()); + it != end; ++it) { + for (int i = 0; i < service_actions_size; ++i) { + if (*it == _service_actions[i].name) + (this->*func_to_call)(_service_actions[i].action); + } + } + } + } +} diff --git a/centreon-broker/notification/src/objects/node.cc b/centreon-broker/notification/src/objects/node.cc new file mode 100644 index 00000000000..2af931977cc --- /dev/null +++ b/centreon-broker/notification/src/objects/node.cc @@ -0,0 +1,248 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/objects/node.hh" + +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + */ +node::node() + : _notification_number(0), + _notifications_enabled(true), + _notification_interval(0), + _last_notification_time(0), + _hard_state(), + _soft_state() {} + +/** + * Copy constructor. + * + * @param[in] obj The object to be copied. + */ +node::node(node const& obj) { + node::operator=(obj); +} + +/** + * Assignment operator. + * + * @param[in] obj The object to be copied. + * + * @return A reference to this object. + */ +node& node::operator=(node const& obj) { + if (this != &obj) { + _notification_number = obj._notification_number; + _notifications_enabled = obj._notifications_enabled; + _notification_interval = obj._notification_interval; + _last_notification_time = obj._last_notification_time; + _hard_state = obj._hard_state; + _soft_state = obj._soft_state; + _parents = obj._parents; + _notification_period = obj._notification_period; + } + return *this; +} + +/** + * @brief Get the notification number of this node. + * + * Used internally by the notification engine. + * + * @return The notification number. + */ +int node::get_notification_number() const throw() { + return (_notification_number); +} + +/** + * @brief Set the notification number of this node. + * + * Used internally by the notification engine. + * + * @param[in] value The value to set. + */ +void node::set_notification_number(int value) { + _notification_number = value; +} + +/** + * Get the time of the last notification. + * + * @return The time of the last notification. + */ +time_t node::get_last_notification_time() const throw() { + return (_last_notification_time); +} + +/** + * Set the time of the last notification. + * + * @param[in] value The time of the last notification. + */ +void node::set_last_notification_time(time_t value) { + _last_notification_time = value; +} + +/** + * Get the hard state of this node. + * + * @return The hard state of this node. + */ +node_state node::get_hard_state() const throw() { + return (_hard_state); +} + +/** + * Set the hard state of this node. + * + * @param[in] value The new value for the hard state of this node. + */ +void node::set_hard_state(node_state value) { + _hard_state = value; +} + +/** + * Get the soft state of this node. + * + * @return The soft state of this node. + */ +node_state node::get_soft_state() const throw() { + return (_soft_state); +} + +/** + * Set the soft state of this node. + * + * @param[în] value The new value for the soft state of this node. + */ +void node::set_soft_state(node_state value) { + _soft_state = value; +} + +/** + * Get this node id. + * + * @return This node id. + */ +node_id node::get_node_id() const throw() { + return (_id); +} + +/** + * Set this node id. + * + * @param[in] id The new value of this node id. + */ +void node::set_node_id(node_id id) throw() { + _id = id; +} + +/** + * Get the correlated parents of this node. + * + * @return A set containing the correlated parents of this node. + */ +std::set const& node::get_parents() const throw() { + return (_parents); +} + +/** + * Add a parent to the correlated parent set of this node. + * + * @param[in] id The id of the parent to add. + */ +void node::add_parent(node_id id) { + _parents.insert(id); +} + +/** + * Remove a parent to the correlated parent set of this node. + * + * @param[in] id The id of the parent to remove. + */ +void node::remove_parent(node_id id) { + std::set::iterator it(_parents.find(id)); + if (it != _parents.end()) + _parents.erase(it); +} + +/** + * Return true if this node has at least a correlated parent. + * + * @return True if this node has at least a correlated parent. + */ +bool node::has_parent() const throw() { + return (!_parents.empty()); +} + +/** + * Return true if the notifications are enabled for this node. + * + * @return True if the notifications are enabled for this node. + */ +bool node::get_notifications_enabled() const throw() { + return (_notifications_enabled); +} + +/** + * Set the notification enabled flag. + * + * @param[in] enable True if the notification are enabled for this node. + */ +void node::set_notifications_enabled(bool enable) throw() { + _notifications_enabled = enable; +} + +/** + * Get the notification timeperiod attached to this node. + * + * @return The notification timeperiod of this node. + */ +std::string const& node::get_notification_timeperiod() const throw() { + return (_notification_period); +} + +/** + * Set the notification timeperiod attached to this node. + * + * @param[in] tp The notification timeperiod attached to this node. + */ +void node::set_notification_timeperiod(std::string const& tp) { + _notification_period = tp; +} + +/** + * Get the notification interval. + * + * @return The notification interval. + */ +double node::get_notification_interval() const throw() { + return (_notification_interval); +} + +/** + * Set the notification interval. + * + * @param[in] val The new value for the notification interval. + */ +void node::set_notification_interval(double val) throw() { + _notification_interval = val; +} diff --git a/centreon-broker/notification/src/objects/node_id.cc b/centreon-broker/notification/src/objects/node_id.cc new file mode 100644 index 00000000000..27ecd195502 --- /dev/null +++ b/centreon-broker/notification/src/objects/node_id.cc @@ -0,0 +1,153 @@ +/* +** 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/notification/objects/node_id.hh" +#include +#include + +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + */ +node_id::node_id() : _host_id(0), _service_id(0) {} + +/** + * Copy constructor. + * + * @param[in] obj The object to copy. + */ +node_id::node_id(node_id const& obj) { + node_id::operator=(obj); +} + +/** + * Assignment operator. + * + * @param[in] obj The object to copy. + * + * @return A reference to this object. + */ +node_id& node_id::operator=(node_id const& obj) { + if (this != &obj) { + _host_id = obj._host_id; + _service_id = obj._service_id; + } + return (*this); +} + +/** + * Constructor given host and service id. + * + * @param[in] host_id The host id of this node. 0 if none. + * @param[in] service_id The service id of this node. 0 if none. + */ +node_id::node_id(uint32_t host_id, uint32_t service_id) + : _host_id(host_id), _service_id(service_id) {} + +/** + * Comparison operator. + * + * @param obj The object to compare with. + * + * @return True if this object is lesser than the other. + */ +bool node_id::operator<(node_id const& obj) const throw() { + if (_host_id != obj._host_id) + return (_host_id < obj._host_id); + else + return (_service_id < obj._service_id); +} + +/** + * Equality operator. + * + * @param[in] obj The object to compare with. + * + * @return True if this object is equal to the other. + */ +bool node_id::operator==(node_id const& obj) const throw() { + return (_host_id == obj._host_id && _service_id == obj._service_id); +} + +/** + * Inequality operator. + * + * @param[in] obj The object to compare with. + * + * @return True if the objects are inequal. + */ +bool node_id::operator!=(node_id const& obj) const throw() { + return (!node_id::operator==(obj)); +} + +/** + * Get the host id of this node. 0 if none. + * + * @return The host id of this node. 0 if none. + */ +uint32_t node_id::get_host_id() const throw() { + return (_host_id); +} + +/** + * Get the service id of this node. 0 if none. + * + * @return The service id of this node. 0 if none. + */ +uint32_t node_id::get_service_id() const throw() { + return (_service_id); +} + +/** + * Is this node a host? + * + * @return True if this node is a host. + */ +bool node_id::is_host() const throw() { + return (_service_id == 0); +} + +/** + * Is this node a service? + * + * @return True if this node is a service. + */ +bool node_id::is_service() const throw() { + return (_service_id != 0); +} + +/** + * Return the node_id of the host associated with this node. + * + * @return The node_id of the host associated with this node. + */ +node_id node_id::to_host() const throw() { + return (node_id(_host_id)); +} + +/** + * QHash function for hash and sets. + * + * @param[in] id A node id. + * + * @return An identifier for this node_id usable in hashtable. + */ +uint com::centreon::broker::notification::objects::qHash(node_id id) { + return (qHash(qMakePair(id.get_host_id(), id.get_service_id()))); +} diff --git a/centreon-broker/notification/src/objects/notification_method.cc b/centreon-broker/notification/src/objects/notification_method.cc new file mode 100644 index 00000000000..e5321ccfe43 --- /dev/null +++ b/centreon-broker/notification/src/objects/notification_method.cc @@ -0,0 +1,241 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/objects/notification_method.hh" + +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + */ +notification_method::notification_method() + : _command_id(0), _interval(0), _start(0), _end(0) {} + +/** + * Copy constructor. + * + * @param[in] obj The object to copy. + */ +notification_method::notification_method(notification_method const& obj) { + notification_method::operator=(obj); +} + +/** + * Assignment operator. + * + * @param[in] obj The object to copy. + * + * @return A reference to this object. + */ +notification_method& notification_method::operator=( + notification_method const& obj) { + if (this != &obj) { + _name = obj._name; + _command_id = obj._command_id; + _interval = obj._interval; + _status = obj._status; + _types = obj._types; + _start = obj._start; + _end = obj._end; + } + return (*this); +} + +/** + * Get the name of this notification method. + * + * @return The name of this notification method. + */ +std::string const& notification_method::get_name() const throw() { + return (_name); +} + +/** + * Set the name of this notification method. + * + * @param[in] val The new name of this notification method. + */ +void notification_method::set_name(std::string const& val) { + _name = val; +} + +/** + * Get the id of the command associated with this method. + * + * @return The id of the command associated with this method. + */ +uint32_t notification_method::get_command_id() const throw() { + return (_command_id); +} + +/** + * Set the id of the command associated with this method. + * + * @param[in] id The new id of the command associated with this method. + */ +void notification_method::set_command_id(uint32_t id) throw() { + _command_id = id; +} + +/** + * Get the interval of this notification method. + * + * @return The interval of this notification method. + */ +uint32_t notification_method::get_interval() const throw() { + return (_interval); +} + +/** + * Set the interval of this notification method. + * + * @param[in] val The new interval of this notification method. + */ +void notification_method::set_interval(uint32_t val) throw() { + _interval = val; +} + +/** + * Get the status when this method should be executed. + * + * @return The status when this method should be executed. + */ +std::string const& notification_method::get_status() const throw() { + return (_status); +} + +/** + * Set the status when this method should be executed. + * + * @param[in] val The new status when this method should be executed. + */ +void notification_method::set_status(std::string const& val) { + _status = val; +} + +/** + * Get the types when this method should be executed. + * + * @return The types when this method should be executed. + */ +std::string const& notification_method::get_types() const throw() { + return (_types); +} + +/** + * Set the types when this method should be executed. + * + * @param[in] val The new types when this method should be executed. + */ +void notification_method::set_types(std::string const& val) { + _types = val; +} + +/** + * Get the start of the escalation range of this method. + * + * @return The start of the escalation range of this method. + */ +uint32_t notification_method::get_start() const throw() { + return (_start); +} + +/** + * Set the start of the escalation range of this method. + * + * @param[in] val The new start of the escalation range of this method. + */ +void notification_method::set_start(uint32_t val) throw() { + _start = val; +} + +/** + * Get the end of the escalation range of this method. + * + * @return The end of the escalation range of this method. + */ +uint32_t notification_method::get_end() const throw() { + return (_end); +} + +/** + * Set the end of the escalation range of this method. + * + * @param[in] val The new end of the escalation range of this method. + */ +void notification_method::set_end(uint32_t val) throw() { + _end = val; +} + +/** + * Check if the status allow a notification. + * + * @param[in] state State of the node. + * @param[in] is_service Is the node a service? + * + * @return True if the notification is allowed. + */ +bool notification_method::should_be_notified_for(node_state state, + bool is_service) const { + if (state == node_state::ok) + return (_status.find_first_of('o') != std::string::npos); + if (is_service) { + if (state == node_state::service_warning) + return (_status.find_first_of('w') != std::string::npos); + else if (state == node_state::service_critical) + return (_status.find_first_of('c') != std::string::npos); + else if (state == node_state::service_unknown) + return (_status.find_first_of('u') != std::string::npos); + } else { + if (state == node_state::host_down) + return (_status.find_first_of('d') != std::string::npos); + else if (state == node_state::host_unreachable) + return (_status.find_first_of('n') != std::string::npos); + } + return (false); +} + +/** + * Check if the types allow a notification. + * + * @param[in] type The type of the notification. + * + * @return True if the notification is allowed. + */ +bool notification_method::should_be_notified_for( + action::action_type type) const { + if (type == action::notification_attempt) + return (_types.find_first_of('n') != std::string::npos); + else if (type == action::notification_up) + return (_types.find_first_of('r') != std::string::npos); + else if (type == action::notification_ack) + return (_types.find_first_of('a') != std::string::npos); + else if (type == action::notification_downtime) + return (_types.find_first_of('d') != std::string::npos); + else + return (false); +} + +/** + * Check if the notification is valid even if the node is correlated. + * + * @return True if the notification is still valid for a correlated node. + */ +bool notification_method::should_be_notified_when_correlated() const { + return (_types.find_first_of('c') != std::string::npos); +} diff --git a/centreon-broker/notification/src/objects/notification_rule.cc b/centreon-broker/notification/src/objects/notification_rule.cc new file mode 100644 index 00000000000..617636f83a8 --- /dev/null +++ b/centreon-broker/notification/src/objects/notification_rule.cc @@ -0,0 +1,143 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/objects/notification_rule.hh" + +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + */ +notification_rule::notification_rule() + : _id(0), _method_id(0), _timeperiod_id(0), _contact_id(0) {} + +/** + * Copy constructor. + * + * @param[in] obj The object to copy. + */ +notification_rule::notification_rule(notification_rule const& obj) { + notification_rule::operator=(obj); +} + +/** + * Assignment operator. + * + * @param[in] obj The object to copy. + * + * @return A reference to this object. + */ +notification_rule& notification_rule::operator=(notification_rule const& obj) { + if (this != &obj) { + _id = obj._id; + _method_id = obj._method_id; + _timeperiod_id = obj._timeperiod_id; + _contact_id = obj._contact_id; + _node_id = obj._node_id; + } + return (*this); +} + +/** + * Get the id of this notification rule. + * + * @return This rule id. + */ +uint32_t notification_rule::get_id() { + return (_id); +} + +/** + * Set the id of this notification rule. + * + * @param[in] id The new id of this rule. + */ +void notification_rule::set_id(uint32_t id) { + _id = id; +} + +/** + * Get the id of the method associated with this rule. + * + * @return The id of the method associated with this rule. + */ +uint32_t notification_rule::get_method_id() const throw() { + return (_method_id); +} + +/** + * Set the id of the method associated with this rule. + * + * @param[in] val The new id the method associated with this rule. + */ +void notification_rule::set_method_id(uint32_t val) throw() { + _method_id = val; +} + +/** + * Get the id of the timeperiod associated with this rule. + * + * @return The id of the timeperiod associated with this rule. + */ +uint32_t notification_rule::get_timeperiod_id() const throw() { + return (_timeperiod_id); +} + +/** + * Set the id of the timeperiod associated with this rule. + * + * @param[in] val The new id of the timeperiod associated with this rule. + */ +void notification_rule::set_timeperiod_id(uint32_t val) throw() { + _timeperiod_id = val; +} + +/** + * Get the id of the contact associated with this rule. + * + * @return The id of the contact associated with this rule. + */ +uint32_t notification_rule::get_contact_id() const throw() { + return (_contact_id); +} +/** + * Set the id of the contact associated with this rule. + * + * @param[in] val The new id of the contact associated with this rule. + */ +void notification_rule::set_contact_id(uint32_t val) throw() { + _contact_id = val; +} + +/** + * Get the id of the node associated with this rule. + * + * @return The id of the node associated with this rule. + */ +node_id notification_rule::get_node_id() const throw() { + return (_node_id); +} + +/** + * Set the id of the node associated with this rule. + * + * @param[in] val The new id of the node associated with this rule. + */ +void notification_rule::set_node_id(node_id val) throw() { + _node_id = val; +} diff --git a/centreon-broker/notification/src/process.cc b/centreon-broker/notification/src/process.cc new file mode 100644 index 00000000000..76e10686cc1 --- /dev/null +++ b/centreon-broker/notification/src/process.cc @@ -0,0 +1,171 @@ +/* +** Copyright 2009-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/notification/process.hh" +#include +#include +#include "com/centreon/broker/notification/process_manager.hh" + +using namespace com::centreon::broker::notification; + +/** + * Constructor. + * + * @param[in] timeout The timeout of this process, default 0 (none). + */ +process::process(int timeout /* = 0 */) + : _timeout(timeout), + _process(new QProcess), + _in_error(false), + _exit_code(-1) {} + +/** + * Get the timeout of this process. + * + * @return The timeout of this process. + */ +uint32_t process::get_timeout() const throw() { + return (_timeout); +} + +/** + * Is this process running? + * + * @return True if this process is running. + */ +bool process::is_running() const { + return (_process->state() == QProcess::Running); +} + +/** + * Has this process timeouted? + * + * @return True if this process has timeouted. + */ +bool process::is_timeout() const throw() { + return (_timeout > 0 ? difftime(time(NULL), _start_time) > _timeout : 0); +} + +/** + * Kill this process. + */ +void process::kill() { + if (is_running()) + _process->kill(); +} + +/** + * Get any error of the process. + * + * @param[out] exit_code The exit code of the process. + * @param[out] error_output The standard error output of the process. + * + * @return True if an error ocurred. + */ +bool process::get_error(int& exit_code, std::string& error_output) { + if (_in_error) { + exit_code = _exit_code; + error_output = _error_output; + return (true); + } + return (false); +} + +/** + * @brief Start this process with a command and an optional process manager. + * + * If a process manager is given, the process manager will manage + * process timeout, process termination, and process freeing. + * + * Else, the process will blocks until the end of its execution. + * + * @param[in] program The program to execute, with its arguments. + * @param[in,out] manager The manager to which register the process. + * + * @return True of the process was started. + */ +bool process::exec(std::string const& program, + process_manager* manager /* = NULL */) { + if (is_running()) + return (false); + + time(&_start_time); + + if (manager) { + _process->moveToThread(&manager->get_thread()); + moveToThread(&manager->get_thread()); + QProcess::connect(this, SIGNAL(finished(process&)), manager, + SLOT(process_finished(process&))); + if (_timeout != 0) { + QTimer* timer(new QTimer(this)); + timer->setSingleShot(true); + connect(this, SIGNAL(timeouted(process&)), manager, + SLOT(process_timeouted(process&))); + connect(timer, SIGNAL(timeout()), this, SLOT(timeouted())); + } + QMetaObject::invokeMethod(this, "start", Qt::QueuedConnection, + Q_ARG(QString, program.c_str())); + } else { + return (_process->execute(program.c_str()) == 0); + } + return (true); +} + +/** + * Start the process. + * + * @param[in] command_line The command to execute. + */ +void process::start(QString const& command_line) { + QProcess::connect(_process.get(), + SIGNAL(QProcess::finished(int, QProcess::ExitStatus)), this, + SLOT(finished())); + QProcess::connect(_process.get(), + SIGNAL(QProcess::error(QProcess::ProcessError)), this, + SLOT(error())); + _process->start(command_line); + _process->closeWriteChannel(); + _process->closeReadChannel(QProcess::StandardOutput); +} + +/** + * The process is in an error state. + */ +void process::error() { + _in_error = true; + _error = _process->error(); +} + +/** + * The process was finished. + */ +void process::finished() { + _exit_code = _process->exitCode(); + _status = _process->exitStatus(); + if (_exit_code != 0 || _status == QProcess::CrashExit) + _in_error = true; + _error_output = _process->readAllStandardError().data(); + emit finished(*this); +} + +/** + * The process timeouted. + */ +void process::timeouted() { + emit timeouted(*this); +} diff --git a/centreon-broker/notification/src/process_manager.cc b/centreon-broker/notification/src/process_manager.cc new file mode 100644 index 00000000000..8e44160ea42 --- /dev/null +++ b/centreon-broker/notification/src/process_manager.cc @@ -0,0 +1,129 @@ +/* +** Copyright 2009-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/notification/process_manager.hh" +#include +#include "com/centreon/broker/notification/process.hh" + +using namespace com::centreon::broker::notification; + +process_manager* process_manager::_instance_ptr = 0; + +/** + * Get the singleton. + * + * @return The singleton. + */ +process_manager& process_manager::instance() { + if (!_instance_ptr) { + _instance_ptr = new process_manager; + _instance_ptr->_thread->start(); + } + return *_instance_ptr; +} + +/** + * Release (destroy and free) the singleton. Wait until the thread termination. + */ +void process_manager::release() { + if (_instance_ptr) { + _instance_ptr->_thread->exit(0); + _instance_ptr->_thread->wait(); + delete _instance_ptr; + _instance_ptr = 0; + } +} + +/** + * @brief Create and execute a process. + * + * Thread safe in and out the process manager thread. + * + * @param[in] command The command to be executed. + * @param[in] timeout The timeout of the command. + */ +void process_manager::create_process(std::string const& command, + uint32_t timeout) { + // No memory leak possible because we set the parent of the process as us. + process* pr(new process(timeout)); + + { + std::lock_guard lock(_process_list_mutex); + pr->moveToThread(_thread.get()); + pr->setParent(this); + _process_list.insert(pr); + } + + pr->exec(command, this); +} + +/** + * Default constructor. + */ +process_manager::process_manager() : _process_list_mutex{} { + _thread.reset(new QThread); + moveToThread(_thread.get()); +} + +/** + * @brief A process was finished: reap the finished processes. + * + * It is always executed from the QT event loop of the process manager thread. + * + * @param[in] process The process that has finished execution. + */ +void process_manager::process_finished(process& pr) { + log_v2::notification()->debug("notification: a process has finished"); + + std::string error_output; + int exit_code; + if (pr.get_error(exit_code, error_output)) + log_v2::notification()->error( + "notification: error while executing a process: {}", error_output); + + std::lock_guard lock(_process_list_mutex); + + std::set::iterator found(_process_list.find(&pr)); + if (found != _process_list.end()) { + delete *found; + _process_list.erase(found); + } +} + +/** + * @brief A process was timeouted: reap the timeouted processes. + * + * It is always executed from the QT event loop of the process manager thread. + * + * @param[in] process The process that has finished timeouted. + */ +void process_manager::process_timeouted(process& process) { + log_v2::notification()->debug("notification: a process has timeouted"); + + process.kill(); + process_finished(process); +} + +/** + * Get the thread of this process manager. + * + * @return The thread of this process manager. + */ +QThread& process_manager::get_thread() { + return (*_thread); +} diff --git a/centreon-broker/notification/src/run_queue.cc b/centreon-broker/notification/src/run_queue.cc new file mode 100644 index 00000000000..972d1dee044 --- /dev/null +++ b/centreon-broker/notification/src/run_queue.cc @@ -0,0 +1,196 @@ +/* +** Copyright 2009-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/notification/run_queue.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + */ +run_queue::run_queue() {} + +/** + * Copy constructor. + * + * @param obj The object to be copied. + */ +run_queue::run_queue(run_queue const& obj) { + run_queue::operator=(obj); +} + +/** + * Assignment operator. + * + * @param obj The object to be copied. + * + * @return A reference to this object. + */ +run_queue& run_queue::operator=(run_queue const& obj) { + if (this != &obj) { + _action_set = obj._action_set; + _rebuild_set(); + } + return (*this); +} + +/** + * Rebuild the run_queue caches from the set of action. + */ +void run_queue::_rebuild_set() { + for (std::set::iterator it(_action_set.begin()), + end(_action_set.end()); + it != end; ++it) { + _action_by_time.insert(std::make_pair(it->get_at(), &*it)); + _action_by_node.insert(std::make_pair(it->get_node_id(), &*it)); + } +} + +/** + * Move the content of this queue to another queue. + * + * @param[out] obj The object where to move the content of this queue. + * @param[in] until The max time of all moved object. + */ +void run_queue::move_to_queue(run_queue& obj, time_t until) { + for (iterator it(begin()), it_end(end()); + it != it_end && it->first <= until;) { + obj.run(it->first, *it->second); + iterator tmp = it; + ++it; + remove(*tmp->second); + } +} + +/** + * Add an action to the run_queue, to be runned at a specified time. + * + * @param at The specified time to run the action. + * @param a The action to run. + */ +void run_queue::run(time_t at, action a) { + a.set_at(at); + + std::pair::iterator, bool> res = _action_set.insert(a); + + _action_by_node.insert(std::make_pair(a.get_node_id(), &*res.first)); + _action_by_time.insert(std::make_pair(at, &*res.first)); +} + +/** + * Get an iterator to the beginning of the run_queue. + * + * @return An iterator to the beginning of the run_queue. + */ +run_queue::iterator run_queue::begin() { + return (_action_by_time.begin()); +} + +/** + * Get a const iterator to the beginning of the run_queue. + * + * @return A const iterator to the beginning of the run_queue. + */ +run_queue::const_iterator run_queue::begin() const { + return (_action_by_time.begin()); +} + +/** + * Get an iterator to the end of the run_queue. + * + * @return An iterator to the end of the run_queue. + */ +run_queue::iterator run_queue::end() { + return (_action_by_time.end()); +} + +/** + * Get a const iterator to the end of the run_queue. + * + * @return A const iterator to the end of the run_queue. + */ +run_queue::const_iterator run_queue::end() const { + return (_action_by_time.end()); +} + +/** + * Get the time of the next action, or time_t(-1) if no action. + * + * @return The time of the next action, or time_t(-1) if no action. + */ +time_t run_queue::get_first_time() const throw() { + if (_action_by_time.empty()) + return (time_t(-1)); + else + return (_action_by_time.begin()->first); +} + +/** + * Remove the next action. + */ +void run_queue::remove_first() { + if (!_action_by_time.empty()) + remove(*_action_by_time.begin()->second); +} + +void run_queue::remove(action const& a) { + std::set::iterator it = _action_set.find(a); + if (it == _action_set.end()) + return; + + const action* ptr = &*it; + + // Erase from _action_by_node + std::pair::iterator, + std::multimap::iterator> + node_range = _action_by_node.equal_range(ptr->get_node_id()); + + for (; node_range.first != node_range.second; ++node_range.first) + if (node_range.first->second == ptr) { + _action_by_node.erase(node_range.first); + break; + } + + // Erase from _action_by_time + std::pair time_range = + _action_by_time.equal_range(ptr->get_at()); + + for (; time_range.first != time_range.second; ++time_range.first) + if (time_range.first->second == ptr) { + _action_by_time.erase(time_range.first); + break; + } +} + +/** + * Get all the actions of a node. + * + * @param[in] id The node id. + * + * @return All the actions associated to this node. + */ +std::vector run_queue::get_actions_of_node(objects::node_id id) { + std::vector ret; + std::pair::iterator, + std::multimap::iterator> + node_range = _action_by_node.equal_range(id); + for (; node_range.first != node_range.second; ++node_range.first) + ret.push_back(node_range.first->second); + return (ret); +} diff --git a/centreon-broker/notification/src/state.cc b/centreon-broker/notification/src/state.cc new file mode 100644 index 00000000000..e45a4c80bf5 --- /dev/null +++ b/centreon-broker/notification/src/state.cc @@ -0,0 +1,391 @@ +/* +** Copyright 2009-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/notification/state.hh" +#include "com/centreon/broker/notification/utilities/data_loggers.hh" +#include "com/centreon/broker/notification/utilities/qhash_func.hh" + +#include "com/centreon/broker/notification/builders/command_by_id_builder.hh" +#include "com/centreon/broker/notification/builders/composed_command_builder.hh" +#include "com/centreon/broker/notification/builders/composed_contact_builder.hh" +#include "com/centreon/broker/notification/builders/composed_dependency_builder.hh" +#include "com/centreon/broker/notification/builders/composed_node_builder.hh" +#include "com/centreon/broker/notification/builders/composed_notification_method_builder.hh" +#include "com/centreon/broker/notification/builders/composed_notification_rule_builder.hh" +#include "com/centreon/broker/notification/builders/composed_timeperiod_builder.hh" +#include "com/centreon/broker/notification/builders/contact_by_id_builder.hh" +#include "com/centreon/broker/notification/builders/dependency_by_node_id_builder.hh" +#include "com/centreon/broker/notification/builders/global_macro_builder.hh" +#include "com/centreon/broker/notification/builders/node_by_node_id_builder.hh" +#include "com/centreon/broker/notification/builders/node_set_builder.hh" +#include "com/centreon/broker/notification/builders/notification_method_by_id_builder.hh" +#include "com/centreon/broker/notification/builders/notification_rule_by_id_builder.hh" +#include "com/centreon/broker/notification/builders/notification_rule_by_node_builder.hh" +#include "com/centreon/broker/notification/builders/timeperiod_by_id_builder.hh" +#include "com/centreon/broker/notification/builders/timeperiod_linker.hh" +#include "com/centreon/broker/time/timeperiod.hh" + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; + +/** + * Default constructor. + */ +state::state() : _state_mutex(QReadWriteLock::Recursive) {} + +/** + * Copy constructor. + * + * @param obj The obj to copy. + */ +state::state(state const& obj) { + state::operator=(obj); +} + +/** + * Assignment operator. + * + * @param obj The obj to copy. + * + * @return A reference to this object. + */ +state& state::operator=(state const& obj) { + if (this != &obj) { + _nodes = obj._nodes; + _node_by_id = obj._node_by_id; + _commands = obj._commands; + _contacts = obj._contacts; + _contact_infos = obj._contact_infos; + _dependency_by_child_id = obj._dependency_by_child_id; + _dependency_by_parent_id = obj._dependency_by_parent_id; + _timeperiod_by_id = obj._timeperiod_by_id; + _notification_methods = obj._notification_methods; + _notification_rules_by_node = obj._notification_rules_by_node; + _notification_rule_by_id = obj._notification_rule_by_id; + _date_format = obj._date_format; + _global_constant_macros = obj._global_constant_macros; + } + return (*this); +} + +/** + * Get the objects from the db. + */ +void state::update_objects_from_db(mysql& centreon_db) { + // Acquire mutex. + QWriteLocker lock(&_state_mutex); + + // Remove old objects. + _nodes.clear(); + _node_by_id.clear(); + _commands.clear(); + _contacts.clear(); + _contact_infos.clear(); + _dependency_by_child_id.clear(); + _dependency_by_parent_id.clear(); + _timeperiod_by_id.clear(); + _notification_methods.clear(); + _notification_rules_by_node.clear(); + _notification_rule_by_id.clear(); + _global_constant_macros.clear(); + + // Get new objects + { + // Get nodes. + node_loader node; + composed_node_builder composed; + node_set_builder set_builder(_nodes); + node_by_node_id_builder by_node_id_builder(_node_by_id); + composed.push_back(set_builder); + composed.push_back(by_node_id_builder); + node.load(¢reon_db, &composed); + } + { + // Get commands. + command_loader command; + composed_command_builder composed; + command_by_id_builder by_id_builder(_commands); + composed.push_back(by_id_builder); + command.load(¢reon_db, &composed); + } + { + // Get contacts. + contact_loader contact; + composed_contact_builder composed; + contact_by_id_builder by_id_builder(_contacts, _contact_infos); + composed.push_back(by_id_builder); + contact.load(¢reon_db, &composed); + } + { + // Get dependencies. + dependency_loader dependency; + composed_dependency_builder composed; + dependency_by_node_id_builder by_node_builder(_dependency_by_child_id, + _dependency_by_parent_id); + composed.push_back(by_node_builder); + dependency.load(¢reon_db, &composed); + } + { + // Get timeperiods. + timeperiod_loader timeperiod; + composed_timeperiod_builder composed; + timeperiod_by_id_builder by_id_builder(_timeperiod_by_id); + timeperiod_linker linker; + composed.push_back(by_id_builder); + composed.push_back(linker); + timeperiod.load(¢reon_db, &composed); + } + { + // Get notification methods. + notification_method_loader nml; + composed_notification_method_builder composed; + notification_method_by_id_builder by_id_builder(_notification_methods); + composed.push_back(by_id_builder); + nml.load(¢reon_db, &composed); + } + { + // Get notification rules. + notification_rule_loader nrl; + composed_notification_rule_builder composed; + notification_rule_by_node_builder by_node_builder( + _notification_rules_by_node); + notification_rule_by_id_builder by_id_builder(_notification_rule_by_id); + composed.push_back(by_node_builder); + composed.push_back(by_id_builder); + nrl.load(¢reon_db, &composed); + } + { + // Get global constant macros. + macro_loader ml; + global_macro_builder builder(_global_constant_macros, _date_format); + ml.load(¢reon_db, &builder); + } + +#ifndef NDEBUG + // data_logger::log_container("_nodes", _nodes); + // data_logger::log_container("_node_by_id", _node_by_id); + // data_logger::log_container("_commands", _commands); + // data_logger::log_container("_contacts", _contacts); + // data_logger::log_container("_dependency_by_child_id", + // _dependency_by_child_id); + // data_logger::log_container("_dependency_by_parent_id", + // _dependency_by_parent_id); + // data_logger::log_container("_timeperiod_by_id", _timeperiod_by_id); + // data_logger::log_container("_global_constant_macro", + // _global_constant_macros); + // data_logger::log_container("_notification_methods", _notification_methods); + // data_logger::log_container("_notification_rules_by_node", + // _notification_rules_by_node + // ); +#endif //! NDEBUG +} + +/** + * Get a node by its node id. + * + * @param[in] id The id of the node. + * + * @return A node::ptr to the node, or a null node::ptr. + */ +node::ptr state::get_node_by_id(node_id id) const { + return (_node_by_id.value(id)); +} + +/** + * Get all the notification rules associated to a node. + * + * @param[in] id The id of the node. + * + * @return A list of notification_rule::ptr associated to this node. + */ +QList state::get_notification_rules_by_node( + node_id id) const { + return (_notification_rules_by_node.values(id)); +} + +/** + * Get the notification rule associated to a id. + * + * @param[in] id The id of the notification rule. + * + * @return A notification_rule::ptr to the notification rule, or a null + * ptr. + */ +notification_rule::ptr state::get_notification_rule_by_id(uint32_t id) const { + return (_notification_rule_by_id.value(id)); +} + +/** + * Get a notification method from its id. + * + * @param[in] id The notification method id. + * + * @return A notification_method::ptr the notification method, or a null + * notification_method::ptr. + */ +notification_method::ptr state::get_notification_method_by_id( + uint32_t id) const { + return (_notification_methods.value(id)); +} + +/** + * Get a timeperiod by its id. + * + * @param[in] id The id of the timeperiod. + * + * @return A timeperiod::ptr to the timeperiod, or a null + * timeperiod::ptr. + */ +::com::centreon::broker::time::timeperiod::ptr state::get_timeperiod_by_id( + uint32_t id) const { + return (_timeperiod_by_id.value(id)); +} + +/** + * Get a contact by its id. + * + * @param[in] id The id of the contact. + * + * @return A contact::ptr to the contact, or a null contact::ptr. + */ +objects::contact::ptr state::get_contact_by_id(uint32_t id) const { + return (_contacts.value(id)); +} + +/** + * Get the infos of a contact by its contact id. + * + * @param[in] id The id of the contact. + * + * @return A map of the contact infos. + */ +QHash state::get_contact_infos(uint32_t id) const { + return (_contact_infos.value(id)); +} + +/** + * Get a command by its id. + * + * @param[în] id The id of the command. + * + * @return A command::ptr to the command, or a null command::ptr. + */ +objects::command::ptr state::get_command_by_id(uint32_t id) const { + return (_commands.value(id)); +} + +/** + * Get a read lock on this state. + * + * @return A QReadLocker locking this state. + */ +std::unique_ptr state::read_lock() { + return (std::unique_ptr(new QReadLocker(&_state_mutex))); +} + +/** + * Get a write lock on this state. + * + * @return A QWriteLocker locking this state. + */ +std::unique_ptr state::write_lock() { + return (std::unique_ptr(new QWriteLocker(&_state_mutex))); +} + +/** + * Get the global macros from the state. + * + * @return The global macros. + */ +QHash const& state::get_global_macros() const { + return (_global_constant_macros); +} + +/** + * Get the format of the date (ie US, Euro, Iso...) + * + * @return The format of the date. + */ +int state::get_date_format() const { + return (_date_format); +} + +/** + * Get all the services of an host. + * + * @param[in] id The id of the host. + * + * @return All the services of the host. + */ +QList state::get_all_services_of_host( + objects::node_id id) const { + if (!id.is_host()) + return (QList()); + QList list; + for (QHash::const_iterator + it(_node_by_id.begin()), + end(_node_by_id.end()); + it != end; ++it) + if (it.key().get_host_id() == id.get_host_id() && it.key().is_service()) + list.push_back(*it); + return (list); +} + +/** + * Get all the hosts in a given state. + * + * @param[in] state The state. -1 for all that are not up. + * + * @return The hosts in the given state. + */ +QList state::get_all_hosts_in_state(short state) const { + QList list; + for (QHash::const_iterator + it(_node_by_id.begin()), + end(_node_by_id.end()); + it != end; ++it) + if (state == -1 && it.key().is_host() && + (*it)->get_hard_state() != objects::node_state::host_up) + list.push_back(*it); + else if (it.key().is_host() && + (*it)->get_hard_state() == objects::node_state(state)) + list.push_back(*it); + return (list); +} + +/** + * Get all the services in a given state. + * + * @param[in] state The state. -1 for all that are not ok. + * + * @return The services in the given state. + */ +QList state::get_all_services_in_state(short state) const { + QList list; + for (QHash::const_iterator + it(_node_by_id.begin()), + end(_node_by_id.end()); + it != end; ++it) + if (state == -1 && it.key().is_service() && + (*it)->get_hard_state() != objects::node_state::service_ok) + list.push_back(*it); + else if (it.key().is_service() && + (*it)->get_hard_state() == objects::node_state(state)) + list.push_back(*it); + return (list); +} diff --git a/centreon-broker/notification/src/stream.cc b/centreon-broker/notification/src/stream.cc new file mode 100644 index 00000000000..e54c524ad74 --- /dev/null +++ b/centreon-broker/notification/src/stream.cc @@ -0,0 +1,536 @@ +/* +** Copyright 2014-2015,2017 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include +#include +//#include +//#include +//#include +//#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "com/centreon/broker/exceptions/shutdown.hh" +#include "com/centreon/broker/io/events.hh" +#include "com/centreon/broker/misc/global_lock.hh" +#include "com/centreon/broker/notification/stream.hh" +#include "com/centreon/broker/notification/utilities/data_loggers.hh" +#include "com/centreon/engine/common.hh" +#include "com/centreon/exceptions/msg_fmt.hh" + +using namespace com::centreon::broker; +using namespace com::centreon::broker::misc; +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::objects; +using namespace com::centreon::exceptions; + +/************************************** + * * + * Public Methods * + * * + **************************************/ + +/** + * Constructor. + * + * @param[in] type Database type. + * @param[in] host Database host. + * @param[in] port Database port. + * @param[in] user User. + * @param[in] password Password. + * @param[in] centreon_db Database name. + * @param[in] check_replication true to check replication status. + * @param[in] node_cache A loaded node event cache. + */ +stream::stream(std::string const& type, + std::string const& host, + unsigned short port, + std::string const& user, + std::string const& password, + std::string const& centreon_db, + bool check_replication, + node_cache& cache) + : _node_cache(cache) { + // Get the driver ID. + std::string t("QMYSQL"); + // if (!type.compare("db2", Qt::CaseInsensitive)) + // t = "QDB2"; + // else if (!type.compare("ibase", Qt::CaseInsensitive) + // || !type.compare("interbase", Qt::CaseInsensitive)) + // t = "QIBASE"; + // else if (!type.compare("mysql", Qt::CaseInsensitive)) + // t = "QMYSQL"; + // else if (!type.compare("oci", Qt::CaseInsensitive) + // || !type.compare("oracle", Qt::CaseInsensitive)) + // t = "QOCI"; + // else if (!type.compare("odbc", Qt::CaseInsensitive)) + // t = "QODBC"; + // else if (!type.compare("psql", Qt::CaseInsensitive) + // || !type.compare("postgres", Qt::CaseInsensitive) + // || !type.compare("postgresql", Qt::CaseInsensitive)) + // t = "QPSQL"; + // else if (!type.compare("sqlite", Qt::CaseInsensitive)) + // t = "QSQLITE"; + // else if (!type.compare("tds", Qt::CaseInsensitive) + // || !type.compare("sybase", Qt::CaseInsensitive)) + // t = "QTDS"; + // else + // t = type; + + // Connection ID. + // QString id; + // id.setNum((qulonglong)this, 16); + + // Open centreon database. + _open_db(_centreon_db, t, host, port, user, password, centreon_db, + // id, + check_replication); + + // Create the process manager. + process_manager::instance(); + + // Create notification scheduler + _notif_scheduler.reset(new notification_scheduler(_state, _node_cache)); + _notif_scheduler->start(); +} + +/** + * Copy constructor. + * + * @param[in] other Object to copy. + */ +stream::stream(stream const& other) + : io::stream(other), _node_cache(other._node_cache) { + _centreon_db = std::move(const_cast(other)._centreon_db); + // Connection ID. + // QString id; + // id.setNum((qulonglong)this, 16); + // + // // Clone centreon database. + // _clone_db(_centreon_db, other._centreon_db, id); + + // Create the process manager. + process_manager::instance(); + + // Move the notification scheduler thread from the first stream. + _notif_scheduler.reset(const_cast(other)._notif_scheduler.release()); + _notif_scheduler->start(); +} + +/** + * Destructor. + */ +stream::~stream() { + // Connection ID. + // QString id; + // id.setNum((qulonglong)this, 16); + // + // { + // QMutexLocker lock(&global_lock); + // // Close database. + // if (_centreon_db->isOpen()) + // _centreon_db->close(); + // _centreon_db.reset(); + // } + // + // // Add this connection to the connections to be deleted. + // QSqlDatabase::removeDatabase(id); + + // Wait for the termination of the thread. + _notif_scheduler->exit(); + _notif_scheduler->wait(); + + // Wait for the termination of the process manager. + process_manager::release(); +} + +/** + * Initialize Notification layer. + */ +void stream::initialize() { + // Not used anymore. +} + +/** + * Read from the database. + * + * @param[out] d Cleared. + * @param[in] deadline Unused. + * + * @return This method will throw. + */ +bool stream::read(std::shared_ptr& d, time_t deadline) { + (void)deadline; + d.reset(); + throw exceptions::shutdown("attempt to read from a notification stream"); + return true; +} + +/** + * Update internal stream cache. + */ +void stream::update() { + _update_objects_from_db(); +} + +/** + * Write an event. + * + * @param[in] data Event pointer. + * + * @return Number of events acknowledged. + */ +int stream::write(std::shared_ptr const& data) { + // Check that data exists. + if (!validate(data, "notification")) + return (1); + + uint32_t retval(1); + + // Update node cache. + _node_cache.write(data); + + // Process events. + if (data->type() == neb::host_status::static_type()) + _process_host_status_event( + *std::static_pointer_cast(data)); + else if (data->type() == neb::service_status::static_type()) + _process_service_status_event( + *std::static_pointer_cast(data)); + else if (data->type() == neb::acknowledgement::static_type()) + _process_ack(*std::static_pointer_cast(data)); + else if (data->type() == neb::downtime::static_type()) + _process_downtime(*std::static_pointer_cast(data)); + + return (retval); +} + +/************************************** + * * + * Private Methods * + * * + **************************************/ + +/** + * Open a database connexion. + * + * @param[out] db The pointer to the new database connection. + * @param[in] t The type of the database. + * @param[in] host The host of the database. + * @param[in] port The port of the database. + * @param[in] user The user to connect with the database. + * @param[in] password The password to use. + * @param[in] db_name The name of the db to connect with. + * @param[in] id An unique id identifying the connection. + * @param[in] check_replication True if we need to check the replication. + */ +void stream::_open_db(std::unique_ptr& ms, + std::string const& t, + std::string const& host, + unsigned short port, + std::string const& user, + std::string const& password, + std::string const& db_name, + // QString const& id, + bool check_replication) { + int queries_per_transaction(1); + // Add database connection. + ms.reset(new mysql(database_config(t, host, port, user, password, db_name, + queries_per_transaction, check_replication, + 1))); + // try { + // if (t == "QMYSQL") + // db->setConnectOptions("CLIENT_FOUND_ROWS"); + // + // // Open database. + // db->setHostName(host); + // db->setPort(port); + // db->setUserName(user); + // db->setPassword(password); + // db->setDatabaseName(db_name); + + // { + // QMutexLocker lock(&global_lock); + // if (!db->open()) + // throw (msg_fmt() + // << "notification: could not open SQL database: " + // << db->lastError().text()); + // } + + // Check that replication is OK. + if (check_replication) { + log_v2::notification()->debug("notification: checking replication status"); + std::promise promise; + ms->run_query_and_get_result("SHOW SLAVE STATUS", &promise); + try { + database::mysql_result res(promise.get_future().get()); + if (ms->fetch_row(res)) { + for (int i(0); i < res.get_num_fields(); ++i) { + std::string field(res.get_field_name(i)); + if ((field == "Slave_IO_Running" && res.value_as_str(i) != "Yes") || + (field == "Slave_SQL_Running" && res.value_as_str(i) != "Yes") || + (field == "Seconds_Behind_Master" && res.value_as_i32(i) != 0)) + throw msg_fmt( + "notification: replication is not " + "complete: {}={}", + field, res.value_as_str(i)); + } + log_v2::notification()->info( + "notification: database replication is complete, " + "connection granted"); + } else { + log_v2::notification()->info( + "notification: database is not under replication"); + } + } catch (std::exception const& e) { + log_v2::notification()->info( + "notification: could not check replication status"); + } + } else + log_v2::notification()->debug( + "notification: NOT checking replication status"); + // catch (...) { + // { + // QMutexLocker lock(&global_lock); + // // Close database if open. + // if (db->isOpen()) + // db->close(); + // db.reset(); + // } + // + // // Add this connection to the connections to be deleted. + // QSqlDatabase::removeDatabase(id); + // throw ; + // } +} + +/** + * Clone a database connection. + * + * @param[out] db A pointer to the new db connection. + * @param[in] db_to_clone A pointer to the db connection to clone. + * @param[in] id An unique id identifiying the new connection. + */ +// void stream::_clone_db( +// std::unique_ptr& db, +// std::unique_ptr const& db_to_clone, +// QString const& id) { +// // Clone database. +// db.reset(new QSqlDatabase(QSqlDatabase::cloneDatabase(*db_to_clone, id))); +// +// try { +// QMutexLocker lock(&global_lock); +// // Open database. +// if (!db->open()) +// throw (msg_fmt() +// << "notification: could not open SQL database: " +// << db->lastError().text()); +// } +// catch (...) { +// +// { +// QMutexLocker lock(&global_lock); +// // Close database if open. +// if (db->isOpen()) +// db->close(); +// db.reset(); +// } +// +// // Add this connection to the connections to be deleted. +// QSqlDatabase::removeDatabase(id); +// throw ; +// } +//} + +/** + * Get the objects from the db. + */ +void stream::_update_objects_from_db() { + if (_centreon_db.get()) + _state.update_objects_from_db(*_centreon_db.get()); +} + +/** + * Process a service status event. + * + * @param event The event to process. + */ +void stream::_process_service_status_event(neb::service_status const& event) { + log_v2::notification()->debug( + "notification: processing status of service {} of host {} (state {})", + event.service_id, event.host_id, event.last_hard_state); + + node_id id(event.host_id, event.service_id); + short old_hard_state; + time_t when_to_schedule(::time(NULL) + 1); + + // Get the node corresponding to this id. + { + // Get the state lock. + // TODO: The write lock here kills the perf. Use a read lock instead. + // and lock on an individual node level. + std::unique_ptr lock(_state.write_lock()); + node::ptr n = _state.get_node_by_id(id); + if (!n) + throw msg_fmt("notification: got an unknown service: {}, host: {}", + id.get_service_id(), id.get_host_id()); + + // Save the old state and copy the current state. + old_hard_state = n->get_hard_state(); + n->set_hard_state(event.last_hard_state); + n->set_soft_state(event.current_state); + } + + // From OK to NOT-OK + if (old_hard_state != event.last_hard_state && + old_hard_state == node_state::ok) { + log_v2::notification()->debug( + "notification: state of service {} of host {} changed from 0 to {}, " + "scheduling notification attempt", + event.service_id, event.host_id, event.last_hard_state); + _notif_scheduler->remove_actions_of_node(id); + action a; + a.set_type(action::notification_processing); + a.set_forwarded_type(action::notification_attempt); + a.set_node_id(id); + _notif_scheduler->add_action_to_queue(when_to_schedule, a); + } + // From NOT-OK to OK + else if (old_hard_state != event.last_hard_state && + old_hard_state != node_state::ok) { + _notif_scheduler->remove_actions_of_node(id); + action a; + a.set_type(action::notification_processing); + a.set_forwarded_type(action::notification_up); + ; + a.set_node_id(id); + _notif_scheduler->add_action_to_queue(when_to_schedule, a); + } +} + +/** + * Process a host status event. + * + * @param event The event to process. + */ +void stream::_process_host_status_event(neb::host_status const& event) { + log_v2::notification()->debug( + "notification: processing status of host {} (state {})", event.host_id, + event.last_hard_state); + + node_id id(event.host_id); + short old_hard_state; + time_t when_to_schedule(::time(NULL) + 1); + + // Get the node corresponding to this id. + { + // Get the state lock. + // TODO: The write lock here kills the perf. Use a read lock instead. + // and lock on an individual node level. + std::unique_ptr lock(_state.write_lock()); + node::ptr n = _state.get_node_by_id(id); + if (!n) + throw msg_fmt("notification: got an unknown host: {}", + id.get_host_id()); + + // Save the old state and copy the current state. + old_hard_state = n->get_hard_state(); + n->set_hard_state(event.last_hard_state); + n->set_soft_state(event.current_state); + } + + // From OK to NOT-OK + if (old_hard_state != event.last_hard_state && + old_hard_state == node_state::ok) { + _notif_scheduler->remove_actions_of_node(id); + action a; + a.set_type(action::notification_processing); + a.set_forwarded_type(action::notification_attempt); + a.set_node_id(id); + _notif_scheduler->add_action_to_queue(when_to_schedule, a); + } + // From NOT-OK to OK + else if (old_hard_state != event.last_hard_state && + old_hard_state != node_state::ok) { + _notif_scheduler->remove_actions_of_node(id); + action a; + a.set_type(action::notification_processing); + a.set_forwarded_type(action::notification_up); + a.set_node_id(id); + _notif_scheduler->add_action_to_queue(when_to_schedule, a); + } +} + +/** + * Process an ack event. + * + * @param event The event to process. + */ +void stream::_process_ack(neb::acknowledgement const& event) { + objects::node_id id(event.host_id, event.service_id); + log_v2::notification()->debug( + "notification: processing acknowledgement of node ({}, {})", + event.host_id, event.service_id); + + // End of ack. + if (!event.deletion_time.is_null()) + return; + + // Add the ack. + if (event.notify_contacts && + (!event.notify_only_if_not_already_acknowledged || + (event.notify_only_if_not_already_acknowledged && + !_node_cache.node_acknowledged(id)))) { + time_t when_to_schedule(::time(NULL) + 1); + action a; + a.set_type(action::notification_processing); + a.set_forwarded_type(action::notification_ack); + a.set_node_id(id); + _notif_scheduler->add_action_to_queue(when_to_schedule, a); + } +} + +/** + * Process a downtime event. + * + * @param event The event to process. + */ +void stream::_process_downtime(neb::downtime const& event) { + objects::node_id id(event.host_id, event.service_id); + log_v2::notification()->debug( + "notification: processing downtime of node ({}, {}) starting at {} and " + "ending at {}", + event.host_id, event.service_id, event.start_time, event.end_time); + + // End of downtime. + if (!event.actual_end_time.is_null()) + return; + + // Add the downtime. + time_t when_to_schedule(::time(NULL) + 1); + action a; + a.set_type(action::notification_processing); + a.set_forwarded_type(action::notification_downtime); + a.set_node_id(id); + _notif_scheduler->add_action_to_queue(when_to_schedule, a); +} diff --git a/centreon-broker/notification/src/utilities/get_datetime_string.cc b/centreon-broker/notification/src/utilities/get_datetime_string.cc new file mode 100644 index 00000000000..838045cc057 --- /dev/null +++ b/centreon-broker/notification/src/utilities/get_datetime_string.cc @@ -0,0 +1,112 @@ +/* +** Copyright 2009-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/notification/utilities/get_datetime_string.hh" +#include +#include +#include + +using namespace com::centreon::broker::notification; +using namespace com::centreon::broker::notification::utilities; + +/** + * given a date/time in time_t format, produce a corresponding + * date/time string, including timezone + * + * @param[in] raw_time The time to transform. + * @param[in] max_length The max length of the resulting string. + * @param[in] type The type. + * + * @return A string containing the date/time; + */ +std::string utilities::get_datetime_string(time_t raw_time, + int max_length, + int type, + int format) { + static char const* weekdays[7] = {"Sun", "Mon", "Tue", "Wed", + "Thu", "Fri", "Sat"}; + static char const* months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"}; + + std::vector buffer; + buffer.resize(max_length); + + std::string ret; + ret.resize(max_length); + + tm tm_s; + if (type == http_date_time) + gmtime_r(&raw_time, &tm_s); + else + localtime_r(&raw_time, &tm_s); + + int hour(tm_s.tm_hour); + int minute(tm_s.tm_min); + int second(tm_s.tm_sec); + int month(tm_s.tm_mon + 1); + int day(tm_s.tm_mday); + int year(tm_s.tm_year + 1900); + + char const* tzone(tm_s.tm_isdst ? tzname[1] : tzname[0]); + + /* ctime() style date/time */ + if (type == long_date_time) + snprintf(&buffer[0], max_length, "%s %s %d %02d:%02d:%02d %s %d", + weekdays[tm_s.tm_wday], months[tm_s.tm_mon], day, hour, minute, + second, tzone, year); + + /* short date/time */ + else if (type == short_date_time) { + if (format == date_format_euro) + snprintf(&buffer[0], max_length, "%02d-%02d-%04d %02d:%02d:%02d", day, + month, year, hour, minute, second); + else if (format == date_format_iso8601 || + format == date_format_strict_iso8601) + snprintf(&buffer[0], max_length, "%04d-%02d-%02d%c%02d:%02d:%02d", year, + month, day, (format == date_format_strict_iso8601) ? 'T' : ' ', + hour, minute, second); + else + snprintf(&buffer[0], max_length, "%02d-%02d-%04d %02d:%02d:%02d", month, + day, year, hour, minute, second); + } + + /* short date */ + else if (type == short_date) { + if (format == date_format_euro) + snprintf(&buffer[0], max_length, "%02d-%02d-%04d", day, month, year); + else if (format == date_format_iso8601 || + format == date_format_strict_iso8601) + snprintf(&buffer[0], max_length, "%04d-%02d-%02d", year, month, day); + else + snprintf(&buffer[0], max_length, "%02d-%02d-%04d", month, day, year); + } + + /* expiration date/time for HTTP headers */ + else if (type == http_date_time) + snprintf(&buffer[0], max_length, "%s, %02d %s %d %02d:%02d:%02d GMT", + weekdays[tm_s.tm_wday], day, months[tm_s.tm_mon], year, hour, + minute, second); + + /* short time */ + else + snprintf(&buffer[0], max_length, "%02d:%02d:%02d", hour, minute, second); + + buffer[max_length - 1] = '\x0'; + + return (std::string(&buffer[0])); +} diff --git a/centreon-broker/notification/src/utilities/qhash_func.cc b/centreon-broker/notification/src/utilities/qhash_func.cc new file mode 100644 index 00000000000..0384f901182 --- /dev/null +++ b/centreon-broker/notification/src/utilities/qhash_func.cc @@ -0,0 +1,32 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#include "com/centreon/broker/notification/utilities/qhash_func.hh" +#include +#include +#include + +/** + * QHash function for std::string. + * + * @param str The std::string to hash. + * @return The hashed value for str. + */ +uint qHash(std::string const& str) { + return (qHash(QByteArray::fromRawData(str.c_str(), str.size()))); +} diff --git a/centreon-broker/packaging/rpm/centreon-broker.spectemplate b/centreon-broker/packaging/rpm/centreon-broker.spectemplate new file mode 100644 index 00000000000..d43a3b79ee5 --- /dev/null +++ b/centreon-broker/packaging/rpm/centreon-broker.spectemplate @@ -0,0 +1,1209 @@ +## +## Copyright 2011-2019 Centreon +## + +Name: centreon-broker +Version: %{VERSION} +Release: %{RELEASE}%{?dist} +Summary: Store Centreon Engine/Nagios events in a database. +%define thismajor 22.04.0 +%define nextmajor 22.05.0 + +Group: Applications/Communications +License: ASL 2.0 +URL: https://github.com/centreon/centreon-broker.git +Packager: Matthieu Kermagoret +Vendor: Centreon Entreprise Server (CES) Repository, http://yum.centreon.com/standard/ + +Source0: %{name}-%{version}.tar.gz +BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root + +BuildRequires: cmake3 >= 3.15 + +BuildRequires: gcc +BuildRequires: gcc-c++ +BuildRequires: libgcrypt-devel +BuildRequires: lua-devel +BuildRequires: make +BuildRequires: MariaDB-devel +BuildRequires: MariaDB-shared +BuildRequires: rrdtool-devel +BuildRequires: systemd +Requires: centreon-common >= %{thismajor} +Requires: centreon-common < %{nextmajor} +Requires: coreutils + +%if 0%{?suse_version} +BuildRequires: libgnutls-devel >= 3.3.29 +%else +BuildRequires: gnutls-devel >= 3.3.29 +%endif + +%description +Centreon Broker is a Centreon Engine/Nagios module that report events in +one or multiple databases. + +%package core +Summary: Centreon Broker's shared library. +Group: Applications/Communications +Requires: gnutls >= 3.3.29 +Requires: lua +Requires: %{name} = %{version}-%{release} +Requires: %{name}-storage = %{version}-%{release} + +%description core +core holds Centreon Broker's default modules; + +%package storage +Summary: Centreon Broker's shared library for prefdata storage. +Group: Applications/Communications +Requires: %{name}-core = %{version}-%{release} + +%description storage +storage holds Centreon Broker's prefdata storage. + +%package graphite +Summary: Write Centreon performance data to Graphite. +Group: Applications/Communications +Requires: %{name}-core = %{version}-%{release} + +%description graphite +This module of Centreon Broker allows you to write performance data +generated by plugins (run themselves by Centreon Engine) to a Graphite +database. + +%package influxdb +Summary: Write Centreon performance data to InfluxDB. +Group: Applications/Communications +Requires: %{name}-core = %{version}-%{release} + +%description influxdb +This module of Centreon Broker allows you to write performance data +generated by plugins (run themselves by Centreon Engine) to an InfluxDB +database. + +%package cbd +Summary: Centreon Broker daemon. +Group: System Environment/Daemons +Requires: %{name}-core = %{version}-%{release} +%{?systemd_requires} + +%description cbd +The Centreon Broker daemon can aggregates output of multiple cbmod and store +events in a DB from a single point. + +%package cbmod +Summary: Centreon Broker as Centreon Engine 2 module. +Group: Applications/Communications +Requires: %{name}-core = %{version}-%{release} +Requires: centreon-engine >= %{thismajor} +Requires: centreon-engine < %{nextmajor} + +%description cbmod +This module can be loaded by Centreon Engine. + +%package devel +Summary: Centreon Broker devel libraries. +Group: Applications/Communications + +%description devel +Include files needed to develop a module Centreon Broker. + +%prep +%setup + +%build +pip3 install conan --upgrade +cpp11=$(gcc --version | awk '/gcc/ && ($3+0)>5.0{print 1}') +if [ $cpp11 -eq 1 ] ; then + conan install . -s compiler.libcxx=libstdc++11 --build=missing +else + conan install . -s compiler.libcxx=libstdc++ +fi + +CXXFLAGS="-DNDEBUG -O2 -g -std=c++11" cmake3 \ + -DWITH_TESTING=0 \ + -DWITH_PREFIX=/usr \ + -DWITH_PREFIX_BIN=%{_sbindir} \ + -DWITH_PREFIX_CONF_BROKER=%{_sysconfdir}/centreon-broker \ + -DWITH_PREFIX_INC=%{_includedir}/centreon-broker \ + -DWITH_PREFIX_MODULES=%{_datadir}/centreon/lib/centreon-broker \ + -DWITH_PREFIX_LIB_BROKER=%{_libdir}/nagios/ \ + -DWITH_PREFIX_VAR=%{_localstatedir}/lib/centreon-broker \ + -DWITH_STARTUP_DIR=%{_unitdir} \ + -DWITH_STARTUP_SCRIPT=systemd \ + -DWITH_USER_BROKER=centreon-broker \ + -DWITH_GROUP_BROKER=centreon-broker \ + -DWITH_DAEMONS='central-rrd;central-broker' \ + -DWITH_CONFIG_FILES=y \ + . +%{__make} -j9 %{?_smp_mflags} VERBOSE="1" + +%install +%{__rm} -rf $RPM_BUILD_ROOT +%{__install} -d $RPM_BUILD_ROOT%{_sbindir} +%{__install} -d -m 0775 $RPM_BUILD_ROOT%{_localstatedir}/log/centreon-broker +%{__install} -d -m 0775 $RPM_BUILD_ROOT%{_localstatedir}/lib/centreon-broker +%{__install} -d -m 0775 $RPM_BUILD_ROOT%{_sysconfdir}/centreon-broker +%{__install} -d $RPM_BUILD_ROOT%{_unitdir} +%{__install} -d $RPM_BUILD_ROOT%{_sysconfdir}/logrotate.d +%{__install} -d $RPM_BUILD_ROOT%{_sysconfdir}/centreon-engine/conf.d +%{__install} -d $RPM_BUILD_ROOT%{_datadir}/doc/centreon-broker +%{__install} -d $RPM_BUILD_ROOT%{_datadir}/centreon-broker/lua +%{__install} -m 644 script/centreon-broker.logrotate $RPM_BUILD_ROOT%{_sysconfdir}/logrotate.d/cbd +%{__make} install DESTDIR="$RPM_BUILD_ROOT" + +%clean +%{__rm} -rf $RPM_BUILD_ROOT + +%pre +%{_bindir}/getent group centreon-broker &>/dev/null || %{_sbindir}/groupadd -r centreon-broker 2> /dev/null || : +%{_bindir}/getent passwd centreon-broker &>/dev/null || %{_sbindir}/useradd -m -g centreon-broker -d %{_localstatedir}/lib/centreon-broker -r centreon-broker 2> /dev/null || : +if id centreon &>/dev/null; then + %{_sbindir}/usermod -a -G centreon-broker centreon +fi +if id centreon-gorgone &>/dev/null; then + %{_sbindir}/usermod -a -G centreon-gorgone centreon-broker +fi +if id centreon-engine &>/dev/null; then + %{_sbindir}/usermod -a -G centreon-broker centreon-engine + %{_sbindir}/usermod -a -G centreon-engine centreon-broker +fi +if id nagios &>/dev/null; then + %{_sbindir}/usermod -a -G centreon-broker nagios +fi + +%post +chown -R centreon-broker:centreon-broker /var/lib/centreon-broker +chmod -R g+w /var/lib/centreon-broker +chown -R centreon-broker:centreon-broker /var/log/centreon-broker +chmod -R g+w /var/log/centreon-broker + +%post cbd +%systemd_post cbd.service || : + +%pre cbd +# Stop cbd daemons for compatibility +if [ -f /etc/init.d/cbd-central-broker ]; then + /etc/init.d/cbd-central-broker stop &>/dev/null || : +fi + +%preun cbd +%systemd_preun cbd.service || : + +%files +%defattr(-,centreon-broker,centreon-broker,-) +%{_localstatedir}/log/centreon-broker +%{_localstatedir}/lib/centreon-broker +%dir %{_sysconfdir}/centreon-broker + +%files core +%defattr(-,root,root,-) +%{_datadir}/centreon/lib/centreon-broker/10-neb.so +%{_datadir}/centreon/lib/centreon-broker/15-stats.so +%{_datadir}/centreon/lib/centreon-broker/20-bam.so +%{_datadir}/centreon/lib/centreon-broker/50-tcp.so +%{_datadir}/centreon/lib/centreon-broker/60-tls.so +%{_datadir}/centreon/lib/centreon-broker/70-lua.so +%{_datadir}/centreon/lib/centreon-broker/80-sql.so +%{_sysconfdir}/logrotate.d/cbd +%defattr(0775,centreon-broker,centreon-broker,-) +%{_datadir}/centreon-broker +%{_datadir}/centreon-broker/lua + +%files storage +%defattr(-,root,root,-) +%{_datadir}/centreon/lib/centreon-broker/20-storage.so +%{_datadir}/centreon/lib/centreon-broker/70-rrd.so + +%files graphite +%defattr(-,root,root,-) +%{_datadir}/centreon/lib/centreon-broker/70-graphite.so + +%files influxdb +%defattr(-,root,root,-) +%{_datadir}/centreon/lib/centreon-broker/70-influxdb.so + +%files cbd +%defattr(664,centreon-broker,centreon-broker,-) +%config(noreplace) %{_sysconfdir}/centreon-broker/central-broker.json +%config(noreplace) %{_sysconfdir}/centreon-broker/central-rrd.json +%config(noreplace) %{_sysconfdir}/centreon-broker/watchdog.json +%defattr(-,root,root,-) +%{_sbindir}/cbd +%{_sbindir}/cbwd + +%defattr(-,root,root,-) +%{_datadir}/doc/centreon-broker/ + +%attr(755, root, root) %{_unitdir}/cbd.service + +%files cbmod +%defattr(664,centreon-broker,centreon-broker,-) +%config(noreplace) %{_sysconfdir}/centreon-broker/poller-module.json +%defattr(-,root,root,-) +%{_libdir}/nagios/cbmod.so + +%post cbmod +%{_bindir}/getent passwd centreon-engine &>/dev/null && %{_sbindir}/usermod -a -G centreon-broker centreon-engine +%{_bindir}/getent group centreon-engine &>/dev/null && %{_sbindir}/usermod -a -G centreon-engine centreon-broker + +%files devel +%defattr(-,root,root,-) +#%{_libdir}/pkgconfig/centengine.pc +%{_prefix}/include/centreon-broker +%doc LICENSE + +%changelog +* Tue Nov 29 2016 Matthieu Kermagoret 3.0.2-3 +- Fix downtime inheritance in BAM module. + +* Fri Nov 25 2016 Matthieu Kermagoret 3.0.2-2 +- Fix SQL queries in the SQL cleanup thread. + +* Wed Nov 23 2016 Matthieu Kermagoret 3.0.2-1 +- Fetch services' host IDs through services themselves. + +* Thu Nov 10 2016 Matthieu Kermagoret 3.0.1-1 +- Minor bugfixes. + +* Tue Jan 19 2016 Matthieu Kermagoret 3.0.0-54 +- Fix file::stream semantic to reflect the io::stream interface. + +* Mon Jan 04 2016 Alexandre Fouille 3.0.0-53 +- Add devel packaging. + +* Wed Dec 02 2015 Alexandre Fouille 3.0.0-52 +- Add systemd directive for el7. + +* Tue Dec 01 2015 Matthieu Kermagoret 3.0.0-51 +- Multiple fixes on SQL queries for 2.x schema. + +* Mon Nov 30 2015 Matthieu Kermagoret 3.0.0-50 +- Remove support for CentOS 5 in spec file. +- Require Centreon Engine 1.x. + +* Fri Nov 27 2015 Matthieu Kermagoret 3.0.0-49 +- Package cbwd. + +* Fri Nov 27 2015 Matthieu Kermagoret 3.0.0-48 +- Compatibility with Centreon Engine 1.x instead of 2.x. +- Compatibility with Centreon Web 2.x and 3.x. + +* Wed Nov 25 2015 Alexandre Fouille 2.11.0-13 +- Small fixes to unit tests. + +* Fri Nov 20 2015 Matthieu Kermagoret 2.11.0-12 +- Backport fixes of the 2.10.2 release. + +* Fri Nov 20 2015 Matthieu Kermagoret 2.10.2-2 +- Fix UPDATE query when processing BA events durations. + +* Thu Nov 19 2015 Matthieu Kermagoret 2.10.2-1 +- Prevent a deadlock from the TCP module when exiting. + +* Tue Nov 17 2015 Alexandre Fouille 2.11.0-11 +- Fix typo in service group delete statement. + +* Tue Nov 17 2015 Matthieu Kermagoret 2.11.0-10 +- Acceptor clients can not have temporary files anymore. + +* Tue Nov 10 2015 Alexandre Fouille 2.11.0-9 +- Fix a deadlock at exit when one peer retention mode is enabled. + +* Thu Nov 05 2015 Matthieu Kermagoret 2.11.0-8 +- Properly serialize group IDs in mappings. + +* Thu Nov 05 2015 Matthieu Kermagoret 2.11.0-7 +- Improve log messages for group processing in SQL module. + +* Thu Nov 05 2015 Matthieu Kermagoret 2.11.0-6 +- Fix group and group member packet generation (they need a valid group ID). + +* Tue Nov 03 2015 Matthieu Kermagoret 2.11.0-5 +- Fix group and group member processing. + +* Wed Oct 28 2015 Matthieu Kermagoret 2.11.0-4 +- Update groups and members classes to improve the database design. + +* Thu Oct 22 2015 Alexandre Fouille 2.11.0-3 +- Set default log status at NULL. + +* Wed Oct 21 2015 Alexandre Fouille 2.11.0-2 +- Update the hostgroup/servicegroup relations table to use instance_id +- Add instance_id to the group_member events. + +* Mon Oct 19 2015 Alexandre Fouille 2.11.0-1 +- Added the field 'state' to meta_service_status events. +- Added hostgroup_id and servicegroup_id management. + +* Thu Oct 08 2015 Alexandre Fouille 2.10.1-6 +- Fix BA events update at centreon broker startup. + +* Tue Oct 06 2015 Alexandre Fouille 2.10.1-5 +- Fix BBDO serialization of high payload packets. +- Fix handling of ephemeral BA/KPI events. + +* Mon Oct 05 2015 Alexandre Fouille 2.10.1-4 +- Fix BA/KPI events linking. + +* Fri Oct 02 2015 Matthieu Kermagoret 2.10.1-3 +- Prevent infinite recursive call in compressed stream. + +* Tue Sep 29 2015 Matthieu Kermagoret 2.10.1-2 +- Do not dequeue an empty event list. + +* Fri Sep 25 2015 Matthieu Kermagoret 2.10.1-1 +- Clean downtime table at instance restart. +- Prevent loops in BA graph. +- Use UPDATE/INSERT combo for BA event durations. + +* Fri Sep 11 2015 Alexandre Fouille 2.10.0-26 +- Bump centreon version requirement. + +* Fri Sep 11 2015 Alexandre Fouille 2.10.0-25 +- Fix extraneous newlines in file stats. + +* Thu Sep 10 2015 Alexandre Fouille 2.10.0-24 +- Fix the way ba events are saved in base, removing duplicates. + +* Tue Sep 08 2015 Alexandre Fouille 2.10.0-23 +- Fix unit tests/neb mappings. + +* Tue Aug 25 2015 Alexandre Fouille 2.10.0-22 +- Don't crash on engine reloading. + +* Tue Aug 25 2015 Alexandre Fouille 2.10.0-21 +- Add db_dumpc_committed bbdo's mapping. + +* Thu Aug 20 2015 Alexandre Fouille 2.10.0-20 +- Copy boolean rules at db synchro. + +* Thu Aug 20 2015 Alexandre Fouille 2.10.0-19 +- Automatically reload BAs/KPIs at db_dump. + +* Wed Aug 19 2015 Alexandre Fouille 2.10.0-18 +- Fix termination of closed TCP connection. + +* Wed Aug 19 2015 Alexandre Fouille 2.10.0-17 +- Add missing case in BBDO's deconnection. + +* Tue Aug 18 2015 Alexandre Fouille 2.10.0-16 +- Remove hosts and services events after a dump. + +* Mon Aug 17 2015 Alexandre Fouille 2.10.0-15 +- Fix thread managing in bbdo's acceptor. + +* Mon Aug 17 2015 Alexandre Fouille 2.10.0-14 +- Fix helgrind warnings. + +* Mon Aug 17 2015 Alexandre Fouille 2.10.0-13 +- Fix feeder terminations in tcp acceptor output. + +* Fri Aug 14 2015 Alexandre Fouille 2.10.0-12 +- Fix a rare condition on tcp stream exit. + +* Thu Aug 13 2015 Alexandre Fouille 2.10.0-11 +- Fix the dumping of hosts and services. + +* Thu Aug 13 2015 Alexandre Fouille 2.10.0-10 +- Fix a deadlock in failovers. + +* Thu Aug 13 2015 Alexandre Fouille 2.10.0-9 +- Fix tcp acceptor termination. +- Fix select in db_reader. + +* Wed Aug 12 2015 Alexandre Fouille 2.10.0-8 +- Add synchronization of BA's virtual services in db_dumpers. + +* Tue Aug 11 2015 Alexandre Fouille 2.10.0-7 +- Fix improper management of null event in feeders. + +* Tue Aug 11 2015 Alexandre Fouille 2.10.0-6 +- Fix thread termination on client close in external command. +- Fix dumper serialization. + +* Fri Aug 07 2015 Alexandre Fouille 2.10.0-5 +- Fix tcp::connector::close(). + +* Fri Aug 07 2015 Alexandre Fouille 2.10.0-4 +- Fix BBDO's close signal forwarding. +- Fix process checks in tcp stream read(). + +* Fri Aug 07 2015 Alexandre Fouille 2.10.0-3 +- Backport if acceptor filters from 3.x. + +* Thu Aug 06 2015 Alexandre Fouille 2.10.0-2 +- Entire rewriting of the TCP layer to make it QTcpSocket compliant. +- Fix a bug where the negative values of the RRD weren't correctly rebuilt. + +* Wed Aug 05 2015 Alexandre Fouille 2.10.0-1 +- Backport bam synchronization and external command files from centreon broker 3.x. + +* Fri Jul 31 2015 Matthieu Kermagoret 2.9.2-1 +- Remove 'valid' flag of KPI queries that was introduced in 2.9.1 release whereas it shouldn't have. + +* Thu Jul 30 2015 Matthieu Kermagoret 3.0.0-47 +- Fix external command execution system that processed only first command. + +* Thu Jul 30 2015 Alexandre Fouille 3.0.0-46 +- Notification start and end are in time, not notification number. + +* Thu Jul 30 2015 Matthieu Kermagoret 3.0.0-45 +- Change external command format. +- Fix some notification queries. + +* Tue Jul 28 2015 Alexandre Fouille 2.9.1-2 +- Fix a memory leak caused by improper handling of null events. + +* Mon Jul 27 2015 Alexandre Fouille 2.9.1-1 +- Fix a SQL query commit problem preventing events from being acknowledged. + +* Mon Jul 27 2015 Matthieu Kermagoret 3.0.0-44 +- Synchronize more DB objects to remote poller (organizations, BA types, ...) +- Fix many queries. + +* Fri Jul 24 2015 Matthieu Kermagoret 3.0.0-43 +- Multiple fixes regarding remote BAs. +- Fix segfault in db_cfg_reader endpoint. +- Use updated graph tables. + +* Thu Jul 09 2015 Alexandre Fouille 3.0.0-42 +- Fix cbmod.cfg rights. + +* Mon Jul 06 2015 Alexandre Fouille 3.0.0-41 +- Fix internal category filtering (again). + +* Mon Jul 06 2015 Alexandre Fouille 3.0.0-40 +- Fix default configuration files. + +* Fri Jul 03 2015 Alexandre Fouille 3.0.0-39 +- Fix the internal category not properly handled in filters. + +* Thu Jul 02 2015 Matthieu Kermagoret 3.0.0-38 +- Fix some minor issues in downtimes and acknowledgements. + +* Wed Jul 01 2015 Matthieu Kermagoret 3.0.0-37 +- Fix a rare crash related to event count in muxer. + +* Wed Jul 01 2015 Alexandre Fouille 2.9.0-8 +- Apply the previous fix to the hosts. + +* Tue Jun 30 2015 Alexandre Fouille 2.9.0-7 +- Fix service/host insertion in db when its id change without restart. + +* Thu Jun 25 2015 Matthieu Kermagoret 2.9.0-6 +- Fix computation of BA availabilities. + +* Wed Jun 24 2015 Matthieu Kermagoret 3.0.0-36 +- Move central-module.xml to poller-module.xml +- centreon-broker-cbmod install a default configuration file for Engine. + +* Wed Jun 24 2015 Matthieu Kermagoret 3.0.0-35 +- Add WITH_VAR build variable. + +* Mon Jun 22 2015 Alexandre Fouille 3.0.0-34 +- Update downtime and acknowledgement flags in host and services. + +* Thu Jun 18 2015 Alexandre Fouille 3.0.0-33 +- Fix mode permission on cfg files. + +* Thu Jun 18 2015 Alexandre Fouille 3.0.0-32 +- Properly handle ack expiration. + +* Wed Jun 17 2015 Alexandre Fouille 3.0.0-31 +- Properly update downtimes in database. + +* Wed Jun 17 2015 Alexandre Fouille 3.0.0-30 +- Properly parse comments and author from downtime/ack commands. +- Restart notification sending if a node stop to be in downtime/ack. + +* Wed Jun 17 2015 Alexandre Fouille 3.0.0-29 +- Fix SQL exclude mecanism that didn't work. + +* Mon Jun 15 2015 Alexandre Fouille 3.0.0-28 +- Fix acknowledgement/downtime handling by the notification module. + +* Mon Jun 15 2015 Alexandre Fouille 3.0.0-27 +- Multiple fixes. +- Fix notification's node cache management. + +* Mon Jun 15 2015 Alexandre Fouille 3.0.0-26 +- Unit test fixes. +- Logs in node events stream. + +* Mon Jun 15 2015 Alexandre Fouille 3.0.0-25 +- Fix QT's warnings on notification processes. + +* Fri Jun 12 2015 Alexandre Fouille 3.0.0-24 +- Remove obsolete notification node options. + +* Fri Jun 12 2015 Alexandre Fouille 3.0.0-23 +- Large number of fixes to the new multiplexing paradigm. + +* Fri Jun 12 2015 Alexandre Fouille 2.9.0-5 +- Fix an invalid return statement in BAM. + +* Thu Jun 11 2015 Alexandre Fouille 3.0.0-22 +- Implement protocol and multiplexer bi-directionality. +- Refactoring of the failovers and multiplexer system. +- Immediate shutdown. +- Creation of memory queue file at shutdown. +- Large number of minor fixes. + +* Wed Jun 10 2015 Alexandre Fouille 3.0.0-21 +- Numerous node events/command parsing fixes. +- Allow downtimes and timeperiods to be parsed from config files. + +* Tue Jun 09 2015 Alexandre Fouille 2.9.0-4 +- Save the state of boolean kpi between reboots. + +* Mon Jun 01 2015 Matthieu Kermagoret 3.0.0-20 +- Move centreon-broker user home to /var/lib instead of /var/spool. + +* Mon Jun 01 2015 Matthieu Kermagoret 3.0.0-19 +- Update package URL. +- Move central-cbmod.xml to central-module.xml + +* Fri May 22 2015 Alexandre Fouille 3.0.0-18 +- Fix acknowledgement db insertion. + +* Thu May 21 2015 Alexandre Fouille 3.0.0-17 +- Small fixes. + +* Wed May 13 2015 Alexandre Fouille 3.0.0-16 +- Add configure files at installation. + +* Wed May 06 2015 Alexandre Fouille 3.0.0-15 +- Directory dumpers are now recursive. + +* Tue May 05 2015 Matthieu Kermagoret 3.0.0-14 +- centreon-broker-cbmod requires centreon-engine. +- Fix filter inheritance to failovers. + +* Mon May 04 2015 Alexandre Fouille 3.0.0-13 +- Node events, downtime manager. + +* Thu Apr 30 2015 Alexandre Fouille 3.0.0-12 +- Fix output acceptor filtering. + +* Thu Apr 30 2015 Alexandre Fouille 3.0.0-11 +- Minor fixes. + +* Wed Apr 29 2015 Alexandre Fouille 3.0.0-10 +- Fix a bug when input connector received a null event. + +* Tue Apr 28 2015 Alexandre Fouille 2.8.2-5 +- Fix the loading of KPI's when the BA is deactivated. + +* Mon Apr 27 2015 Alexandre Fouille 3.0.0-9 +- Set end_time to NULL for opened issue/state events in correlation. + +* Mon Apr 27 2015 Alexandre Fouille 3.0.0-8 +- Debug logging for new correlation module. +- Minor fixes. + +* Fri Apr 24 2015 Matthieu Kermagoret 3.0.0-7 +- Improved compatibility with Centreon Engine 2. +- Remove compression module. +- Minor bug fixes. + +* Fri Apr 24 2015 Matthieu Kermagoret 2.9.0-3 +- Import latest fixes. +- Graphite and InfluxDB modules are 70-, not 80-. + +* Tue Apr 21 2015 Alexandre Fouille 2.8.2-4 +- Fix a race condition causing a crash when two reporting outputs are configured. +- Fix an infinite commit loop when read_timeout is set to 0. +- Check that host parents and groups relationships are not already present in the db before inserting them. + +* Thu Apr 16 2015 Matthieu Kermagoret 3.0.0-6 +- Compatibility with Centreon Engine 2. +- Move Graphite and InfluxDB modules to their own packages. + +* Tue Apr 14 2015 Matthieu Kermagoret 2.9.0-2 +- Import fixes from 2.8.2 release. + +* Fri Apr 10 2015 Alexandre Fouille 2.8.2-3 +- Fix the socket timeout option. + +* Thu Apr 09 2015 Alexandre Fouille 3.0.0-5 +- Use Centreon 3.0 table names for bam broker. + +* Wed Apr 08 2015 Alexandre Fouille 3.0.0-4 +- Command file managing. +- Various core, notification fixes. + +* Wed Apr 08 2015 Alexandre Fouille 2.8.2-2 +- Fix a crash in BAM update when updating on erroneous configuration. +- Fix dimension loading for BVs. + +* Thu Mar 26 2015 Alexandre Fouille 2.8.2-1 +- Fix kpi name dimension reporting for kpis of services. +- Add a way to force timeout of writing socket operations. + + +* Wed Mar 25 2015 Alexandre Fouille 3.0.0-3 +- Add Influxdb module. +- Add Graphite module. +- Add dir_dump and fifo_dump inputs. +- Merge Bam from previous release. +- Event handling refactoring. +- Read timeout even with constant stream. +- Removal of the File and NDO modules. +- Persistent cache. + +* Fri Mar 20 2015 Matthieu Kermagoret 2.9.0-1 +- Remove local module. +- Add beta InfluxDB module. +- Add beta Graphite module. + +* Thu Feb 19 2015 Alexandre Fouille 2.8.1-5 +- Fix an erronuous condition in KPI event handling. + +* Wed Feb 18 2015 Matthieu Kermagoret 2.8.1-4 +- Fix type of RRD update values according to RRD type. + +* Tue Feb 17 2015 Alexandre Fouille 2.8.1-3 +- Fix an error in BA-event handling. + +* Wed Feb 11 2015 Alexandre Fouille 2.8.1-2 +- Commit current event states of BA at broker's startup. + +* Mon Feb 09 2015 Alexandre Fouille 2.8.1-1 +- Ignore any bdd error on BA dimension insertion. + +* Tue Jan 27 2015 Alexandre Fouille 2.8.0-47 +- Fix a segfault in the configuration check with the BAM module loaded. +- Fix incorrect serialization of timestamp -1 in BBDO's protocol. + +* Thu Jan 22 2015 Alexandre Fouille 2.8.0-46 +- Bump bbdo's version to 1.2.0 to account for BAM packets. + +* Tue Jan 20 2015 Alexandre Fouille 2.8.0-45 +- Don't update kpi events with not matching impact_level. + +* Tue Jan 20 2015 Alexandre Fouille 2.8.0-44 +- Manage a cache of initial kpi_event in kpi configuration. + +* Mon Jan 19 2015 Alexandre Fouille 2.8.0-43 +- Save last impact of each KPI into the database. +- Close and open a new event when a KPI's impact has changed at startup. +- Update correctly overlaping kpi events. + +* Thu Jan 15 2015 Alexandre Fouille 2.8.0-42 +- Fix a typo causing the kpi event to not be reopened. + +* Thu Jan 15 2015 Alexandre Fouille 2.8.0-41 +- Impact the first opened kpi event at restart. + +* Wed Jan 14 2015 Alexandre Fouille 2.8.0-40 +- Discard kpi of deactivated services. + +* Wed Jan 14 2015 Alexandre Fouille 2.8.0-39 +- Use meta id for kpi of meta services instead of kpi id. + +* Wed Jan 14 2015 Alexandre Fouille 2.8.0-38 +- Commit last_state_change for each KPI into DB. + +* Tue Jan 13 2015 Alexandre Fouille 2.8.0-37 +- Set last check at start time of opened event in kpi services. + +* Tue Jan 13 2015 Alexandre Fouille 2.8.0-36 +- Commit BA events before KPI events. + +* Tue Jan 13 2015 Matthieu Kermagoret 2.8.0-35 +- Fix BA/KPI events times. + +* Mon Jan 12 2015 Alexandre Fouille 2.8.0-34 +- Insert a kpi-ba relation on new kpi insertions, not on kpi closing. +- Only insert a kpi-ba event relation on associated kpi/ba. + +* Fri Jan 09 2015 Alexandre Fouille 2.8.0-33 +- Fix a crash on empty ba event insertion on an empty cache. + +* Fri Jan 09 2015 Alexandre Fouille 2.8.0-32 +- Fix a double impact on a reloading on modified kpis. + +* Thu Jan 08 2015 Alexandre Fouille 2.8.0-31 +- Clamp ba events level between 0% and 100%. +- Set the last service update in BA at start. + +* Wed Jan 07 2015 Alexandre Fouille 2.8.0-30 +- Add centreon-broker to centreon-engine group at install. + +* Tue Jan 06 2015 Alexandre Fouille 2.7.0-8 +- Fix RPM dependencies. + +* Tue Jan 06 2015 Alexandre Fouille 2.8.0-29 +- Fix rpm dependencies. + +* Mon Jan 05 2015 Alexandre Fouille 2.8.0-28 +- Fix a bug in the daily availability build. + +* Mon Dec 22 2014 Alexandre Fouille 2.8.0-27 +- Fix a bug when the timeperiods only computed one range each day. + +* Fri Dec 19 2014 Alexandre Fouille 2.8.0-26 +- Compute downtime as an exclusive value in BA availabilities. + +* Thu Dec 18 2014 Alexandre Fouille 2.8.0-25 +- Compute the BA of meta services in the BA module. +- Manage ba event durations outside of timeperiods. + +* Wed Dec 17 2014 Alexandre Fouille 2.8.0-24 +- Fix a bug in the availability computation of a DST day. + +* Wed Dec 17 2014 Alexandre Fouille 2.8.0-23 +- Fix timezone and DST handling in availability computation in the BAM module. + +* Tue Dec 16 2014 Alexandre Fouille 2.8.0-22 +- Fix availabilities computing in BAM module. + +* Tue Dec 16 2014 Alexandre Fouille 2.8.0-21 +- Close unfinished BA/KPI events on startup in the BAM module. +- Fix a bug which would sometimes cause the BA availability to not be computed on rebuild. +- New sql abstraction layer. + +* Thu Dec 11 2014 Matthieu Kermagoret 2.8.0-20 +- Fix BA value when recomputed during a KPI state change. + +* Wed Dec 10 2014 Alexandre Fouille 2.8.0-19 +- Performance amelioration in the handling of timezone. + +* Wed Dec 10 2014 Alexandre Fouille 2.8.0-18 +- Build the BAM availabilities in the [00:00, 23:59] range. + +* Wed Dec 10 2014 Alexandre Fouille 2.8.0-17 +- Correctly manage the timezones in multiple different threads. + +* Tue Dec 09 2014 Alexandre Fouille 2.8.0-16 +- Correctly compute the availabilities of opened and not closed events in BAM module. + +* Tue Dec 09 2014 Alexandre Fouille 2.8.0-15 +- Fix a NULL mangling in a mysql statement in BAM module. + +* Mon Dec 08 2014 Alexandre Fouille 2.8.0-14 +- Solve an infinite loop in timeperiod resolution in BAM module. + +* Mon Dec 08 2014 Alexandre Fouille 2.8.0-13 +- Allows the BAM module events to be filtered. + +* Mon Dec 08 2014 Alexandre Fouille 2.8.0-12 +- Cache the dimension insertion in BAM module and commit everything at once. + +* Fri Dec 05 2014 Alexandre Fouille 2.8.0-11 +- Insert the events in database when there is a gap in event continuity in BAM module. + +* Thu Dec 04 2014 Alexandre Fouille 2.8.0-10 +- Fix a segfault in some case when the availability thread exit in BAM module. +- Change the sla month field names in BAM module. + +* Thu Dec 04 2014 Alexandre Fouille 2.8.0-9 +- Properly make a join for the delete of event durations in the BAM module. +- Add info logs for rebuild in the BAM module. + +* Tue Dec 02 2014 Alexandre Fouille 2.8.0-8 +- Don't load the last_level as last hard state in the BAM module. + +* Mon Dec 01 2014 Matthieu Kermagoret 2.8.0-7 +- Properly handle BA/timeperiods relations in the BAM module. + +* Wed Nov 19 2014 Matthieu Kermagoret 2.8.0-6 +- New BAM reporting endpoint (for use with Centreon BI). + +* Wed Nov 19 2014 Alexandre Fouille 3.0.0-2 +- Replace rt_data_bin by log_data_bin. + +* Tue Nov 18 2014 Matthieu Kermagoret 2.7.0-7 +- Fix potential crash at RRD file creation. +- Properly update the /command_line/ field of hosts and services tables. + +* Mon Oct 27 2014 Alexandre Fouille 2.7.0-6 +- By default, set the instance timeout at 5 minutes. +- If the instance timeout is 0, deactivate the option. + +* Fri Oct 24 2014 Alexandre Fouille 2.7.0-5 +- Create the instance_timeout option. +- Set tcp keep alive options on tcp connections. + +* Wed Sep 03 2014 Matthieu Kermagoret 2.7.0-3 +- Fix SQL cleanup queries. +- Set outdate timeout to 30 seconds. +- Set outdate mechanism to work with soft states. + +* Thu Aug 28 2014 Matthieu Kermagoret 2.7.0-2 +- Remove dependency on openssl-devel. + +* Thu Aug 28 2014 Matthieu Kermagoret 2.6.3-6 +- Remove dependency on openssl-devel. + +* Thu Aug 28 2014 Matthieu Kermagoret 2.8.0-5 +- Remove dependency on openssl-devel. + +* Wed Aug 20 2014 Matthieu Kermagoret 2.8.0-4 +- Merge all fixes of previous release. +- Globally improve the BAM engine. + +* Tue Aug 19 2014 Matthieu Kermagoret 2.6.3-5 +- data_bin value is FLOAT, not DOUBLE. + +* Tue Aug 05 2014 Matthieu Kermagoret 2.6.3-4 +- Properly insert infinity values in MySQL. + +* Fri Jul 18 2014 Matthieu Kermagoret 2.6.3-3 +- Use +/-INFINITY, not DBL_MAX/DBL_MIN. + +* Tue Jul 08 2014 Matthieu Kermagoret 2.8.0-3 +- Add missing changelog entries in spec. + +* Tue Jul 08 2014 Matthieu Kermagoret 2.8.0-2 +- Add missing BAM module in spec. + +* Tue Jul 08 2014 Matthieu Kermagoret 2.8.0-1 +- Add BAM module + +* Mon Jul 07 2014 Matthieu Kermagoret 2.6.3-2 +- Handle infinity for graph rebuild. + +* Wed Jun 25 2014 Matthieu Kermagoret 2.6.3-1 +- Handle infinity for metric values. + +* Thu Jun 12 2014 Matthieu Kermagoret 2.6.2-1 +- Read compression buffer back. +- Group memberships are properly dropped. + +* Tue Apr 08 2014 Matthieu Kermagoret 2.7.0-1 +- Send statistics events +- Deletion thread +- Instance ID filtering + +* Tue Mar 04 2014 Matthieu Kermagoret 2.6.1-2 +- Add dependency of centreon-broker-core towards centreon-broker-storage. + +* Tue Feb 18 2014 Matthieu Kermagoret 2.6.1-1 +- Add g+w right on files created by the RRD module. + +* Thu Jan 09 2014 Matthieu Kermagoret 2.6.0-8 +- Once again, fix RRD file creation, hopefully for the last time. + +* Tue Jan 07 2014 Matthieu Kermagoret 2.6.0-7 +- Really fix RRD file creation. +- Various minor fixes. + +* Thu Dec 19 2013 Matthieu Kermagoret 2.6.0-6 +- Fix RRD file creation that used sendfile() (not working on Linux < 2.6.33). + +* Tue Dec 17 2013 Dorian Guillois 2.6.0-5 +- Add instance id into all broker events. + +* Wed Dec 11 2013 Dorian Guillois 2.6.0-4 +- Hostgroup filter in the wind. +- Add filtering events. +- Add one peer retention mode option. +- Change DS_name to metric from "value". + +* Tue Dec 10 2013 Dorian Guillois 2.5.1-1 +- Fix lock multiplexing engine during module updates. + +* Tue Nov 26 2013 Matthieu Kermagoret 2.5.0-13 +- properly reread large retention file (> 4 GB) + +* Wed Oct 30 2013 Matthieu Kermagoret 2.5.0-12 +- BBDO retention file could not get resumed in case of early termination + +* Thu Oct 17 2013 Dorian Guillois 2.5.0-11 +- change centreon-broker spec to use the new cmake package + +* Tue Oct 08 2013 Matthieu Kermagoret 2.5.0-10 +- avoid "invalid row count" issue when creating RRD graphs + +* Fri Sep 13 2013 Matthieu Kermagoret 2.5.0-9 +- exchange BBDO version packets event without negociation + +* Tue Sep 03 2013 Matthieu Kermagoret 2.5.0-8 +- handle group deletion events +- handle dependency deletion events +- avoid duplicate hosts / services on ID change + +* Thu Aug 29 2013 Matthieu Kermagoret 2.5.0-7 +- handle the 'auto' keyword in TLS and compression modules +- avoid dereference of NULL pointer in the failover thread + +* Thu Aug 29 2013 Matthieu Kermagoret 2.5.0-6 +- handle graph locking +- properly generate host dependencies +- runtime configuration update only available with Centreon Engine 1.4+ + +* Wed Aug 28 2013 Matthieu Kermagoret 2.5.0-5 +- add missing libgcrypt init for GNU TLS <= 2.11 in the TLS module + +* Tue Aug 20 2013 Matthieu Kermagoret 2.5.0-4 +- support for Engine configuration update +- diagnostic utility + +* Fri Aug 02 2013 Matthieu Kermagoret 2.5.0-3 +- fix RRD 'invalid row count' creation + +* Wed Jul 31 2013 Matthieu Kermagoret 2.5.0-2 +- fix 'other' startup script +- thread incoming clients with BBDO protocol + +* Wed Jul 03 2013 Matthieu Kermagoret 2.5.0-1 +- new BBDO protocol +- new TLS module based on GNU TLS +- event acknowledgement +- downtime actual start/end time +- perfdata thresholds +- 'store_in_data_bin' +- 'insert_in_index_data' +- retention time per metric + +* Wed Jun 05 2013 Maximilien Bersoult 2.4.4-2 +- Add version dependancy form centreon-common + +* Tue May 21 2013 Matthieu Kermagoret 2.4.5-3 +- create statistics pipe with g+w +- generate status graphs for services without performance data +- fix a crash when time is changed to the past + +* Fri Apr 19 2013 Dorian Guillois 2.4.5-2 +- fix temporary reload. + +* Fri Apr 05 2013 Matthieu Kermagoret 2.4.4-1 +- fix concurrent SIGHUP handlers +- fix configuration diff of sql and storage endpoints + +* Wed Mar 13 2013 Matthieu Kermagoret 2.4.3-1 +- fix cbmod initialization when used with Nagios in daemon mode + +* Mon Mar 11 2013 Matthieu Kermagoret 2.4.2-1 +- fix a crash that arised when SIGHUP'ing a cbd without correlation + +* Wed Mar 06 2013 Matthieu Kermagoret 2.4.1-8 +- use proper tarball + +* Tue Mar 05 2013 Matthieu Kermagoret 2.4.1-7 +- fix correlation module to handle SIGHUP + +* Tue Feb 26 2013 Matthieu Kermagoret 2.4.1-6 +- properly insert initial states logs + +* Mon Feb 25 2013 Matthieu Kermagoret 2.4.1-5 +- apply realpath() on status and metrics RRD directories +- added new 'blocked' and 'listening' states for endpoint statistics +- separate long and short outputs with a '\n' inbetween + +* Wed Feb 13 2013 Julien Mathis 2.4.1-1 +- New version of centreon-broker: fix the problem with the delete of data in data_bin table + +* Fri Jan 25 2013 Julien Mathis 2.4.0-18 +- change order of broker instance in master.run + +* Mon Jan 07 2013 Matthieu Kermagoret 2.4.0-16 +- file's default max_size is unlimited +- TLS certificates are now checked + +* Thu Jan 03 2013 Matthieu Kermagoret 2.4.0-15 +- remove statistics FIFO file at shutdown +- prevent TCP sockets from consuming too much memory +- files can be splitted +- proper downtime deletion time in all cases +- update time management in events + +* Thu Dec 06 2012 Maximilien Bersoult 2.4.0-14 +- Fix /etc/init.d/cbd right +- Modify make install with DESTDIR + +* Wed Dec 05 2012 Maximilien Bersoult 2.4.0-13 +- Change user by centreon-broker +- Change the init.d script + +* Thu Nov 29 2012 Matthieu Kermagoret 2.4.0-12 +- properly update must_be_rebuild flag when rebuilding graphs + +* Tue Nov 27 2012 Matthieu Kermagoret 2.4.0-11 +- statuses of passive host/service are properly updated +- temporary endpoint +- splittable files with maximum size + +* Mon Nov 26 2012 Matthieu Kermagoret 2.4.0-10 +- optimized NDO protocol +- set locale when using cbmod +- use last check time for opening/deletin correlation issues +- fix segfault at restart + +* Fri Nov 02 2012 Matthieu Kermagoret 2.4.0-9 +- fix segfault at restart + +* Thu Oct 25 2012 Matthieu Kermagoret 2.4.0-8 +- backport of various fixes + +* Thu Oct 11 2012 Matthieu Kermagoret 2.3.0-9 +- MySQL does not handle all IEEE 754 values + +* Tue Oct 09 2012 Matthieu Kermagoret 2.4.0-7 +- propagate configuration update requests to threads + +* Tue Oct 09 2012 Matthieu Kermagoret 2.4.0-6 +- use FORGET instead of FLUSH to remove RRD file with rrdcached + +* Tue Oct 09 2012 Matthieu Kermagoret 2.4.0-5 +- determine which events should be handled when rebuilding graphs + +* Tue Oct 09 2012 Matthieu Kermagoret 2.4.0-4 +- remove RRD file before rebuilding it + +* Tue Oct 09 2012 Matthieu Kermagoret 2.4.0-3 +- properly insert in status rebuild cache +- typo fix + +* Tue Oct 09 2012 Matthieu Kermagoret 2.4.0-2 +- enum in DB sucks + +* Tue Oct 09 2012 Matthieu Kermagoret 2.4.0-1 +- handle graph rebuild + +* Fri Oct 05 2012 Matthieu Kermagoret 2.3.0-8 +- the data_source_type field of the metrics table is now filled + +* Fri Oct 05 2012 Matthieu Kermagoret 2.2.2-2 +- ignore some storage errors to prevent premature shutdown +- fixed SysV init script + +* Thu Oct 04 2012 Matthieu Kermagoret 2.2.2-1 +- rebranded last build as a new release + +* Mon Oct 01 2012 Matthieu Kermagoret 2.2.1-14 +- host statuses were not updated +- non-persistent comments had their deletion time changed +- order of custom macro definition does not matter anymore + +* Fri Sep 21 2012 Matthieu Kermagoret 2.3.0-7 +- make the storage::stream::read method throw + +* Thu Sep 20 2012 Matthieu Kermagoret 2.2.1-13 +- the storage::stream::read method must throw + +* Wed Sep 19 2012 Matthieu Kermagoret 2.3.0-6 +- new 'check_replication' option for SQL and Storage endpoints + +* Wed Sep 19 2012 Matthieu Kermagoret 2.3.0-5 +- fetch data_source_type from DB enum properly + +* Wed Sep 19 2012 Matthieu Kermagoret 2.3.0-4 +- handle the data_source_type value from the metrics table + +* Tue Sep 18 2012 Matthieu Kermagoret 2.3.0-3 +- NDO protocol discarded some precision of high double values + +* Tue Sep 18 2012 Matthieu Kermagoret 2.3.0-2 +- non-GAUGE RRD files only handle integer values + +* Mon Sep 17 2012 Matthieu Kermagoret 2.3.0-1 +- handle ABSOLUTE, COUNTER, DERIVE and GAUGE graph types + +* Thu Sep 13 2012 Matthieu Kermagoret 2.2.1-12 +- store passive host/service status regardless of their time + +* Thu Sep 13 2012 Matthieu Kermagoret 2.2.1-11 +- remove non-persistent comments on instance startup + +* Wed Sep 12 2012 Matthieu Kermagoret 2.1.3-1 +- remove non-persistent comments on instance startup + +* Wed Sep 05 2012 Matthieu Kermagoret 2.2.1-10 +- ignore UPDATE errors with rrdcached + +* Wed Sep 05 2012 Matthieu Kermagoret 2.2.1-9 +- correctly read rrdcached output + +* Wed Sep 05 2012 Matthieu Kermagoret 2.2.1-8 +- put a '\n' after each command sent to rrdcached + +* Wed Sep 05 2012 Matthieu Kermagoret 2.2.1-7 +- flush commands sent to rrdcached + +* Fri Aug 31 2012 Matthieu Kermagoret 2.2.1-6 +- removed flock from RRD module + +* Fri Aug 31 2012 Matthieu Kermagoret 2.2.1-5 +- fix a previous commit that was not properly pushed + +* Fri Aug 31 2012 Matthieu Kermagoret 2.1.2-4 +- fix error detection on TLS streams (invalid fix application) + +* Wed Aug 29 2012 Matthieu Kermagoret 2.2.1-4 +- backport of the 2.1.2 release in the 2.2 branch +- ignore SIGCHLD when loading Qt in NEB module + +* Tue Aug 28 2012 Matthieu Kermagoret 2.1.2-3 +- fix module (cbmod) shutdown + +* Mon Aug 27 2012 Matthieu Kermagoret 2.1.2-2 +- fix error detection on TLS streams + +* Mon Aug 20 2012 Matthieu Kermagoret 2.1.2-1 +- backported fixes of the 2.2 branch within 2.1 + +* Wed Aug 08 2012 Matthieu Kermagoret 2.2.1-3 +- infinite loop in the failover thread in some specific cases + +* Mon Aug 06 2012 Matthieu Kermagoret 2.2.1-2 +- compression does not propagate close signal upon termination +- uncompression does not work some times + +* Thu Aug 02 2012 Matthieu Kermagoret 2.2.1-1 +- compression module never got loaded +- shutdown does not properly close TCP connections +- unnecessary heavy CPU use + +* Tue Jul 24 2012 Maximilien Bersoult 2.2.0-3 +- Modify right to daemon binary + +* Tue Jul 24 2012 Maximilien Bersoult 2.2.0-2 +- Check user exists before add group + +* Tue Jul 24 2012 Matthieu Kermagoret 2.2.0-1 +- SQL supports transactions +- fix floating-point exception in RRD module +- Broker can log in monitoring engine log file +- fix compression module +- new statistics module + +* Fri Apr 13 2012 Dorian Guillois 2.1.1-2 +- Add logrotate script. + +* Fri Feb 10 2012 Maximilien Bersout 2.1.1-1 +- Add better metrics name support + +* Wed Feb 01 2012 Maximilien Bersout 2.1.0-1 +- Add information for delete downtime and acknowledgement + +* Tue Jan 24 2012 Maximilien Bersout 2.0.1-1 +- Deactivation hosts without services when stopping the instance +- Remove Qt actions in Nagios when cbmod does not initialize + +* Fri Jun 10 2011 Maximilien Bersout 2.0.0-1 +- Update to new version 2.0.0 +- Change rpm output +- Add module storage for Nagios perfdata + +* Mon Apr 18 2011 Cedric Temple 1.2.1-1 +- Update to new version 1.2.1 +- add check configuration file in init script + +* Thu Apr 14 2011 Cedric Temple 1.2.0-3 +- restaure centreon-broker dependancie (for log creation) +- add user centreon +- add log directory +- add configuration file +- add init script + +* Tue Apr 12 2011 Cedric Temple 1.2.0-2 +- Add PATH to qmake +- add requires to all packages +- remove centreon-broker dependancie + +* Tue Apr 05 2011 Matthieu Kermagoret 1.2.0-1 +- Initial build diff --git a/centreon-broker/packaging/rpm/debian/centreon-broker-cbmod.postinst b/centreon-broker/packaging/rpm/debian/centreon-broker-cbmod.postinst new file mode 100755 index 00000000000..dad085cefeb --- /dev/null +++ b/centreon-broker/packaging/rpm/debian/centreon-broker-cbmod.postinst @@ -0,0 +1,8 @@ +#!/bin/sh + +if [ "$1" = "configure" ] ; then + usermod -a -G centreon-broker centreon-engine + usermod -a -G centreon-engine centreon-broker +fi + +#DEBHELPER# diff --git a/centreon-broker/packaging/rpm/debian/centreon-broker-cbmod.triggers b/centreon-broker/packaging/rpm/debian/centreon-broker-cbmod.triggers new file mode 100644 index 00000000000..dd866036784 --- /dev/null +++ b/centreon-broker/packaging/rpm/debian/centreon-broker-cbmod.triggers @@ -0,0 +1 @@ +activate-noawait ldconfig diff --git a/centreon-broker/packaging/rpm/debian/centreon-broker-core.postinst b/centreon-broker/packaging/rpm/debian/centreon-broker-core.postinst new file mode 100755 index 00000000000..4c46c16e069 --- /dev/null +++ b/centreon-broker/packaging/rpm/debian/centreon-broker-core.postinst @@ -0,0 +1,9 @@ +#!/bin/sh + +if [ "$1" = "configure" ] ; then + adduser --system --group --home /var/lib/centreon-broker --no-create-home centreon-broker + usermod -a -G centreon-broker centreon + chown -R centreon-broker:centreon-broker /etc/centreon-broker /var/lib/centreon-broker /var/log/centreon-broker +fi + +#DEBHELPER# diff --git a/centreon-broker/packaging/rpm/debian/centreon-broker-core.postrm b/centreon-broker/packaging/rpm/debian/centreon-broker-core.postrm new file mode 100755 index 00000000000..242ca3cd6e5 --- /dev/null +++ b/centreon-broker/packaging/rpm/debian/centreon-broker-core.postrm @@ -0,0 +1,7 @@ +#!/bin/sh + +deluser centreon centreon-broker || true +deluser centreon-broker || true +delgroup centreon-broker || true + +#DEBHELPER# diff --git a/centreon-broker/packaging/rpm/debian/changelog.in b/centreon-broker/packaging/rpm/debian/changelog.in new file mode 100644 index 00000000000..46405df1271 --- /dev/null +++ b/centreon-broker/packaging/rpm/debian/changelog.in @@ -0,0 +1,5 @@ +centreon-broker (@VERSION@-@RELEASE@) UNRELEASED; urgency=medium + + * Release. + + -- Matthieu Kermagoret Thu, 13 Jul 2017 10:40:36 +0200 diff --git a/centreon-broker/packaging/rpm/debian/compat b/centreon-broker/packaging/rpm/debian/compat new file mode 100644 index 00000000000..f599e28b8ab --- /dev/null +++ b/centreon-broker/packaging/rpm/debian/compat @@ -0,0 +1 @@ +10 diff --git a/centreon-broker/packaging/rpm/debian/control b/centreon-broker/packaging/rpm/debian/control new file mode 100644 index 00000000000..9bd521516ce --- /dev/null +++ b/centreon-broker/packaging/rpm/debian/control @@ -0,0 +1,52 @@ +Source: centreon-broker +Section: net +Priority: optional +Maintainer: Matthieu Kermagoret +Build-Depends: debhelper (>=10), cmake, libgnutls28-dev, librrd-dev, lsb-base, make (>=3), zlib1g-dev +Standards-Version: 3.9.8 +Homepage: https://github.com/centreon/centreon-broker + +Package: centreon-broker-core +Architecture: any +Depends: centreon-common, ${shlibs:Depends}, ${misc:Depends} +Description: Centreon Broker core components. + Contains all Centreon Broker components shared by cbd or cbmod. + +Package: centreon-broker-graphite +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends} +Description: This module of Centreon Broker allows you to write performance data + generated by plugins (run themselves by Centreon Engine) to a Graphite + database. + +Package: centreon-broker-influxdb +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends} +Description: This module of Centreon Broker allows you to write performance data + generated by plugins (run themselves by Centreon Engine) to an InfluxDB + database. + +Package: centreon-broker-cbd +Architecture: any +Depends: centreon-broker-core, ${shlibs:Depends}, ${misc:Depends} +Description: Centreon Broker daemon can aggregates output of multiple + cbmod and store events in a DB from a single point. + +Package: centreon-broker-cbmod +Architecture: any +Depends: centreon-engine, centreon-broker-core, ${shlibs:Depends}, ${misc:Depends} +Description: Centreon Broker module for Centreon Engine. + Listen for monitoring events of Centreon Engine and convert them the + Centreon Broker way. + +Package: centreon-broker +Architecture: any +Depends: centreon-broker-cbd, centreon-broker-cbmod, ${misc:Depends} +Description: Data processing component of the Centreon software suite. + Generate, transmit and store monitoring events in various ways. + +Package: centreon-broker-dev +Architecture: any +Depends: ${misc:Depends} +Description: Centreon Broker development files. + Include files needed to develop a module for Centreon Broker. diff --git a/centreon-broker/packaging/rpm/debian/copyright b/centreon-broker/packaging/rpm/debian/copyright new file mode 100644 index 00000000000..50dba506d4e --- /dev/null +++ b/centreon-broker/packaging/rpm/debian/copyright @@ -0,0 +1 @@ +See /usr/share/common-licenses/Apache-2.0 diff --git a/centreon-broker/packaging/rpm/debian/rules b/centreon-broker/packaging/rpm/debian/rules new file mode 100755 index 00000000000..dc3a42f7f23 --- /dev/null +++ b/centreon-broker/packaging/rpm/debian/rules @@ -0,0 +1,51 @@ +#!/usr/bin/make -f + +export DH_VERBOSE=1 +export ABI=$(shell grep -q "ABI=1" CMakeLists.txt && echo -n 11) +export USE_CXX11=$(shell grep -q "ABI=1" CMakeLists.txt && echo -n 1 || echo -n 0) + +%: + dh $@ + +override_dh_auto_configure: + conan install -s arch=$(ARCH) -s compiler.libcxx=libstdc++$(ABI) . + CXXFLAGS="-std=c++11 -O2 -DNDEBUG" cmake \ + -DUSE_CXX11_ABI=$(USE_CXX11) \ + -DWITH_TESTING=0 \ + -DWITH_PREFIX=/usr \ + -DWITH_PREFIX_CONF=/etc/centreon-broker \ + -DWITH_PREFIX_LIB=/usr/lib/centreon-broker \ + -DWITH_PREFIX_MODULES=/usr/lib/centreon-broker/modules \ + -DWITH_PREFIX_VAR=/var/lib/centreon-broker \ + -DWITH_STARTUP_SCRIPT=systemd \ + -DWITH_STARTUP_DIR=/lib/systemd/system \ + -DWITH_DAEMONS='central-rrd;central-broker' \ + -DWITH_CONFIG_FILES=y \ + . + +override_dh_auto_install: +# centreon-broker-core + make install DESTDIR=debian/centreon-broker-core + mkdir -p debian/centreon-broker-core/var/lib/centreon-broker + mkdir -p debian/centreon-broker-core/var/log/centreon-broker +# centreon-broker-graphite + mkdir -p debian/centreon-broker-graphite/usr/lib/centreon-broker/modules + mv debian/centreon-broker-core/usr/lib/centreon-broker/modules/*graphite* debian/centreon-broker-graphite/usr/lib/centreon-broker/modules/ +# centreon-broker-influxdb + mkdir -p debian/centreon-broker-influxdb/usr/lib/centreon-broker/modules + mv debian/centreon-broker-core/usr/lib/centreon-broker/modules/*influxdb* debian/centreon-broker-influxdb/usr/lib/centreon-broker/modules/ +# centreon-broker-cbd + mkdir -p debian/centreon-broker-cbd/usr/bin + mv debian/centreon-broker-core/usr/bin/cbd debian/centreon-broker-cbd/usr/bin/ +# centreon-broker-cbmod + mkdir -p debian/centreon-broker-cbmod/usr/lib/centreon-broker + mv debian/centreon-broker-core/usr/lib/centreon-broker/cbmod.so debian/centreon-broker-cbmod/usr/lib/centreon-broker/ +# centreon-broker + mkdir -p debian/centreon-broker +# centreon-broker-dev + mkdir -p debian/centreon-broker-dev/usr/include + mv debian/centreon-broker-core/usr/include/centreon-broker debian/centreon-broker-dev/usr/include/ + +override_dh_fixperms: + dh_fixperms + chmod -R g+w debian/centreon-broker-core/etc/centreon-broker debian/centreon-broker-core/var/lib/centreon-broker debian/centreon-broker-core/var/log/centreon-broker diff --git a/centreon-broker/packaging/rpm/debian/source/format b/centreon-broker/packaging/rpm/debian/source/format new file mode 100644 index 00000000000..163aaf8d82b --- /dev/null +++ b/centreon-broker/packaging/rpm/debian/source/format @@ -0,0 +1 @@ +3.0 (quilt) diff --git a/centreon-broker/packaging/script/rpmbuild.sh b/centreon-broker/packaging/script/rpmbuild.sh new file mode 100755 index 00000000000..b08e4e53d07 --- /dev/null +++ b/centreon-broker/packaging/script/rpmbuild.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +show_help() { +cat << EOF +Usage: ${0##*/} -n=[yes|no] -v + +This program build Centreon-broker + + -v : major version + -r : release number + -h : help +EOF +exit 2 +} + +VERSION=$1 +RELEASE=$2 + +if [ -z $VERSION ] || [ -z $RELEASE ] ; then + echo "Some or all of the parameters are empty"; + echo $VERSION; + echo $RELEASE; + show_help +fi + +ln -s /usr/bin/cmake3 /usr/bin/cmake + +# dossier racine du nouveau centreon collect +if [ ! -d /root/rpmbuild/SOURCES ] ; then + mkdir -p /root/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} +fi + +cd "../../../" + +mkdir centreon-broker-$VERSION +cp -r centreon-broker/* centreon-broker-$VERSION +tar -czf centreon-broker-$VERSION.tar.gz centreon-broker-$VERSION cmake.sh +mv centreon-broker-$VERSION.tar.gz /root/rpmbuild/SOURCES/ +rm -rf centreon-broker-$VERSION + +rpmbuild -ba centreon-broker/packaging/rpm/centreon-broker.spectemplate -D "VERSION $VERSION" -D "RELEASE $RELEASE" + diff --git a/centreon-broker/rrd/CMakeLists.txt b/centreon-broker/rrd/CMakeLists.txt index af3d8868a47..cbf0c8e8990 100644 --- a/centreon-broker/rrd/CMakeLists.txt +++ b/centreon-broker/rrd/CMakeLists.txt @@ -21,7 +21,7 @@ set(INC_DIR "${PROJECT_SOURCE_DIR}/rrd/inc") set(SRC_DIR "${PROJECT_SOURCE_DIR}/rrd/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/rrd/test") include_directories("${INC_DIR}") -include_directories("${CMAKE_SOURCE_DIR}") +include_directories("${PROJECT_SOURCE_DIR}/storage/inc") include_directories("${PROJECT_SOURCE_DIR}/neb/inc") # Find librrd. @@ -49,8 +49,6 @@ else () set(LIBRRD_LDFLAGS "${LIBRRD_LDFLAGS}" PARENT_SCOPE) endif () -get_protobuf_files(rebuild) - # RRD module. set(RRD "70-rrd") set(RRD "${RRD}" PARENT_SCOPE) @@ -62,7 +60,6 @@ add_library("${RRD}" SHARED "${SRC_DIR}/lib.cc" "${SRC_DIR}/main.cc" "${SRC_DIR}/output.cc" - ${proto_rebuild} # Headers. "${INC_DIR}/com/centreon/broker/rrd/backend.hh" "${INC_DIR}/com/centreon/broker/rrd/connector.hh" @@ -86,7 +83,7 @@ if (LIBRRD_CFLAGS) COMPILE_FLAGS "${LIBRRD_CFLAGS}") endif () endif () -target_link_libraries("${RRD}" ${LIBRRD_LDFLAGS} bbdo_storage) +target_link_libraries("${RRD}" ${LIBRRD_LDFLAGS}) # Testing. if (WITH_TESTING) diff --git a/centreon-broker/rrd/inc/com/centreon/broker/rrd/backend.hh b/centreon-broker/rrd/inc/com/centreon/broker/rrd/backend.hh index fa2cf69db83..c1e564581f5 100644 --- a/centreon-broker/rrd/inc/com/centreon/broker/rrd/backend.hh +++ b/centreon-broker/rrd/inc/com/centreon/broker/rrd/backend.hh @@ -20,7 +20,6 @@ #define CCB_RRD_BACKEND_HH #include -#include #include #include "com/centreon/broker/namespace.hh" @@ -56,7 +55,6 @@ class backend { short value_type = 0) = 0; virtual void remove(std::string const& filename) = 0; virtual void update(time_t t, std::string const& value) = 0; - virtual void update(const std::list& pts) = 0; }; } // namespace rrd diff --git a/centreon-broker/rrd/inc/com/centreon/broker/rrd/cached.hh b/centreon-broker/rrd/inc/com/centreon/broker/rrd/cached.hh index 630ea80c4e8..b295f051715 100644 --- a/centreon-broker/rrd/inc/com/centreon/broker/rrd/cached.hh +++ b/centreon-broker/rrd/inc/com/centreon/broker/rrd/cached.hh @@ -130,7 +130,7 @@ class cached : public backend { * * @param[in] command Command to send. */ - void _send_to_cached(const std::string& command) { + void _send_to_cached(std::string const& command) { std::error_code err; asio::write(_socket, asio::buffer(command), asio::transfer_all(), err); @@ -288,23 +288,6 @@ class cached : public backend { _filename, e.what() + 5); } } - - void update(const std::list& pts) { - log_v2::rrd()->debug("RRD: updating file '{}' with {} values", _filename, - pts.size()); - - std::string cmd{ - fmt::format("UPDATE {} {}\n", _filename, fmt::join(pts, " "))}; - try { - _send_to_cached(cmd); - } catch (msg_fmt const& e) { - if (!strstr(e.what(), "illegal attempt to update using time")) - throw exceptions::update(e.what()); - else - log_v2::rrd()->error("RRD: ignored update error in file '{}': {}", - _filename, e.what() + 5); - } - } }; } // namespace rrd diff --git a/centreon-broker/rrd/inc/com/centreon/broker/rrd/lib.hh b/centreon-broker/rrd/inc/com/centreon/broker/rrd/lib.hh index f6ae915e3b5..4e8cd310df0 100644 --- a/centreon-broker/rrd/inc/com/centreon/broker/rrd/lib.hh +++ b/centreon-broker/rrd/inc/com/centreon/broker/rrd/lib.hh @@ -53,7 +53,6 @@ class lib : public backend { short value_type = 0); void remove(std::string const& filename); void update(time_t t, std::string const& value); - void update(const std::list& pts); private: creator _creator; diff --git a/centreon-broker/rrd/src/creator.cc b/centreon-broker/rrd/src/creator.cc index c7a6727277b..58742ae4359 100644 --- a/centreon-broker/rrd/src/creator.cc +++ b/centreon-broker/rrd/src/creator.cc @@ -30,11 +30,10 @@ #include #include -#include "bbdo/storage/metric.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/rrd/creator.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" +#include "com/centreon/broker/storage/perfdata.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; @@ -228,13 +227,13 @@ void creator::_open(std::string const& filename, { const char* tt; switch (value_type) { - case misc::perfdata::absolute: + case storage::perfdata::absolute: tt = "ABSOLUTE"; break; - case misc::perfdata::counter: + case storage::perfdata::counter: tt = "COUNTER"; break; - case misc::perfdata::derive: + case storage::perfdata::derive: tt = "DERIVE"; break; default: diff --git a/centreon-broker/rrd/src/lib.cc b/centreon-broker/rrd/src/lib.cc index 78684fde68f..ba261d35832 100644 --- a/centreon-broker/rrd/src/lib.cc +++ b/centreon-broker/rrd/src/lib.cc @@ -27,14 +27,20 @@ #include #include -#include "bbdo/storage/metric.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" #include "com/centreon/broker/rrd/exceptions/update.hh" +#include "com/centreon/broker/storage/perfdata.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; +/************************************** + * * + * Public Methods * + * * + **************************************/ + /** * Constructor. * @@ -163,25 +169,3 @@ void lib::update(time_t t, std::string const& value) { _filename, msg); } } - -void lib::update(const std::list& pts) { - const char* argv[pts.size() + 1]; - argv[pts.size()] = nullptr; - auto it = pts.begin(); - for (uint32_t i = 0; i < pts.size(); i++) { - argv[i] = it->data(); - ++it; - } - rrd_clear_error(); - if (rrd_update_r(_filename.c_str(), nullptr, sizeof(argv) / sizeof(*argv) - 1, - argv)) { - char const* msg(rrd_get_error()); - if (!strstr(msg, "illegal attempt to update using time")) - log_v2::rrd()->error("RRD: failed to update value in file '{}': {}", - _filename, msg); - - else - log_v2::rrd()->error("RRD: ignored update error in file '{}': {}", - _filename, msg); - } -} diff --git a/centreon-broker/rrd/src/main.cc b/centreon-broker/rrd/src/main.cc index 042800a2fb6..be15689f6f0 100644 --- a/centreon-broker/rrd/src/main.cc +++ b/centreon-broker/rrd/src/main.cc @@ -18,17 +18,9 @@ #include -#include "bbdo/storage/index_mapping.hh" -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/metric_mapping.hh" -#include "bbdo/storage/rebuild.hh" -#include "bbdo/storage/remove_graph.hh" -#include "bbdo/storage/status.hh" -#include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/rrd/factory.hh" -#include "com/centreon/broker/rrd/internal.hh" using namespace com::centreon::broker; @@ -47,7 +39,7 @@ char const* broker_module_version = CENTREON_BROKER_VERSION; * @return An array of const char* */ const char* const* broker_module_parents() { - constexpr static const char* retval[]{"10-neb.so", nullptr}; + constexpr static const char* retval[]{"10-neb.so", "20-storage.so", nullptr}; return retval; } @@ -80,33 +72,6 @@ void broker_module_init(void const* arg) { log_v2::rrd()->info("RRD: using rrdtool {}", (rrdversion ? rrdversion : "(unknown)")); - io::events& e(io::events::instance()); - - // Register events. - { - e.register_event(make_type(io::storage, storage::de_metric), "metric", - &storage::metric::operations, storage::metric::entries, - "rt_metrics"); - e.register_event(make_type(io::storage, storage::de_rebuild), "rebuild", - &storage::rebuild::operations, - storage::rebuild::entries); - e.register_event(make_type(io::storage, storage::de_remove_graph), - "remove_graph", &storage::remove_graph::operations, - storage::remove_graph::entries); - e.register_event(make_type(io::storage, storage::de_status), "status", - &storage::status::operations, storage::status::entries); - e.register_event(make_type(io::storage, storage::de_index_mapping), - "index_mapping", &storage::index_mapping::operations, - storage::index_mapping::entries); - e.register_event(make_type(io::storage, storage::de_metric_mapping), - "metric_mapping", &storage::metric_mapping::operations, - storage::metric_mapping::entries); - log_v2::bbdo()->info("registering protobuf pb_rebuild as {:x}:{:x}", - io::storage, storage::de_pb_rebuild); - e.register_event(storage_pb_rebuild, "pb_rebuild", - &storage::pb_rebuild::operations); - } - // Register RRD layer. io::protocols::instance().reg("RRD", std::make_shared(), 1, 7); diff --git a/centreon-broker/rrd/src/output.cc b/centreon-broker/rrd/src/output.cc index bec1f668221..fb6b3e2818c 100644 --- a/centreon-broker/rrd/src/output.cc +++ b/centreon-broker/rrd/src/output.cc @@ -17,23 +17,20 @@ */ #include "com/centreon/broker/rrd/output.hh" -#include "com/centreon/broker/rrd/internal.hh" -#include #include #include #include +#include -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/rebuild.hh" -#include "bbdo/storage/remove_graph.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" #include "com/centreon/broker/rrd/exceptions/update.hh" +#include "com/centreon/broker/storage/events.hh" +#include "com/centreon/broker/storage/internal.hh" +#include "com/centreon/broker/storage/perfdata.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; @@ -193,7 +190,7 @@ int output::write(std::shared_ptr const& d) { fmt::format("{}{}.rrd", _metrics_path, e->metric_id)); // Check that metric is not being rebuild. - rebuild_cache::iterator it = _metrics_rebuild.find(metric_path); + rebuild_cache::iterator it(_metrics_rebuild.find(metric_path)); if (e->is_for_rebuild || it == _metrics_rebuild.end()) { // Write metrics RRD. try { @@ -204,39 +201,39 @@ int output::write(std::shared_ptr const& d) { _backend.open(metric_path, e->rrd_len, e->ctime - 1, interval, e->value_type); } - std::string v; + std::ostringstream oss; switch (e->value_type) { - case misc::perfdata::gauge: - v = fmt::format("{:f}", e->value); + case storage::perfdata::gauge: + oss << std::fixed << e->value; log_v2::rrd()->trace( "RRD: update metric {} of type GAUGE with {}", e->metric_id, - v); + oss.str()); break; - case misc::perfdata::counter: - v = fmt::format("{}", static_cast(e->value)); + case storage::perfdata::counter: + oss << static_cast(e->value); log_v2::rrd()->trace( "RRD: update metric {} of type COUNTER with {}", e->metric_id, - v); + oss.str()); break; - case misc::perfdata::derive: - v = fmt::format("{}", static_cast(e->value)); + case storage::perfdata::derive: + oss << static_cast(e->value); log_v2::rrd()->trace( "RRD: update metric {} of type DERIVE with {}", e->metric_id, - v); + oss.str()); break; - case misc::perfdata::absolute: - v = fmt::format("{}", static_cast(e->value)); + case storage::perfdata::absolute: + oss << static_cast(e->value); log_v2::rrd()->trace( "RRD: update metric {} of type ABSOLUTE with {}", - e->metric_id, v); + e->metric_id, oss.str()); break; default: - v = fmt::format("{:f}", e->value); + oss << std::fixed << e->value; log_v2::rrd()->trace("RRD: update metric {} of type {} with {}", - e->metric_id, e->value_type, v); + e->metric_id, e->value_type, oss.str()); break; } - _backend.update(e->ctime, v); + _backend.update(e->ctime, oss.str()); } else // Cache value. it->second.push_back(d); @@ -281,86 +278,6 @@ int output::write(std::shared_ptr const& d) { it->second.push_back(d); } break; - case storage::pb_rebuild::static_type(): { - std::shared_ptr e{ - std::static_pointer_cast(d)}; - std::string path; - std::list lst; - if (e->obj.has_index_id()) { - log_v2::rrd()->debug("RRD: complete rebuild request for status {}", - e->obj.index_id()); - // Generate path. - path = fmt::format("{}{}.rrd", _status_path, e->obj.index_id()); - time_t start_time = time(nullptr); - if (!e->obj.data().empty()) - start_time = e->obj.data()[0].ctime() - 1; - for (auto& p : e->obj.data()) { - std::string v; - switch (p.status()) { - case 0: - lst.emplace_back(fmt::format("{}:{}", p.ctime(), 100)); - break; - case 1: - lst.emplace_back(fmt::format("{}:{}", p.ctime(), 75)); - break; - case 2: - lst.emplace_back(fmt::format("{}:{}", p.ctime(), 0)); - break; - default: - lst.emplace_back(fmt::format("{}:", p.ctime())); - break; - } - } - _backend.remove(path); - try { - _backend.open(path); - } catch (exceptions::open const& b) { - time_t interval{e->obj.interval() ? e->obj.interval() : 60}; - _backend.open(path, e->obj.length(), start_time, interval); - } - _backend.update(lst); - } else { - log_v2::rrd()->debug("RRD: complete rebuild request for metric {}", - e->obj.metric().metric_id()); - time_t start_time = time(nullptr); - if (!e->obj.data().empty()) - start_time = e->obj.data()[0].ctime() - 1; - // Generate path. - path = - fmt::format("{}{}.rrd", _metrics_path, e->obj.metric().metric_id()); - std::string v; - switch (e->obj.metric().value_type()) { - case misc::perfdata::gauge: - for (auto& p : e->obj.data()) - lst.emplace_back(fmt::format("{}:{:f}", p.ctime(), p.value())); - break; - case misc::perfdata::counter: - case misc::perfdata::absolute: - for (auto& p : e->obj.data()) - lst.emplace_back(fmt::format("{}:{}", p.ctime(), - static_cast(p.value()))); - break; - case misc::perfdata::derive: - for (auto& p : e->obj.data()) - lst.emplace_back(fmt::format("{}:{}", p.ctime(), - static_cast(p.value()))); - break; - default: - for (auto& p : e->obj.data()) - lst.emplace_back(fmt::format("{}:{:f}", p.ctime(), p.value())); - break; - } - _backend.remove(path); - try { - _backend.open(path); - } catch (exceptions::open const& b) { - time_t interval{e->obj.interval() ? e->obj.interval() : 60}; - _backend.open(path, e->obj.length(), start_time, interval, - e->obj.metric().value_type()); - } - _backend.update(lst); - } - } break; case storage::rebuild::static_type(): { // Debug message. std::shared_ptr e( diff --git a/centreon-broker/script/systemd/cbd.service.in b/centreon-broker/script/systemd/cbd.service.in index dc29388e293..97b2262585a 100644 --- a/centreon-broker/script/systemd/cbd.service.in +++ b/centreon-broker/script/systemd/cbd.service.in @@ -24,7 +24,7 @@ ReloadPropagatedFrom=centreon.service After=mariadb.service [Service] -ExecStart=@CMAKE_INSTALL_FULL_SBINDIR@/cbwd @PREFIX_BROKER_CONF@/watchdog.json +ExecStart=@PREFIX_BIN@/cbwd @PREFIX_CONF@/watchdog.json ExecReload=/bin/kill -HUP $MAINPID Type=simple User=centreon-broker diff --git a/centreon-broker/simu/CMakeLists.txt b/centreon-broker/simu/CMakeLists.txt index 4067c3aae50..597012da9d6 100644 --- a/centreon-broker/simu/CMakeLists.txt +++ b/centreon-broker/simu/CMakeLists.txt @@ -21,9 +21,11 @@ set(INC_DIR "${PROJECT_SOURCE_DIR}/simu/inc") set(SRC_DIR "${PROJECT_SOURCE_DIR}/simu/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/simu/test") -include_directories("${INC_DIR}" +include_directories("${INC_DIR}") +include_directories("${PROJECT_SOURCE_DIR}/bam/inc" "${PROJECT_SOURCE_DIR}/lua/inc" - "${PROJECT_SOURCE_DIR}/neb/inc") + "${PROJECT_SOURCE_DIR}/neb/inc" + "${PROJECT_SOURCE_DIR}/storage/inc") set(INC_DIR "${INC_DIR}/com/centreon/broker/simu") # Storage module. @@ -31,12 +33,16 @@ set(SIMU "70-simu") set(SIMU "${SIMU}" PARENT_SCOPE) add_library("${SIMU}" SHARED # Sources. +#"${SRC_DIR}/broker_log.cc" +# "${SRC_DIR}/broker_utils.cc" "${SRC_DIR}/connector.cc" "${SRC_DIR}/factory.cc" "${SRC_DIR}/luabinding.cc" "${SRC_DIR}/main.cc" "${SRC_DIR}/stream.cc" # Headers. +# "${INC_DIR}/broker_log.hh" +# "${INC_DIR}/broker_utils.hh" "${INC_DIR}/connector.hh" "${INC_DIR}/factory.hh" "${INC_DIR}/luabinding.hh" diff --git a/centreon-broker/simu/src/main.cc b/centreon-broker/simu/src/main.cc index b76f2c6e49b..9d2c902e3c1 100644 --- a/centreon-broker/simu/src/main.cc +++ b/centreon-broker/simu/src/main.cc @@ -16,11 +16,6 @@ ** For more information : contact@centreon.com */ -#include "bbdo/storage/index_mapping.hh" -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/metric_mapping.hh" -#include "bbdo/storage/status.hh" -#include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/simu/factory.hh" @@ -29,7 +24,7 @@ using namespace com::centreon::broker; // Load count. -static uint32_t instances{0u}; +static uint32_t instances(0); extern "C" { /** @@ -43,8 +38,8 @@ char const* broker_module_version = CENTREON_BROKER_VERSION; * @return An array of const char* */ const char* const* broker_module_parents() { - constexpr static const char* retval[]{"10-neb.so", "20-bam.so", "70-lua.so", - nullptr}; + constexpr static const char* retval[]{"10-neb.so", "20-bam.so", + "20-storage.so", "70-lua.so", nullptr}; return retval; } @@ -73,23 +68,6 @@ void broker_module_init(void const* arg) { log_v2::core()->info("simu: module for Centreon Broker {}", CENTREON_BROKER_VERSION); - io::events& e(io::events::instance()); - - // Register events. - { - e.register_event(make_type(io::storage, storage::de_metric), "metric", - &storage::metric::operations, storage::metric::entries, - "rt_metrics"); - e.register_event(make_type(io::storage, storage::de_status), "status", - &storage::status::operations, storage::status::entries); - e.register_event(make_type(io::storage, storage::de_index_mapping), - "index_mapping", &storage::index_mapping::operations, - storage::index_mapping::entries); - e.register_event(make_type(io::storage, storage::de_metric_mapping), - "metric_mapping", &storage::metric_mapping::operations, - storage::metric_mapping::entries); - } - // Register simu layer. io::protocols::instance().reg("simu", std::make_shared(), 1, 7); diff --git a/centreon-broker/simu/test/simu.cc b/centreon-broker/simu/test/simu.cc index 5a24b7439a3..aeb9275ec9d 100644 --- a/centreon-broker/simu/test/simu.cc +++ b/centreon-broker/simu/test/simu.cc @@ -20,12 +20,12 @@ #include #include #include -#include "bbdo/storage/status.hh" #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/instance_broadcast.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/simu/luabinding.hh" +#include "com/centreon/broker/storage/status.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; diff --git a/centreon-broker/sql/src/stream.cc b/centreon-broker/sql/src/stream.cc index 3d217c4714e..4dfc927ba4a 100644 --- a/centreon-broker/sql/src/stream.cc +++ b/centreon-broker/sql/src/stream.cc @@ -24,6 +24,7 @@ #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/log_v2.hh" +#include "com/centreon/broker/misc/global_lock.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/neb/internal.hh" diff --git a/centreon-broker/stats/inc/com/centreon/broker/stats/builder.hh b/centreon-broker/stats/inc/com/centreon/broker/stats/builder.hh index 52e8321bcbc..bdf02a558dc 100644 --- a/centreon-broker/stats/inc/com/centreon/broker/stats/builder.hh +++ b/centreon-broker/stats/inc/com/centreon/broker/stats/builder.hh @@ -20,8 +20,8 @@ #ifndef CCB_STATS_BUILDER_HH #define CCB_STATS_BUILDER_HH -#include #include +#include #include #include "com/centreon/broker/namespace.hh" diff --git a/centreon-broker/stats/test/stats.cc b/centreon-broker/stats/test/stats.cc index 9f84dbcb888..8fb287eec84 100644 --- a/centreon-broker/stats/test/stats.cc +++ b/centreon-broker/stats/test/stats.cc @@ -82,32 +82,32 @@ TEST_F(StatsTest, Builder) { ASSERT_TRUE(result["mysql manager"]["delay since last check"].is_string()); } -//TEST_F(StatsTest, BuilderWithModules) { -// stats::builder build; -// auto& modules = config::applier::state::instance().get_modules(); -// modules.apply({"storage/20-storage.so", "neb/10-neb.so", "lua/70-lua.so"}, -// ".", nullptr); -// -// build.build(); -// -// nlohmann::json result; -// ASSERT_NO_THROW(result = nlohmann::json::parse(build.data())); -// -// ASSERT_TRUE(result.is_object()); -// ASSERT_EQ(result["version"], CENTREON_BROKER_VERSION); -// ASSERT_EQ(result["pid"], getpid()); -// ASSERT_TRUE(result["now"].is_string()); -// ASSERT_TRUE(result["asio_version"].is_string()); -// ASSERT_TRUE(result["mysql manager"].is_object()); -// ASSERT_TRUE(result["mysql manager"]["delay since last check"].is_string()); -// -// ASSERT_EQ(result["module./neb/10-neb.so"]["state"].get(), -// "loaded"); -// ASSERT_EQ(result["module./storage/20-storage.so"]["state"].get(), -// "loaded"); -// ASSERT_EQ(result["module./lua/70-lua.so"]["state"].get(), -// "loaded"); -//} +TEST_F(StatsTest, BuilderWithModules) { + stats::builder build; + auto& modules = config::applier::state::instance().get_modules(); + modules.apply({"storage/20-storage.so", "neb/10-neb.so", "lua/70-lua.so"}, + ".", nullptr); + + build.build(); + + nlohmann::json result; + ASSERT_NO_THROW(result = nlohmann::json::parse(build.data())); + + ASSERT_TRUE(result.is_object()); + ASSERT_EQ(result["version"], CENTREON_BROKER_VERSION); + ASSERT_EQ(result["pid"], getpid()); + ASSERT_TRUE(result["now"].is_string()); + ASSERT_TRUE(result["asio_version"].is_string()); + ASSERT_TRUE(result["mysql manager"].is_object()); + ASSERT_TRUE(result["mysql manager"]["delay since last check"].is_string()); + + ASSERT_EQ(result["module./neb/10-neb.so"]["state"].get(), + "loaded"); + ASSERT_EQ(result["module./storage/20-storage.so"]["state"].get(), + "loaded"); + ASSERT_EQ(result["module./lua/70-lua.so"]["state"].get(), + "loaded"); +} class st : public io::stream { public: diff --git a/centreon-broker/storage/CMakeLists.txt b/centreon-broker/storage/CMakeLists.txt index 50c059eaf18..e9ca742f7ae 100644 --- a/centreon-broker/storage/CMakeLists.txt +++ b/centreon-broker/storage/CMakeLists.txt @@ -1,5 +1,5 @@ ## -## Copyright 2011-2013, 2020-2021 Centreon +## Copyright 2011-2013 Centreon ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. @@ -20,9 +20,8 @@ set(INC_DIR "${PROJECT_SOURCE_DIR}/storage/inc") set(SRC_DIR "${PROJECT_SOURCE_DIR}/storage/src") set(TEST_DIR "${PROJECT_SOURCE_DIR}/storage/test") -include_directories("${INC_DIR}" "${SRC_DIR}") +include_directories("${INC_DIR}") include_directories("${PROJECT_SOURCE_DIR}/neb/inc") -include_directories("${CMAKE_SOURCE_DIR}") set(INC_DIR "${INC_DIR}/com/centreon/broker/storage") # conflict_manager library. @@ -41,8 +40,6 @@ set(CONFLICTMGR "conflictmgr" PARENT_SCOPE) set_target_properties(conflictmgr PROPERTIES COMPILE_FLAGS "-fPIC") -get_protobuf_files(rebuild) - # Storage module. set(STORAGE "20-storage") set(STORAGE "${STORAGE}" PARENT_SCOPE) @@ -50,22 +47,38 @@ add_library("${STORAGE}" SHARED # Sources. "${SRC_DIR}/connector.cc" "${SRC_DIR}/factory.cc" + "${SRC_DIR}/index_mapping.cc" "${SRC_DIR}/main.cc" + "${SRC_DIR}/metric.cc" + "${SRC_DIR}/metric_mapping.cc" + "${SRC_DIR}/parser.cc" + "${SRC_DIR}/perfdata.cc" + "${SRC_DIR}/rebuild.cc" "${SRC_DIR}/rebuilder.cc" + "${SRC_DIR}/remove_graph.cc" + "${SRC_DIR}/status.cc" "${SRC_DIR}/stream.cc" - ${proto_rebuild} # Headers. "${INC_DIR}/connector.hh" "${INC_DIR}/events.hh" + "${INC_DIR}/exceptions/perfdata.hh" "${INC_DIR}/factory.hh" + "${INC_DIR}/index_mapping.hh" "${INC_DIR}/internal.hh" + "${INC_DIR}/metric.hh" + "${INC_DIR}/metric_mapping.hh" + "${INC_DIR}/parser.hh" + "${INC_DIR}/perfdata.hh" + "${INC_DIR}/rebuild.hh" "${INC_DIR}/rebuilder.hh" + "${INC_DIR}/remove_graph.hh" + "${INC_DIR}/status.hh" "${INC_DIR}/stream.hh" ) set_target_properties("${STORAGE}" PROPERTIES PREFIX "" COMPILE_FLAGS "-fPIC") -target_link_libraries(${STORAGE} conflictmgr rokerbase bbdo_storage) +target_link_libraries(${STORAGE} conflictmgr) # Testing. if (WITH_TESTING) @@ -79,8 +92,8 @@ if (WITH_TESTING) ${TESTS_SOURCES} ${TEST_DIR}/connector.cc ${TEST_DIR}/metric.cc + ${TEST_DIR}/perfdata.cc ${TEST_DIR}/rebuild.cc - ${TEST_DIR}/rebuild2.cc ${TEST_DIR}/remove_graph.cc ${TEST_DIR}/status.cc ${TEST_DIR}/status-entry.cc diff --git a/centreon-broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh index 9629ec9724f..4d5bc81e355 100644 --- a/centreon-broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/conflict_manager.hh @@ -32,8 +32,8 @@ #include "com/centreon/broker/io/stream.hh" #include "com/centreon/broker/misc/mfifo.hh" #include "com/centreon/broker/misc/pair.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/mysql.hh" +#include "com/centreon/broker/storage/perfdata.hh" #include "com/centreon/broker/storage/stored_timestamp.hh" CCB_BEGIN() @@ -125,12 +125,10 @@ class conflict_manager { bool special; }; - static const std::array metric_type_name; - struct metric_info { bool locked; uint32_t metric_id; - int16_t type; + uint32_t type; double value; std::string unit_name; double warn; diff --git a/centreon-broker/storage/inc/com/centreon/broker/storage/events.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/events.hh index e0aacfa577a..1327b7373e1 100644 --- a/centreon-broker/storage/inc/com/centreon/broker/storage/events.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/events.hh @@ -19,7 +19,7 @@ #ifndef CCB_STORAGE_EVENTS_HH #define CCB_STORAGE_EVENTS_HH -#include "bbdo/storage/metric.hh" +#include "com/centreon/broker/storage/metric.hh" #include "com/centreon/broker/storage/rebuild.hh" #include "com/centreon/broker/storage/remove_graph.hh" #include "com/centreon/broker/storage/status.hh" diff --git a/centreon-broker/storage/inc/com/centreon/broker/storage/exceptions/perfdata.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/exceptions/perfdata.hh new file mode 100644 index 00000000000..e5e7d615071 --- /dev/null +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/exceptions/perfdata.hh @@ -0,0 +1,52 @@ +/* +** Copyright 2011-2013 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_STORAGE_EXCEPTIONS_PERFDATA_HH +#define CCB_STORAGE_EXCEPTIONS_PERFDATA_HH + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/exceptions/msg_fmt.hh" + +using namespace com::centreon::exceptions; + +CCB_BEGIN() + +namespace storage { +namespace exceptions { +/** + * @class perfdata perfdata.hh + * "com/centreon/broker/storage/exceptions/perfdata.hh" + * @brief Perfdata exception. + * + * Exception thrown when handling performance data. + */ +class perfdata : public msg_fmt { + public: + template + explicit perfdata(std::string const& str, const Args&... args) + : msg_fmt(str, args...) {} + perfdata() = delete; + ~perfdata() noexcept {} + perfdata& operator=(const perfdata&) = delete; +}; +} // namespace exceptions +} // namespace storage + +CCB_END() + +#endif // !CCB_STORAGE_EXCEPTIONS_PERFDATA_HH diff --git a/bbdo/storage/index_mapping.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/index_mapping.hh similarity index 91% rename from bbdo/storage/index_mapping.hh rename to centreon-broker/storage/inc/com/centreon/broker/storage/index_mapping.hh index 9c5ce73fa40..0a0e4c2ac7b 100644 --- a/bbdo/storage/index_mapping.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/index_mapping.hh @@ -24,6 +24,7 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/internal.hh" #include "com/centreon/broker/timestamp.hh" CCB_BEGIN() @@ -45,7 +46,8 @@ class index_mapping : public io::data { ~index_mapping() = default; index_mapping& operator=(index_mapping const& other) = delete; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } uint64_t index_id; diff --git a/centreon-broker/storage/inc/com/centreon/broker/storage/internal.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/internal.hh index 5a155a2d440..956cf7cefb1 100644 --- a/centreon-broker/storage/inc/com/centreon/broker/storage/internal.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/internal.hh @@ -19,15 +19,21 @@ #ifndef CCB_STORAGE_INTERNAL_HH #define CCB_STORAGE_INTERNAL_HH -#include "bbdo/events.hh" -#include "bbdo/rebuild.pb.h" -#include "com/centreon/broker/io/protobuf.hh" +#include "com/centreon/broker/namespace.hh" CCB_BEGIN() namespace storage { -using pb_rebuild = io::protobuf; -} +// Data elements. +enum data_element { + de_metric = 1, + de_rebuild, + de_remove_graph, + de_status, + de_index_mapping, + de_metric_mapping +}; +} // namespace storage CCB_END() diff --git a/bbdo/storage/metric.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/metric.hh similarity index 84% rename from bbdo/storage/metric.hh rename to centreon-broker/storage/inc/com/centreon/broker/storage/metric.hh index 0de1c711a25..c53ef502d1b 100644 --- a/bbdo/storage/metric.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/metric.hh @@ -26,6 +26,7 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/internal.hh" #include "com/centreon/broker/timestamp.hh" CCB_BEGIN() @@ -42,17 +43,17 @@ class metric : public io::data { metric(); metric(uint32_t host_id, uint32_t service_id, - const std::string& name, + std::string const& name, timestamp ctime, uint32_t interval, bool is_for_rebuild, uint32_t metric_id, int32_t rrd_len, double value, - int16_t value_type); - metric(const metric&) = delete; - ~metric() noexcept = default; - metric& operator=(const metric&) = delete; + short value_type); + metric(metric const& m) = delete; + ~metric() = default; + metric& operator=(metric const& m) = delete; /** * Get the type of this event. @@ -60,7 +61,8 @@ class metric : public io::data { * @return The event type. */ constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } timestamp ctime; @@ -70,7 +72,7 @@ class metric : public io::data { std::string name; int rrd_len; double value; - int16_t value_type; + short value_type; uint32_t host_id; uint32_t service_id; diff --git a/bbdo/storage/metric_mapping.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/metric_mapping.hh similarity index 94% rename from bbdo/storage/metric_mapping.hh rename to centreon-broker/storage/inc/com/centreon/broker/storage/metric_mapping.hh index 125e5366b60..55a106a83a2 100644 --- a/bbdo/storage/metric_mapping.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/metric_mapping.hh @@ -24,6 +24,7 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/internal.hh" #include "com/centreon/broker/timestamp.hh" CCB_BEGIN() @@ -45,7 +46,7 @@ class metric_mapping : public io::data { ~metric_mapping(); metric_mapping& operator=(metric_mapping const& s); constexpr static uint32_t static_type() { - return io::events::data_type::value; } diff --git a/centreon-broker/storage/inc/com/centreon/broker/storage/parser.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/parser.hh new file mode 100644 index 00000000000..af9f0f4609c --- /dev/null +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/parser.hh @@ -0,0 +1,53 @@ +/* +** Copyright 2011-2013, 2021 Centreon +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +** +** For more information : contact@centreon.com +*/ + +#ifndef CCB_STORAGE_PARSER_HH +#define CCB_STORAGE_PARSER_HH + +#include +#include + +#include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/perfdata.hh" + +CCB_BEGIN() + +namespace storage { +/** + * @class parser parser.hh "com/centreon/broker/storage/parser.hh" + * @brief Parse raw perfdatas. + * + * Parse perfdata as given by plugins output and convert them to a + * perfdata structure. + */ +class parser { + public: + parser() = default; + ~parser() noexcept = default; + parser(parser const& p) = delete; + parser& operator=(parser const& p) = delete; + void parse_perfdata(uint32_t host_id, + uint32_t service_id, + const char* str, + std::list& pd); +}; +} // namespace storage + +CCB_END() + +#endif // !CCB_STORAGE_PARSER_HH diff --git a/centreon-broker/core/inc/com/centreon/broker/misc/perfdata.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/perfdata.hh similarity index 75% rename from centreon-broker/core/inc/com/centreon/broker/misc/perfdata.hh rename to centreon-broker/storage/inc/com/centreon/broker/storage/perfdata.hh index e95fcab7b1e..c93e926c522 100644 --- a/centreon-broker/core/inc/com/centreon/broker/misc/perfdata.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/perfdata.hh @@ -16,8 +16,8 @@ ** For more information : contact@centreon.com */ -#ifndef CCB_MISC_PERFDATA_HH -#define CCB_MISC_PERFDATA_HH +#ifndef CCB_STORAGE_PERFDATA_HH +#define CCB_STORAGE_PERFDATA_HH #include #include @@ -26,9 +26,9 @@ CCB_BEGIN() -namespace misc { +namespace storage { /** - * @class perfdata perfdata.hh "com/centreon/broker/misc/perfdata.hh" + * @class perfdata perfdata.hh "com/centreon/broker/storage/perfdata.hh" * @brief Store perfdata values. * * Store perfdata values. @@ -36,22 +36,8 @@ namespace misc { class perfdata { public: enum data_type { gauge = 0, counter, derive, absolute, automatic }; + static const std::array data_type_name; - private: - double _critical; - double _critical_low; - bool _critical_mode; - double _max; - double _min; - std::string _name; - std::string _unit; - double _value; - int16_t _value_type; - double _warning; - double _warning_low; - bool _warning_mode; - - public: perfdata(); perfdata(const perfdata&) = default; perfdata(perfdata&&) = default; @@ -76,14 +62,28 @@ class perfdata { void unit(std::string&& u); double value() const noexcept; void value(double v) noexcept; - int16_t value_type() const noexcept; - void value_type(int16_t t) noexcept; + data_type value_type() const noexcept; + void value_type(data_type t) noexcept; double warning() const noexcept; void warning(double w) noexcept; double warning_low() const noexcept; void warning_low(double w) noexcept; bool warning_mode() const noexcept; void warning_mode(bool m) noexcept; + + private: + double _critical; + double _critical_low; + bool _critical_mode; + double _max; + double _min; + std::string _name; + std::string _unit; + double _value; + data_type _value_type; + double _warning; + double _warning_low; + bool _warning_mode; }; /** @@ -92,16 +92,16 @@ class perfdata { * @return Metric value. */ // Inlined after profiling for performance. -inline double perfdata::value() const noexcept { - return _value; +inline double perfdata::value() const throw() { + return (_value); } -} // namespace misc +} // namespace storage CCB_END() -bool operator==(com::centreon::broker::misc::perfdata const& left, - com::centreon::broker::misc::perfdata const& right); -bool operator!=(com::centreon::broker::misc::perfdata const& left, - com::centreon::broker::misc::perfdata const& right); +bool operator==(com::centreon::broker::storage::perfdata const& left, + com::centreon::broker::storage::perfdata const& right); +bool operator!=(com::centreon::broker::storage::perfdata const& left, + com::centreon::broker::storage::perfdata const& right); -#endif // !CCB_MISC_PERFDATA_HH +#endif // !CCB_STORAGE_PERFDATA_HH diff --git a/bbdo/storage/rebuild.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/rebuild.hh similarity index 90% rename from bbdo/storage/rebuild.hh rename to centreon-broker/storage/inc/com/centreon/broker/storage/rebuild.hh index c64e0444c32..7b8e736af56 100644 --- a/bbdo/storage/rebuild.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/rebuild.hh @@ -24,6 +24,7 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/internal.hh" CCB_BEGIN() @@ -46,7 +47,8 @@ class rebuild : public io::data { ~rebuild() noexcept = default; rebuild& operator=(const rebuild& right) = delete; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/bbdo/storage/remove_graph.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/remove_graph.hh similarity index 90% rename from bbdo/storage/remove_graph.hh rename to centreon-broker/storage/inc/com/centreon/broker/storage/remove_graph.hh index cce4bf796d4..d5579b69174 100644 --- a/bbdo/storage/remove_graph.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/remove_graph.hh @@ -24,6 +24,7 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/internal.hh" CCB_BEGIN() @@ -46,7 +47,8 @@ class remove_graph : public io::data { remove_graph(remove_graph const&) = delete; remove_graph& operator=(remove_graph const&) = delete; constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } static mapping::entry const entries[]; diff --git a/bbdo/storage/status.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/status.hh similarity index 91% rename from bbdo/storage/status.hh rename to centreon-broker/storage/inc/com/centreon/broker/storage/status.hh index 8a1f0617fdf..febf4cbc9a7 100644 --- a/bbdo/storage/status.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/status.hh @@ -24,6 +24,7 @@ #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/mapping/entry.hh" #include "com/centreon/broker/namespace.hh" +#include "com/centreon/broker/storage/internal.hh" #include "com/centreon/broker/timestamp.hh" CCB_BEGIN() @@ -60,7 +61,8 @@ class status : public io::data { ~status(); status& operator=(status const& s); constexpr static uint32_t static_type() { - return io::events::data_type::value; + return io::events::data_type::value; } }; } // namespace storage diff --git a/centreon-broker/storage/inc/com/centreon/broker/storage/stream.hh b/centreon-broker/storage/inc/com/centreon/broker/storage/stream.hh index 2d40a32bb00..c3a18ea2e06 100644 --- a/centreon-broker/storage/inc/com/centreon/broker/storage/stream.hh +++ b/centreon-broker/storage/inc/com/centreon/broker/storage/stream.hh @@ -51,7 +51,7 @@ class stream : public io::stream { struct metric_info { bool locked; uint32_t metric_id; - uint16_t type; + uint32_t type; double value; std::string unit_name; double warn; diff --git a/centreon-broker/storage/src/conflict_manager.cc b/centreon-broker/storage/src/conflict_manager.cc index fa7f7c340af..4d245d6c83c 100644 --- a/centreon-broker/storage/src/conflict_manager.cc +++ b/centreon-broker/storage/src/conflict_manager.cc @@ -20,13 +20,13 @@ #include #include -#include "bbdo/storage/index_mapping.hh" #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/database/mysql_result.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/events.hh" +#include "com/centreon/broker/storage/index_mapping.hh" +#include "com/centreon/broker/storage/perfdata.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -34,9 +34,6 @@ using namespace com::centreon::broker; using namespace com::centreon::broker::database; using namespace com::centreon::broker::storage; -const std::array conflict_manager::metric_type_name{ - "GAUGE", "COUNTER", "DERIVE", "ABSOLUTE", "AUTOMATIC"}; - conflict_manager* conflict_manager::_singleton = nullptr; conflict_manager::instance_state conflict_manager::_state{ conflict_manager::not_started}; @@ -141,8 +138,7 @@ bool conflict_manager::init_storage(bool store_in_db, return _singleton != nullptr || _state == finished || config::applier::mode == config::applier::finished; })) { - if (_state == finished || - config::applier::mode == config::applier::finished) + if (_state == finished) return false; std::lock_guard lk(_singleton->_loop_m); _singleton->_store_in_db = store_in_db; @@ -154,7 +150,7 @@ bool conflict_manager::init_storage(bool store_in_db, _singleton->_max_log_queries = queries_per_transaction; _singleton->_ref_count++; _singleton->_thread = - std::thread(&conflict_manager::_callback, _singleton); + std::move(std::thread(&conflict_manager::_callback, _singleton)); pthread_setname_np(_singleton->_thread.native_handle(), "conflict_mngr"); return true; } @@ -387,7 +383,7 @@ void conflict_manager::_load_caches() { void conflict_manager::update_metric_info_cache(uint64_t index_id, uint32_t metric_id, - const std::string& metric_name, + std::string const& metric_name, short metric_type) { auto it = _metric_cache.find({index_id, metric_name}); if (it != _metric_cache.end()) { @@ -395,7 +391,7 @@ void conflict_manager::update_metric_info_cache(uint64_t index_id, "conflict_manager: updating metric '{}' of id {} at index {} to " "metric_type {}", metric_name, metric_id, index_id, - metric_type_name[metric_type]); + perfdata::data_type_name[metric_type]); std::lock_guard lock(_metric_cache_m); it->second.type = metric_type; if (it->second.metric_id != metric_id) { @@ -540,11 +536,11 @@ void conflict_manager::_callback() { events.pop_front(); std::shared_ptr& d = std::get<0>(tpl); uint32_t type{d->type()}; - uint16_t cat{category_of_type(type)}; - uint16_t elem{element_of_type(type)}; - if (std::get<1>(tpl) == sql && cat == io::neb) + uint16_t cat{io::events::category_of_type(type)}; + uint16_t elem{io::events::element_of_type(type)}; + if (std::get<1>(tpl) == sql && cat == io::events::neb) (this->*(_neb_processing_table[elem]))(tpl); - else if (std::get<1>(tpl) == storage && cat == io::neb && + else if (std::get<1>(tpl) == storage && cat == io::events::neb && type == neb::service_status::static_type()) _storage_process_service_status(tpl); else { @@ -590,7 +586,7 @@ void conflict_manager::_callback() { std::lock_guard lk(_stat_m); _speed = s / _stats_count.size(); stats::center::instance().execute( - [s = this->_stats, spd = _speed] { s->set_speed(spd); }); + [ s = this->_stats, spd = _speed ] { s->set_speed(spd); }); } } } @@ -772,7 +768,7 @@ void conflict_manager::_update_stats(const std::uint32_t size, const std::size_t sql_size, const std::size_t stor_size) noexcept { stats::center::instance().execute( - [s = this->_stats, size, mpdq, ev_size, sql_size, stor_size] { + [ s = this->_stats, size, mpdq, ev_size, sql_size, stor_size ] { s->set_events_handled(size); s->set_max_perfdata_events(mpdq); s->set_waiting_events(static_cast(ev_size)); diff --git a/centreon-broker/storage/src/conflict_manager_sql.cc b/centreon-broker/storage/src/conflict_manager_sql.cc index 258aa6e5a0c..da88cb1531a 100644 --- a/centreon-broker/storage/src/conflict_manager_sql.cc +++ b/centreon-broker/storage/src/conflict_manager_sql.cc @@ -360,8 +360,7 @@ void conflict_manager::_process_acknowledgement( log_v2::sql()->info( "processing acknowledgement event (poller: {}, host: {}, service: {}, " "entry time: {}, deletion time: {})", - ack.poller_id, ack.host_id, ack.service_id, ack.entry_time, - ack.deletion_time); + ack.poller_id, ack.host_id, ack.service_id, ack.entry_time, ack.deletion_time); // Processing. if (_is_valid_poller(ack.poller_id)) { @@ -515,6 +514,7 @@ void conflict_manager::_process_custom_variable_status( log_v2::sql()->info("SQL: updating custom variable '{}' of ({}, {})", cv.name, cv.host_id, cv.service_id); + } /** diff --git a/centreon-broker/storage/src/conflict_manager_storage.cc b/centreon-broker/storage/src/conflict_manager_storage.cc index e3e58b53a2e..b5bcd95fbaa 100644 --- a/centreon-broker/storage/src/conflict_manager_storage.cc +++ b/centreon-broker/storage/src/conflict_manager_storage.cc @@ -1,5 +1,5 @@ /* -** Copyright 2019-2021 Centreon +** Copyright 2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -21,21 +21,21 @@ #include #include #include -#include #include -#include "bbdo/storage/index_mapping.hh" -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/metric_mapping.hh" -#include "bbdo/storage/remove_graph.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/database/table_max_size.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/storage/conflict_manager.hh" +#include "com/centreon/broker/storage/exceptions/perfdata.hh" +#include "com/centreon/broker/storage/index_mapping.hh" +#include "com/centreon/broker/storage/metric.hh" +#include "com/centreon/broker/storage/metric_mapping.hh" +#include "com/centreon/broker/storage/parser.hh" +#include "com/centreon/broker/storage/perfdata.hh" +#include "com/centreon/broker/storage/remove_graph.hh" +#include "com/centreon/broker/storage/status.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; @@ -238,13 +238,11 @@ void conflict_manager::_storage_process_service_status( "conflict_manager: host_id:{}, service_id:{} - generating status event " "with index_id {}, rrd_len: {}", host_id, service_id, index_id, rrd_len); - if (ss.has_been_checked) { - auto status(std::make_shared( - ss.last_check, index_id, - static_cast(ss.check_interval * _interval_length), false, - rrd_len, ss.last_hard_state)); - multiplexing::publisher().write(status); - } + std::shared_ptr status(std::make_shared( + ss.last_check, index_id, + static_cast(ss.check_interval * _interval_length), false, + rrd_len, ss.last_hard_state)); + multiplexing::publisher().write(status); if (!ss.perf_data.empty()) { /* Statements preparations */ @@ -258,170 +256,177 @@ void conflict_manager::_storage_process_service_status( } /* Parse perfdata. */ - _finish_action(-1, actions::metrics); - std::list pds{misc::parse_perfdata( - ss.host_id, ss.service_id, ss.perf_data.c_str())}; - - std::list> to_publish; - for (auto& pd : pds) { - auto it_index_cache = _metric_cache.find({index_id, pd.name()}); - - /* The cache does not contain this metric */ - uint32_t metric_id; - bool need_metric_mapping = true; - if (it_index_cache == _metric_cache.end()) { - log_v2::perfdata()->debug( - "conflict_manager: no metrics corresponding to index {} and " - "perfdata '{}' found in cache", - index_id, pd.name()); - /* Let's insert it */ - _metrics_insert.bind_value_as_u64(0, index_id); - _metrics_insert.bind_value_as_str(1, pd.name()); - _metrics_insert.bind_value_as_str(2, pd.unit()); - _metrics_insert.bind_value_as_f32(3, pd.warning()); - _metrics_insert.bind_value_as_f32(4, pd.warning_low()); - _metrics_insert.bind_value_as_tiny(5, pd.warning_mode()); - _metrics_insert.bind_value_as_f32(6, pd.critical()); - _metrics_insert.bind_value_as_f32(7, pd.critical_low()); - _metrics_insert.bind_value_as_tiny(8, pd.critical_mode()); - _metrics_insert.bind_value_as_f32(9, pd.min()); - _metrics_insert.bind_value_as_f32(10, pd.max()); - _metrics_insert.bind_value_as_f32(11, pd.value()); - - int16_t type = pd.value_type(); - char t[2]; - t[0] = '0' + type; - t[1] = 0; - _metrics_insert.bind_value_as_str(12, t); - - // Execute query. - std::promise promise; - _mysql.run_statement_and_get_int( - _metrics_insert, &promise, database::mysql_task::LAST_INSERT_ID, - conn); - try { - metric_id = promise.get_future().get(); - - // Insert metric in cache. - log_v2::perfdata()->info( - "conflict_manager: new metric {} for index {} and perfdata " - "'{}'", - metric_id, index_id, pd.name()); - metric_info info{.locked = false, - .metric_id = metric_id, - .type = type, - .value = pd.value(), - .unit_name = pd.unit(), - .warn = pd.warning(), - .warn_low = pd.warning_low(), - .warn_mode = pd.warning_mode(), - .crit = pd.critical(), - .crit_low = pd.critical_low(), - .crit_mode = pd.critical_mode(), - .min = pd.min(), - .max = pd.max(), - .metric_mapping_sent = - true}; // It will be done after this block - + std::list pds; + storage::parser p; + try { + _finish_action(-1, actions::metrics); + p.parse_perfdata(ss.host_id, ss.service_id, ss.perf_data.c_str(), pds); + + std::list> to_publish; + for (auto& pd : pds) { + auto it_index_cache = _metric_cache.find({index_id, pd.name()}); + + /* The cache does not contain this metric */ + uint32_t metric_id; + bool need_metric_mapping = true; + if (it_index_cache == _metric_cache.end()) { + log_v2::perfdata()->debug( + "conflict_manager: no metrics corresponding to index {} and " + "perfdata '{}' found in cache", + index_id, pd.name()); + /* Let's insert it */ + _metrics_insert.bind_value_as_u64(0, index_id); + _metrics_insert.bind_value_as_str(1, pd.name()); + _metrics_insert.bind_value_as_str(2, pd.unit()); + _metrics_insert.bind_value_as_f32(3, pd.warning()); + _metrics_insert.bind_value_as_f32(4, pd.warning_low()); + _metrics_insert.bind_value_as_tiny(5, pd.warning_mode()); + _metrics_insert.bind_value_as_f32(6, pd.critical()); + _metrics_insert.bind_value_as_f32(7, pd.critical_low()); + _metrics_insert.bind_value_as_tiny(8, pd.critical_mode()); + _metrics_insert.bind_value_as_f32(9, pd.min()); + _metrics_insert.bind_value_as_f32(10, pd.max()); + _metrics_insert.bind_value_as_f32(11, pd.value()); + + uint32_t type = pd.value_type(); + char t[2]; + t[0] = '0' + type; + t[1] = 0; + _metrics_insert.bind_value_as_str(12, t); + + // Execute query. + std::promise promise; + _mysql.run_statement_and_get_int( + _metrics_insert, &promise, database::mysql_task::LAST_INSERT_ID, + conn); + try { + metric_id = promise.get_future().get(); + + // Insert metric in cache. + log_v2::perfdata()->info( + "conflict_manager: new metric {} for index {} and perfdata " + "'{}'", + metric_id, index_id, pd.name()); + metric_info info{.locked = false, + .metric_id = metric_id, + .type = type, + .value = pd.value(), + .unit_name = pd.unit(), + .warn = pd.warning(), + .warn_low = pd.warning_low(), + .warn_mode = pd.warning_mode(), + .crit = pd.critical(), + .crit_low = pd.critical_low(), + .crit_mode = pd.critical_mode(), + .min = pd.min(), + .max = pd.max(), + .metric_mapping_sent = + true}; // It will be done after this block + + std::lock_guard lock(_metric_cache_m); + _metric_cache[{index_id, pd.name()}] = info; + } catch (std::exception const& e) { + log_v2::perfdata()->error( + "conflict_manager: failed to create metric {} with type {}, " + "value {}, unit_name {}, warn {}, warn_low {}, warn_mode {}, " + "crit {}, crit_low {}, crit_mode {}, min {} and max {}", + metric_id, type, pd.value(), pd.unit(), pd.warning(), + pd.warning_low(), pd.warning_mode(), pd.critical(), + pd.critical_low(), pd.critical_mode(), pd.min(), pd.max()); + throw msg_fmt( + "storage: insertion of metric '{}" + "' of index {} failed: {}", + pd.name(), index_id, e.what()); + } + } else { std::lock_guard lock(_metric_cache_m); - _metric_cache[{index_id, pd.name()}] = info; - } catch (const std::exception& e) { - log_v2::perfdata()->error( - "conflict_manager: failed to create metric {} with type {}, " - "value {}, unit_name {}, warn {}, warn_low {}, warn_mode {}, " - "crit {}, crit_low {}, crit_mode {}, min {} and max {}", - metric_id, type, pd.value(), pd.unit(), pd.warning(), - pd.warning_low(), pd.warning_mode(), pd.critical(), - pd.critical_low(), pd.critical_mode(), pd.min(), pd.max()); - throw msg_fmt( - "storage: insertion of metric '{}" - "' of index {} failed: {}", - pd.name(), index_id, e.what()); + /* We have the metric in the cache */ + metric_id = it_index_cache->second.metric_id; + if (!it_index_cache->second.metric_mapping_sent) + it_index_cache->second.metric_mapping_sent = true; + else + need_metric_mapping = false; + + pd.value_type( + static_cast(it_index_cache->second.type)); + + log_v2::perfdata()->debug( + "conflict_manager: metric {} concerning index {}, perfdata " + "'{}' found in cache", + it_index_cache->second.metric_id, index_id, pd.name()); + // Should we update metrics ? + if (!check_equality(it_index_cache->second.value, pd.value()) || + it_index_cache->second.unit_name != pd.unit() || + !check_equality(it_index_cache->second.warn, pd.warning()) || + !check_equality(it_index_cache->second.warn_low, + pd.warning_low()) || + it_index_cache->second.warn_mode != pd.warning_mode() || + !check_equality(it_index_cache->second.crit, pd.critical()) || + !check_equality(it_index_cache->second.crit_low, + pd.critical_low()) || + it_index_cache->second.crit_mode != pd.critical_mode() || + !check_equality(it_index_cache->second.min, pd.min()) || + !check_equality(it_index_cache->second.max, pd.max())) { + log_v2::perfdata()->info( + "conflict_manager: updating metric {} of index {}, perfdata " + "'{}' with unit: {}, warning: {}:{}, critical: {}:{}, min: " + "{}, max: {}", + it_index_cache->second.metric_id, index_id, pd.name(), + pd.unit(), pd.warning_low(), pd.warning(), pd.critical_low(), + pd.critical(), pd.min(), pd.max()); + // Update metrics table. + it_index_cache->second.unit_name = pd.unit(); + it_index_cache->second.value = pd.value(); + it_index_cache->second.warn = pd.warning(); + it_index_cache->second.warn_low = pd.warning_low(); + it_index_cache->second.crit = pd.critical(); + it_index_cache->second.crit_low = pd.critical_low(); + it_index_cache->second.warn_mode = pd.warning_mode(); + it_index_cache->second.crit_mode = pd.critical_mode(); + it_index_cache->second.min = pd.min(); + it_index_cache->second.max = pd.max(); + _metrics[it_index_cache->second.metric_id] = + &it_index_cache->second; + log_v2::perfdata()->debug("new metric with metric_id={}", + it_index_cache->second.metric_id); + } } - } else { - std::lock_guard lock(_metric_cache_m); - /* We have the metric in the cache */ - metric_id = it_index_cache->second.metric_id; - if (!it_index_cache->second.metric_mapping_sent) - it_index_cache->second.metric_mapping_sent = true; - else - need_metric_mapping = false; - - pd.value_type(it_index_cache->second.type); - - log_v2::perfdata()->debug( - "conflict_manager: metric {} concerning index {}, perfdata " - "'{}' found in cache", - it_index_cache->second.metric_id, index_id, pd.name()); - // Should we update metrics ? - if (!check_equality(it_index_cache->second.value, pd.value()) || - it_index_cache->second.unit_name != pd.unit() || - !check_equality(it_index_cache->second.warn, pd.warning()) || - !check_equality(it_index_cache->second.warn_low, - pd.warning_low()) || - it_index_cache->second.warn_mode != pd.warning_mode() || - !check_equality(it_index_cache->second.crit, pd.critical()) || - !check_equality(it_index_cache->second.crit_low, - pd.critical_low()) || - it_index_cache->second.crit_mode != pd.critical_mode() || - !check_equality(it_index_cache->second.min, pd.min()) || - !check_equality(it_index_cache->second.max, pd.max())) { - log_v2::perfdata()->info( - "conflict_manager: updating metric {} of index {}, perfdata " - "'{}' with unit: {}, warning: {}:{}, critical: {}:{}, min: " - "{}, max: {}", - it_index_cache->second.metric_id, index_id, pd.name(), - pd.unit(), pd.warning_low(), pd.warning(), pd.critical_low(), - pd.critical(), pd.min(), pd.max()); - // Update metrics table. - it_index_cache->second.unit_name = pd.unit(); - it_index_cache->second.value = pd.value(); - it_index_cache->second.warn = pd.warning(); - it_index_cache->second.warn_low = pd.warning_low(); - it_index_cache->second.crit = pd.critical(); - it_index_cache->second.crit_low = pd.critical_low(); - it_index_cache->second.warn_mode = pd.warning_mode(); - it_index_cache->second.crit_mode = pd.critical_mode(); - it_index_cache->second.min = pd.min(); - it_index_cache->second.max = pd.max(); - _metrics[it_index_cache->second.metric_id] = - &it_index_cache->second; - log_v2::perfdata()->debug("new metric with metric_id={}", - it_index_cache->second.metric_id); + if (need_metric_mapping) + to_publish.emplace_back( + std::make_shared(index_id, metric_id)); + + if (_store_in_db) { + // Append perfdata to queue. + metric_value val; + val.c_time = ss.last_check; + val.metric_id = metric_id; + val.status = ss.current_state; + val.value = pd.value(); + _perfdata_queue.push_back(val); } - } - if (need_metric_mapping) - to_publish.emplace_back( - std::make_shared(index_id, metric_id)); - - if (_store_in_db) { - // Append perfdata to queue. - metric_value val; - val.c_time = ss.last_check; - val.metric_id = metric_id; - val.status = ss.current_state; - val.value = pd.value(); - _perfdata_queue.push_back(val); - } - // Send perfdata event to processing. - if (!index_locked) { - std::shared_ptr perf{ - std::make_shared( - ss.host_id, ss.service_id, pd.name(), ss.last_check, - static_cast(ss.check_interval * _interval_length), - false, metric_id, rrd_len, pd.value(), - static_cast(pd.value_type()))}; - log_v2::perfdata()->debug( - "conflict_manager: generating perfdata event for metric {} " - "(name '{}', ctime {}, value {}, rrd_len {}, data_type {})", - perf->metric_id, perf->name, perf->ctime, perf->value, rrd_len, - perf->value_type); - multiplexing::publisher().write(perf); + // Send perfdata event to processing. + if (!index_locked) { + std::shared_ptr perf{ + std::make_shared( + ss.host_id, ss.service_id, pd.name(), ss.last_check, + static_cast(ss.check_interval * _interval_length), + false, metric_id, rrd_len, pd.value(), pd.value_type())}; + log_v2::perfdata()->debug( + "conflict_manager: generating perfdata event for metric {} " + "(name '{}', ctime {}, value {}, rrd_len {}, data_type {})", + perf->metric_id, perf->name, perf->ctime, perf->value, rrd_len, + perf->value_type); + multiplexing::publisher().write(perf); + } } + multiplexing::publisher pblshr; + pblshr.write(to_publish); + } catch (storage::exceptions::perfdata const& e) { + log_v2::sql()->error( + "storage: error while parsing perfdata of service ({}, {}): {}", + host_id, service_id, e.what()); } - multiplexing::publisher pblshr; - pblshr.write(to_publish); } } *std::get<2>(t) = true; @@ -547,7 +552,7 @@ void conflict_manager::_check_deleted_index() { std::promise promise; int32_t conn = _mysql.choose_best_connection(-1); std::unordered_set index_to_delete; - std::set metrics_to_delete; + std::list metrics_to_delete; try { _mysql.run_query_and_get_result( "SELECT m.index_id,m.metric_id, m.metric_name, i.host_id, " @@ -559,7 +564,7 @@ void conflict_manager::_check_deleted_index() { std::lock_guard lock(_metric_cache_m); while (_mysql.fetch_row(res)) { index_to_delete.insert(res.value_as_u64(0)); - metrics_to_delete.insert(res.value_as_u64(1)); + metrics_to_delete.push_back(res.value_as_u64(1)); _metric_cache.erase({res.value_as_u64(0), res.value_as_str(2)}); _index_cache.erase({res.value_as_u32(3), res.value_as_u32(4)}); } @@ -570,9 +575,11 @@ void conflict_manager::_check_deleted_index() { res = promise.get_future().get(); while (_mysql.fetch_row(res)) { - metrics_to_delete.insert(res.value_as_u64(0)); + metrics_to_delete.push_back(res.value_as_u64(0)); _metric_cache.erase({res.value_as_u64(0), res.value_as_str(1)}); } + metrics_to_delete.sort(); + metrics_to_delete.unique(); } catch (const std::exception& e) { throw msg_fmt("could not query index table to get index to delete: {} ", e.what()); diff --git a/centreon-broker/rrd/inc/com/centreon/broker/rrd/internal.hh b/centreon-broker/storage/src/exceptions/perfdata.cc similarity index 65% rename from centreon-broker/rrd/inc/com/centreon/broker/rrd/internal.hh rename to centreon-broker/storage/src/exceptions/perfdata.cc index ec70255afc1..b893b68e65c 100644 --- a/centreon-broker/rrd/inc/com/centreon/broker/rrd/internal.hh +++ b/centreon-broker/storage/src/exceptions/perfdata.cc @@ -1,5 +1,5 @@ /* -** Copyright 2021 Centreon +** Copyright 2011-2013 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -16,18 +16,11 @@ ** For more information : contact@centreon.com */ -#ifndef CCB_RRD_INTERNAL_HH -#define CCB_RRD_INTERNAL_HH +#include "com/centreon/broker/storage/exceptions/perfdata.hh" -#include "bbdo/events.hh" -#include "bbdo/rebuild.pb.h" -#include "com/centreon/broker/io/protobuf.hh" -CCB_BEGIN() +using namespace com::centreon::broker; +using namespace com::centreon::broker::storage::exceptions; -namespace storage { -using pb_rebuild = io::protobuf; +void perfdata::rethrow() const { + throw *this; } - -CCB_END() - -#endif /* !CCB_RRD_INTERNAL_HH */ diff --git a/bbdo/storage/index_mapping.cc b/centreon-broker/storage/src/index_mapping.cc similarity index 86% rename from bbdo/storage/index_mapping.cc rename to centreon-broker/storage/src/index_mapping.cc index 78c91c156be..7e1da92d32c 100644 --- a/bbdo/storage/index_mapping.cc +++ b/centreon-broker/storage/src/index_mapping.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/storage/index_mapping.hh" +#include "com/centreon/broker/storage/index_mapping.hh" #include @@ -44,6 +44,12 @@ index_mapping::index_mapping(uint64_t index_id, host_id{host_id}, service_id{service_id} {} +/************************************** + * * + * Static Objects * + * * + **************************************/ + // Mapping. mapping::entry const index_mapping::entries[] = { mapping::entry(&index_mapping::index_id, @@ -62,4 +68,4 @@ static io::data* new_index_mapping() { return new index_mapping; } io::event_info::event_operations const index_mapping::operations = { - &new_index_mapping, nullptr, nullptr}; + &new_index_mapping}; diff --git a/centreon-broker/storage/src/main.cc b/centreon-broker/storage/src/main.cc index 8411c1b2dfa..775439a6565 100644 --- a/centreon-broker/storage/src/main.cc +++ b/centreon-broker/storage/src/main.cc @@ -16,18 +16,17 @@ ** For more information : contact@centreon.com */ -#include "bbdo/events.hh" -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/rebuild.hh" -#include "bbdo/storage/remove_graph.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/storage/factory.hh" -#include "bbdo/storage/index_mapping.hh" +#include "com/centreon/broker/storage/index_mapping.hh" #include "com/centreon/broker/storage/internal.hh" -#include "bbdo/storage/metric_mapping.hh" +#include "com/centreon/broker/storage/metric.hh" +#include "com/centreon/broker/storage/metric_mapping.hh" +#include "com/centreon/broker/storage/rebuild.hh" +#include "com/centreon/broker/storage/remove_graph.hh" +#include "com/centreon/broker/storage/status.hh" #include "com/centreon/broker/storage/stream.hh" #include "com/centreon/exceptions/msg_fmt.hh" @@ -61,7 +60,7 @@ void broker_module_deinit() { if (!--instances) { // Deregister storage layer. // Remove events. - io::events::instance().unregister_category(io::storage); + io::events::instance().unregister_category(io::events::storage); io::protocols::instance().unreg("storage"); } } @@ -82,29 +81,37 @@ void broker_module_init(void const* arg) { io::events& e(io::events::instance()); + // Register category. + int storage_category(e.register_category("storage", io::events::storage)); + if (storage_category != io::events::storage) { + e.unregister_category(storage_category); + --instances; + throw msg_fmt( + "storage: category {}" + " is already registered whereas it should be " + "reserved for the storage module", + io::events::storage); + } + // Register events. { - e.register_event(make_type(io::storage, storage::de_metric), "metric", + e.register_event(io::events::storage, storage::de_metric, "metric", &storage::metric::operations, storage::metric::entries, "rt_metrics"); - e.register_event(make_type(io::storage, storage::de_rebuild), "rebuild", + e.register_event(io::events::storage, storage::de_rebuild, "rebuild", &storage::rebuild::operations, storage::rebuild::entries); - e.register_event(make_type(io::storage, storage::de_remove_graph), + e.register_event(io::events::storage, storage::de_remove_graph, "remove_graph", &storage::remove_graph::operations, storage::remove_graph::entries); - e.register_event(make_type(io::storage, storage::de_status), "status", + e.register_event(io::events::storage, storage::de_status, "status", &storage::status::operations, storage::status::entries); - e.register_event(make_type(io::storage, storage::de_index_mapping), + e.register_event(io::events::storage, storage::de_index_mapping, "index_mapping", &storage::index_mapping::operations, storage::index_mapping::entries); - e.register_event(make_type(io::storage, storage::de_metric_mapping), + e.register_event(io::events::storage, storage::de_metric_mapping, "metric_mapping", &storage::metric_mapping::operations, storage::metric_mapping::entries); - log_v2::bbdo()->info("registering protobuf pb_rebuild as {:x}:{:x}", - io::storage, storage::de_pb_rebuild); - e.register_event(storage_pb_rebuild, "pb_rebuild", - &storage::pb_rebuild::operations); } // Register storage layer. diff --git a/bbdo/storage/metric.cc b/centreon-broker/storage/src/metric.cc similarity index 87% rename from bbdo/storage/metric.cc rename to centreon-broker/storage/src/metric.cc index 057e27ac2bc..0f3e294bae2 100644 --- a/bbdo/storage/metric.cc +++ b/centreon-broker/storage/src/metric.cc @@ -16,17 +16,25 @@ ** For more information : contact@centreon.com */ -#include "bbdo/storage/metric.hh" +#include "com/centreon/broker/storage/metric.hh" #include #include #include "com/centreon/broker/database/table_max_size.hh" #include "com/centreon/broker/io/events.hh" +#include "com/centreon/broker/storage/internal.hh" +#include "com/centreon/broker/storage/perfdata.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::storage; +/************************************** + * * + * Public Methods * + * * + **************************************/ + /** * Default constructor. */ @@ -38,7 +46,7 @@ metric::metric() metric_id(0), rrd_len(0), value(NAN), - value_type{0}, // gauge + value_type(perfdata::gauge), host_id(0), service_id(0) {} @@ -51,7 +59,7 @@ metric::metric(uint32_t host_id, uint32_t metric_id, int32_t rrd_len, double value, - int16_t value_type) + short value_type) : io::data(metric::static_type()), ctime{ctime}, interval{interval}, @@ -98,5 +106,4 @@ mapping::entry const metric::entries[] = { static io::data* new_metric() { return new metric; } -io::event_info::event_operations const metric::operations = {&new_metric, - nullptr, nullptr}; +io::event_info::event_operations const metric::operations = {&new_metric}; diff --git a/bbdo/storage/metric_mapping.cc b/centreon-broker/storage/src/metric_mapping.cc similarity index 90% rename from bbdo/storage/metric_mapping.cc rename to centreon-broker/storage/src/metric_mapping.cc index 92f9c43f060..49ddfac7cdf 100644 --- a/bbdo/storage/metric_mapping.cc +++ b/centreon-broker/storage/src/metric_mapping.cc @@ -16,13 +16,19 @@ ** For more information : contact@centreon.com */ -#include "bbdo/storage/metric_mapping.hh" +#include "com/centreon/broker/storage/metric_mapping.hh" #include using namespace com::centreon::broker; using namespace com::centreon::broker::storage; +/************************************** + * * + * Public Methods * + * * + **************************************/ + /** * Default constructor. */ @@ -104,4 +110,4 @@ static io::data* new_metric_mapping() { return new metric_mapping; } io::event_info::event_operations const metric_mapping::operations = { - &new_metric_mapping, nullptr, nullptr}; + &new_metric_mapping}; diff --git a/centreon-broker/core/src/misc/parse_perfdata.cc b/centreon-broker/storage/src/parser.cc similarity index 89% rename from centreon-broker/core/src/misc/parse_perfdata.cc rename to centreon-broker/storage/src/parser.cc index 71ac8949a77..cbae4e10324 100644 --- a/centreon-broker/core/src/misc/parse_perfdata.cc +++ b/centreon-broker/storage/src/parser.cc @@ -1,5 +1,5 @@ /* -** Copyright 2011-2013,2017-2021 Centreon +** Copyright 2011-2013,2017 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ ** For more information : contact@centreon.com */ +#include "com/centreon/broker/storage/parser.hh" + #include #include #include @@ -23,14 +25,19 @@ #include #include -#include "bbdo/storage/metric.hh" #include "com/centreon/broker/database/table_max_size.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/misc/misc.hh" #include "com/centreon/broker/misc/string.hh" +#include "com/centreon/broker/storage/exceptions/perfdata.hh" +#include "com/centreon/broker/storage/perfdata.hh" + +using namespace com::centreon::broker::storage; -using namespace com::centreon::broker; -using namespace com::centreon::broker::misc; +/************************************** + * * + * Local Objects * + * * + **************************************/ /** * Extract a real value from a perfdata string. @@ -118,18 +125,15 @@ static inline void extract_range(double* low, } /** - * @brief Parse perfdata string as given by plugin. + * Parse perfdata string as given by plugin. * - * @param host_id The host id of the service with this perfdata - * @param service_id The service id of the service with this perfdata - * @param str The perfdata string to parse - * - * @return A list of perfdata + * @param[in] str Raw perfdata string. + * @param[out] pd List of parsed metrics. */ -std::list misc::parse_perfdata(uint32_t host_id, - uint32_t service_id, - const char* str) { - std::list retval; +void parser::parse_perfdata(uint32_t host_id, + uint32_t service_id, + const char* str, + std::list& pd) { auto id = [host_id, service_id] { if (host_id || service_id) return fmt::format("({}:{})", host_id, service_id); @@ -206,7 +210,7 @@ std::list misc::parse_perfdata(uint32_t host_id, } if (end - s + 1 > 0) { - std::string name(s, end - s + 1); + std::string name(std::move(std::string(s, end - s + 1))); name.resize(misc::string::adjust_size_utf8( name, get_metrics_col_size(metrics_metric_name))); p.name(std::move(name)); @@ -254,7 +258,7 @@ std::list misc::parse_perfdata(uint32_t host_id, // Extract unit. size_t t = strcspn(tmp, " \t\n\r;"); { - std::string unit(tmp, t); + std::string unit(std::move(std::string(tmp, t))); unit.resize(misc::string::adjust_size_utf8( unit, get_metrics_col_size(metrics_unit_name))); p.unit(std::move(unit)); @@ -301,11 +305,10 @@ std::list misc::parse_perfdata(uint32_t host_id, p.max()); // Append to list. - retval.emplace_back(std::move(p)); + pd.emplace_back(std::move(p)); // Skip whitespaces. while (isspace(*tmp)) ++tmp; } - return retval; } diff --git a/centreon-broker/core/src/misc/perfdata.cc b/centreon-broker/storage/src/perfdata.cc similarity index 95% rename from centreon-broker/core/src/misc/perfdata.cc rename to centreon-broker/storage/src/perfdata.cc index 0d384663a01..90d00338ebf 100644 --- a/centreon-broker/core/src/misc/perfdata.cc +++ b/centreon-broker/storage/src/perfdata.cc @@ -16,11 +16,14 @@ ** For more information : contact@centreon.com */ -#include "com/centreon/broker/misc/perfdata.hh" +#include "com/centreon/broker/storage/perfdata.hh" #include -using namespace com::centreon::broker::misc; +using namespace com::centreon::broker::storage; + +const std::array perfdata::data_type_name{ + "GAUGE", "COUNTER", "DERIVE", "ABSOLUTE", "AUTOMATIC"}; /** * Default constructor. @@ -32,7 +35,7 @@ perfdata::perfdata() _max(NAN), _min(NAN), _value(NAN), - _value_type(0), // gauge + _value_type(gauge), _warning(NAN), _warning_low(NAN), _warning_mode(false) {} @@ -242,7 +245,7 @@ void perfdata::value(double v) noexcept { * * @return Type of the value. */ -int16_t perfdata::value_type() const noexcept { +perfdata::data_type perfdata::value_type() const noexcept { return _value_type; } @@ -251,7 +254,7 @@ int16_t perfdata::value_type() const noexcept { * * @param[in] t New type. */ -void perfdata::value_type(int16_t t) noexcept { +void perfdata::value_type(perfdata::data_type t) noexcept { _value_type = t; } diff --git a/bbdo/storage/rebuild.cc b/centreon-broker/storage/src/rebuild.cc similarity index 92% rename from bbdo/storage/rebuild.cc rename to centreon-broker/storage/src/rebuild.cc index 5148b7687cc..a916e0e9782 100644 --- a/bbdo/storage/rebuild.cc +++ b/centreon-broker/storage/src/rebuild.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/storage/rebuild.hh" +#include "com/centreon/broker/storage/rebuild.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::storage; @@ -50,5 +50,4 @@ mapping::entry const rebuild::entries[] = { static io::data* new_rebuild() { return new rebuild; } -io::event_info::event_operations const rebuild::operations = {&new_rebuild, - nullptr, nullptr}; +io::event_info::event_operations const rebuild::operations = {&new_rebuild}; diff --git a/centreon-broker/storage/src/rebuild.proto b/centreon-broker/storage/src/rebuild.proto deleted file mode 100644 index 26bea825e80..00000000000 --- a/centreon-broker/storage/src/rebuild.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; - -package com.centreon.broker; - -message Point { - int64 ctime = 1; - double value = 2; - int32 status = 3; -} - -message Metric { - int32 value_type = 1; - uint64 metric_id = 2; -} - -message Rebuild { - oneof type { - uint64 index_id = 1; - Metric metric = 2; - } - uint32 interval = 3; - uint32 length = 4; - repeated Point data = 5; -} diff --git a/centreon-broker/storage/src/rebuilder.cc b/centreon-broker/storage/src/rebuilder.cc index b54db996002..8860b7c8213 100644 --- a/centreon-broker/storage/src/rebuilder.cc +++ b/centreon-broker/storage/src/rebuilder.cc @@ -25,18 +25,15 @@ #include #include -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/rebuild.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/database/mysql_error.hh" #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/storage/conflict_manager.hh" -#include "com/centreon/broker/storage/internal.hh" +#include "com/centreon/broker/storage/metric.hh" +#include "com/centreon/broker/storage/rebuild.hh" +#include "com/centreon/broker/storage/status.hh" #include "com/centreon/exceptions/msg_fmt.hh" -#define USE_PROTOBUF - using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::storage; @@ -273,16 +270,10 @@ void rebuilder::_rebuild_metric(mysql& ms, "{})", metric_id, metric_name, metric_type, interval); -#ifdef USE_PROTOBUF - auto r = std::make_shared(); - r->obj.mutable_metric()->set_metric_id(metric_id); - r->obj.mutable_metric()->set_value_type(metric_type); -#else // Send rebuild start event. _send_rebuild_event(false, metric_id, false); -#endif - time_t start{time(nullptr) - length}; + time_t start(time(nullptr) - length); try { // Get data. @@ -299,7 +290,6 @@ void rebuilder::_rebuild_metric(mysql& ms, try { database::mysql_result res(promise.get_future().get()); while (!_should_exit && ms.fetch_row(res)) { -#ifndef USE_PROTOBUF std::shared_ptr entry = std::make_shared( host_id, service_id, metric_name, res.value_as_u32(0), interval, @@ -316,42 +306,21 @@ void rebuilder::_rebuild_metric(mysql& ms, true, metric_id, length, res.value_as_f64(1), metric_type); multiplexing::publisher().write(entry); -#else - Point* p = r->obj.add_data(); - p->set_ctime(res.value_as_u32(0)); - p->set_value(res.value_as_f64(1)); - if (p->value() > FLT_MAX * 0.999) - p->set_value(std::numeric_limits::infinity()); - else if (p->value() < -FLT_MAX * 0.999) - p->set_value(-std::numeric_limits::infinity()); - log_v2::perfdata()->trace( - "storage(rebuilder): Sending metric with host_id {}, service_id " - "{}, metric_name {}, ctime {}, interval {}, is_for_rebuild {}, " - "metric_id {}, rrd_len {}, value {}, value_type{}", - host_id, service_id, metric_name, p->ctime(), interval, true, - metric_id, length, p->value(), metric_type); -#endif } -#ifdef USE_PROTOBUF - multiplexing::publisher().write(r); -#endif - } catch (const std::exception& e) { throw msg_fmt("storage: rebuilder: cannot fetch data of metric {} : {}", metric_id, e.what()); } } catch (...) { -#ifndef USE_PROTOBUF // Send rebuild end event. _send_rebuild_event(true, metric_id, false); -#endif + // Rethrow exception. throw; } -#ifndef USE_PROTOBUF + // Send rebuild end event. _send_rebuild_event(true, metric_id, false); -#endif } /** @@ -369,18 +338,12 @@ void rebuilder::_rebuild_status(mysql& ms, log_v2::sql()->info("storage: rebuilder: rebuilding status {} (interval {})", index_id, interval); -#ifdef USE_PROTOBUF - auto r = std::make_shared(); - r->obj.set_index_id(index_id); - r->obj.set_interval(interval); - r->obj.set_length(length); -#else // Send rebuild start event. _send_rebuild_event(false, index_id, true); -#endif - time_t start{time(nullptr) - length}; + time_t start(time(nullptr) - length); + // Database schema version. try { // Get data. std::string query{ @@ -393,38 +356,28 @@ void rebuilder::_rebuild_status(mysql& ms, try { database::mysql_result res(promise.get_future().get()); while (!_should_exit && ms.fetch_row(res)) { -#ifndef USE_PROTOBUF std::shared_ptr entry( std::make_shared(res.value_as_u32(0), index_id, interval, true, _rrd_len, res.value_as_i32(1))); multiplexing::publisher().write(entry); -#else - Point* p = r->obj.add_data(); - p->set_ctime(res.value_as_u32(0)); - p->set_status(res.value_as_i32(1)); -#endif } } catch (const std::exception& e) { throw msg_fmt("storage: rebuilder: cannot fetch data of index {} : {}", index_id, e.what()); } } catch (...) { -#ifndef USE_PROTOBUF // Send rebuild end event. _send_rebuild_event(true, index_id, true); // Rethrow exception. -#endif throw; } -#ifndef USE_PROTOBUF + // Send rebuild end event. _send_rebuild_event(true, index_id, true); -#endif } -#ifndef USE_PROTOBUF /** * Send a rebuild event. * @@ -437,7 +390,6 @@ void rebuilder::_send_rebuild_event(bool end, uint64_t id, bool is_index) { std::make_shared(end, id, is_index); multiplexing::publisher().write(rb); } -#endif /** * Set index rebuild flag. diff --git a/bbdo/storage/remove_graph.cc b/centreon-broker/storage/src/remove_graph.cc similarity index 94% rename from bbdo/storage/remove_graph.cc rename to centreon-broker/storage/src/remove_graph.cc index ebbdc78757a..2ead8b2a497 100644 --- a/bbdo/storage/remove_graph.cc +++ b/centreon-broker/storage/src/remove_graph.cc @@ -16,7 +16,7 @@ ** For more information : contact@centreon.com */ -#include "bbdo/storage/remove_graph.hh" +#include "com/centreon/broker/storage/remove_graph.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::storage; @@ -46,4 +46,4 @@ static io::data* new_remove_graph() { return new remove_graph; } io::event_info::event_operations const remove_graph::operations = { - &new_remove_graph, nullptr, nullptr}; + &new_remove_graph}; diff --git a/bbdo/storage/status.cc b/centreon-broker/storage/src/status.cc similarity index 92% rename from bbdo/storage/status.cc rename to centreon-broker/storage/src/status.cc index 4d684c5d5aa..82adaf7c065 100644 --- a/bbdo/storage/status.cc +++ b/centreon-broker/storage/src/status.cc @@ -16,11 +16,17 @@ ** For more information : contact@centreon.com */ -#include "bbdo/storage/status.hh" +#include "com/centreon/broker/storage/status.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::storage; +/************************************** + * * + * Public Methods * + * * + **************************************/ + /** * Default constructor. */ @@ -129,5 +135,4 @@ mapping::entry const status::entries[] = { static io::data* new_status() { return new status; } -io::event_info::event_operations const status::operations = {&new_status, - nullptr, nullptr}; +io::event_info::event_operations const status::operations = {&new_status}; diff --git a/centreon-broker/storage/src/stream.cc b/centreon-broker/storage/src/stream.cc index eaf84a36a7e..a61f4a0433f 100644 --- a/centreon-broker/storage/src/stream.cc +++ b/centreon-broker/storage/src/stream.cc @@ -23,21 +23,22 @@ #include #include -#include "bbdo/storage/index_mapping.hh" -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/remove_graph.hh" -#include "bbdo/storage/status.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/neb/host.hh" #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/broker/neb/service_status.hh" #include "com/centreon/broker/storage/conflict_manager.hh" +#include "com/centreon/broker/storage/exceptions/perfdata.hh" +#include "com/centreon/broker/storage/index_mapping.hh" +#include "com/centreon/broker/storage/metric.hh" +#include "com/centreon/broker/storage/parser.hh" +#include "com/centreon/broker/storage/perfdata.hh" +#include "com/centreon/broker/storage/remove_graph.hh" +#include "com/centreon/broker/storage/status.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; diff --git a/centreon-broker/storage/test/connector.cc b/centreon-broker/storage/test/connector.cc index e29275c4fc1..5a104f91428 100644 --- a/centreon-broker/storage/test/connector.cc +++ b/centreon-broker/storage/test/connector.cc @@ -1,5 +1,5 @@ /* - * Copyright 2011 - 2021 Centreon (https://www.centreon.com/) + * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/centreon-broker/storage/test/metric.cc b/centreon-broker/storage/test/metric.cc index 55b166f9af1..0bf48f84ac2 100644 --- a/centreon-broker/storage/test/metric.cc +++ b/centreon-broker/storage/test/metric.cc @@ -17,12 +17,12 @@ * */ -#include "bbdo/storage/metric.hh" +#include "com/centreon/broker/storage/metric.hh" #include #include #include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/misc/perfdata.hh" #include "com/centreon/broker/storage/internal.hh" +#include "com/centreon/broker/storage/perfdata.hh" using namespace com::centreon::broker; @@ -51,7 +51,8 @@ TEST(StorageMetric, DefaultCtor) { // Build object. storage::metric m; - auto val(io::events::data_type::value); + auto val( + io::events::data_type::value); // Check properties values. ASSERT_FALSE(m.ctime != 0); @@ -61,6 +62,6 @@ TEST(StorageMetric, DefaultCtor) { ASSERT_FALSE(!m.name.empty()); ASSERT_FALSE(m.rrd_len != 0); ASSERT_FALSE(!std::isnan(m.value)); - ASSERT_FALSE(m.value_type != misc::perfdata::gauge); + ASSERT_FALSE(m.value_type != storage::perfdata::gauge); ASSERT_FALSE(m.type() != val); } diff --git a/centreon-broker/storage/test/perfdata.cc b/centreon-broker/storage/test/perfdata.cc index 93ab53b6b8d..125f34c47bd 100644 --- a/centreon-broker/storage/test/perfdata.cc +++ b/centreon-broker/storage/test/perfdata.cc @@ -17,6 +17,8 @@ * */ +#include "com/centreon/broker/storage/exceptions/perfdata.hh" + #include #include @@ -24,8 +26,8 @@ #include #include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/perfdata.hh" +#include "com/centreon/broker/storage/parser.hh" +#include "com/centreon/broker/storage/perfdata.hh" using namespace com::centreon::broker; @@ -34,7 +36,7 @@ using namespace com::centreon::broker; */ TEST(StoragePerfdata, Assign) { // First object. - misc::perfdata p1; + storage::perfdata p1; p1.critical(42.0); p1.critical_low(-456.032); p1.critical_mode(false); @@ -43,13 +45,13 @@ TEST(StoragePerfdata, Assign) { p1.name("foo"); p1.unit("bar"); p1.value(52189.912); - p1.value_type(misc::perfdata::counter); + p1.value_type(storage::perfdata::counter); p1.warning(4548.0); p1.warning_low(42.42); p1.warning_mode(true); // Second object. - misc::perfdata p2; + storage::perfdata p2; p2.critical(2345678.9672374); p2.critical_low(-3284523786.8923); p2.critical_mode(true); @@ -58,7 +60,7 @@ TEST(StoragePerfdata, Assign) { p2.name("merethis"); p2.unit("centreon"); p2.value(8374598345.234); - p2.value_type(misc::perfdata::absolute); + p2.value_type(storage::perfdata::absolute); p2.warning(0.823745784); p2.warning_low(NAN); p2.warning_mode(false); @@ -75,7 +77,7 @@ TEST(StoragePerfdata, Assign) { p1.name("baz"); p1.unit("qux"); p1.value(3485.9); - p1.value_type(misc::perfdata::derive); + p1.value_type(storage::perfdata::derive); p1.warning(3612.0); p1.warning_low(-987579.0); p1.warning_mode(false); @@ -89,7 +91,7 @@ TEST(StoragePerfdata, Assign) { ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); + ASSERT_FALSE(p1.value_type() != storage::perfdata::derive); ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); ASSERT_FALSE(p1.warning_mode()); @@ -101,7 +103,7 @@ TEST(StoragePerfdata, Assign) { ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); + ASSERT_FALSE(p2.value_type() != storage::perfdata::counter); ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); ASSERT_FALSE(!p2.warning_mode()); @@ -112,7 +114,7 @@ TEST(StoragePerfdata, Assign) { */ TEST(StoragePerfdata, CopyCtor) { // First object. - misc::perfdata p1; + storage::perfdata p1; p1.critical(42.0); p1.critical_low(-456.032); p1.critical_mode(false); @@ -121,13 +123,13 @@ TEST(StoragePerfdata, CopyCtor) { p1.name("foo"); p1.unit("bar"); p1.value(52189.912); - p1.value_type(misc::perfdata::counter); + p1.value_type(storage::perfdata::counter); p1.warning(4548.0); p1.warning_low(42.42); p1.warning_mode(true); // Second object. - misc::perfdata p2(p1); + storage::perfdata p2(p1); // Change first object. p1.critical(9432.5); @@ -138,7 +140,7 @@ TEST(StoragePerfdata, CopyCtor) { p1.name("baz"); p1.unit("qux"); p1.value(3485.9); - p1.value_type(misc::perfdata::derive); + p1.value_type(storage::perfdata::derive); p1.warning(3612.0); p1.warning_low(-987579.0); p1.warning_mode(false); @@ -152,7 +154,7 @@ TEST(StoragePerfdata, CopyCtor) { ASSERT_FALSE(p1.name() != "baz"); ASSERT_FALSE(p1.unit() != "qux"); ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); + ASSERT_FALSE(p1.value_type() != storage::perfdata::derive); ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); ASSERT_FALSE(p1.warning_mode()); @@ -164,7 +166,7 @@ TEST(StoragePerfdata, CopyCtor) { ASSERT_FALSE(p2.name() != "foo"); ASSERT_FALSE(p2.unit() != "bar"); ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); + ASSERT_FALSE(p2.value_type() != storage::perfdata::counter); ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); ASSERT_FALSE(!p2.warning_mode()); @@ -177,7 +179,7 @@ TEST(StoragePerfdata, CopyCtor) { */ TEST(StoragePerfdata, DefaultCtor) { // Build object. - misc::perfdata p; + storage::perfdata p; // Check properties values. ASSERT_FALSE(!std::isnan(p.critical())); @@ -188,7 +190,7 @@ TEST(StoragePerfdata, DefaultCtor) { ASSERT_FALSE(!p.name().empty()); ASSERT_FALSE(!p.unit().empty()); ASSERT_FALSE(!std::isnan(p.value())); - ASSERT_FALSE(p.value_type() != misc::perfdata::gauge); + ASSERT_FALSE(p.value_type() != storage::perfdata::gauge); ASSERT_FALSE(!std::isnan(p.warning())); ASSERT_FALSE(!std::isnan(p.warning_low())); ASSERT_FALSE(p.warning_mode()); @@ -200,20 +202,22 @@ class StorageParserParsePerfdata : public testing::Test { void TearDown() override { config::applier::deinit(); }; }; -// Given a misc::parser object +// Given a storage::parser object // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list TEST_F(StorageParserParsePerfdata, Simple1) { // Parse perfdata. - std::list lst{misc::parse_perfdata( - 0, 0, "time=2.45698s;2.000000;5.000000;0.000000;10.000000")}; + std::list lst; + storage::parser p; + p.parse_perfdata(0, 0, "time=2.45698s;2.000000;5.000000;0.000000;10.000000", + lst); // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + storage::perfdata expected; expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.warning(2.0); @@ -227,15 +231,16 @@ TEST_F(StorageParserParsePerfdata, Simple1) { TEST_F(StorageParserParsePerfdata, Simple2) { // Parse perfdata. - std::list list{ - misc::parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100")}; + std::list list; + storage::parser p; + p.parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100", list); // Assertions. ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + storage::perfdata expected; expected.name("ABCD12E"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(18.0); expected.unit("%"); expected.warning(std::numeric_limits::infinity()); @@ -249,21 +254,23 @@ TEST_F(StorageParserParsePerfdata, Simple2) { TEST_F(StorageParserParsePerfdata, Complex1) { // Parse perfdata. - std::list list{ - misc::parse_perfdata( + std::list list; + storage::parser p; + p.parse_perfdata( 0, 0, "time=2.45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " "infotraffic=18x;;;; a[foo]=1234;10;11: c[bar]=1234;~:10;20:30 " - "baz=1234;@10:20; 'q u x'=9queries_per_second;@10:;@5:;0;100")}; + "baz=1234;@10:20; 'q u x'=9queries_per_second;@10:;@5:;0;100", + list); // Assertions. ASSERT_EQ(list.size(), 7u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + storage::perfdata expected; // #1. expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.max(std::numeric_limits::infinity()); @@ -271,9 +278,9 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ++it; // #2. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("metric"); - expected.value_type(misc::perfdata::derive); + expected.value_type(storage::perfdata::derive); expected.value(239765); expected.unit("B/s"); expected.warning(5.0); @@ -283,18 +290,18 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ++it; // #3. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(18.0); expected.unit("x"); ASSERT_TRUE(expected == *it); ++it; // #4. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("foo"); - expected.value_type(misc::perfdata::absolute); + expected.value_type(storage::perfdata::absolute); expected.value(1234.0); expected.warning(10.0); expected.warning_low(0.0); @@ -304,9 +311,9 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ++it; // #5. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("bar"); - expected.value_type(misc::perfdata::counter); + expected.value_type(storage::perfdata::counter); expected.value(1234.0); expected.warning(10.0); expected.warning_low(-std::numeric_limits::infinity()); @@ -316,9 +323,9 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ++it; // #6. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("baz"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(1234.0); expected.warning(20.0); expected.warning_low(10.0); @@ -327,9 +334,9 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ++it; // #7. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("q u x"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(9.0); expected.unit("queries_per_second"); expected.warning(std::numeric_limits::infinity()); @@ -343,25 +350,27 @@ TEST_F(StorageParserParsePerfdata, Complex1) { ASSERT_TRUE(expected == *it); } -// Given a misc::parser object +// Given a storage::parser object // When parse_perfdata() is called multiple time with valid strings // Then the corresponding perfdata list is returned TEST_F(StorageParserParsePerfdata, Loop) { // Objects. - std::list list; + std::list list; + storage::parser p; // Loop. for (uint32_t i(0); i < 10000; ++i) { // Parse perfdata string. - list = misc::parse_perfdata( - 0, 0, "c[time]=2.45698s;2.000000;5.000000;0.000000;10.000000"); + list.clear(); + p.parse_perfdata( + 0, 0, "c[time]=2.45698s;2.000000;5.000000;0.000000;10.000000", list); // Assertions. ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + storage::perfdata expected; expected.name("time"); - expected.value_type(misc::perfdata::counter); + expected.value_type(storage::perfdata::counter); expected.value(2.45698); expected.unit("s"); expected.warning(2.0); @@ -375,34 +384,46 @@ TEST_F(StorageParserParsePerfdata, Loop) { } } -// Given a misc::parser object +// Given a storage::parser object // When parse_perfdata() is called with an invalid string +// Then it throws a storage::exceptions::perfdata TEST_F(StorageParserParsePerfdata, Incorrect1) { + // Objects. + std::list list; + storage::parser p; + // Attempt to parse perfdata. - auto list{misc::parse_perfdata(0, 0, "metric1= 10 metric2=42")}; + p.parse_perfdata(0, 0, "metric1= 10 metric2=42", list); ASSERT_EQ(list.size(), 1u); ASSERT_EQ(list.back().name(), "metric2"); ASSERT_EQ(list.back().value(), 42); } -// Given a misc::parser object +// Given a storage::parser object // When parse_perfdata() is called with a metric without value but with unit +// Then it throws a storage::exceptions::perfdata TEST_F(StorageParserParsePerfdata, Incorrect2) { + // Given + std::list list; + storage::parser p; + // Then - auto list{misc::parse_perfdata(0, 0, "metric=kb/s")}; + p.parse_perfdata(0, 0, "metric=kb/s", list); ASSERT_TRUE(list.empty()); } TEST_F(StorageParserParsePerfdata, LabelWithSpaces) { // Parse perfdata. - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; + std::list lst; + storage::parser p; + p.parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;", lst); // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + storage::perfdata expected; expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(2); expected.unit("s"); expected.warning(2.0); @@ -414,14 +435,16 @@ TEST_F(StorageParserParsePerfdata, LabelWithSpaces) { TEST_F(StorageParserParsePerfdata, LabelWithSpacesMultiline) { // Parse perfdata. - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; + std::list lst; + storage::parser p; + p.parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;", lst); // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + storage::perfdata expected; expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(2); expected.unit("s"); expected.warning(2.0); @@ -433,20 +456,23 @@ TEST_F(StorageParserParsePerfdata, LabelWithSpacesMultiline) { TEST_F(StorageParserParsePerfdata, Complex2) { // Parse perfdata. - auto list{misc::parse_perfdata( + std::list list; + storage::parser p; + p.parse_perfdata( 0, 0, "' \n time'=2,45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " "g[test]=8x;;;;" - " infotraffic=18,6x;;;; a[foo]=1234,17;10;11: c[bar]=1234,147;~:10;20:30")}; + " infotraffic=18,6x;;;; a[foo]=1234,17;10;11: c[bar]=1234,147;~:10;20:30", + list); // Assertions. ASSERT_EQ(list.size(), 6u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; + std::list::const_iterator it(list.begin()); + storage::perfdata expected; // #1. expected.name("time"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(2.45698); expected.unit("s"); expected.max(std::numeric_limits::infinity()); @@ -455,9 +481,9 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; // #2. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("metric"); - expected.value_type(misc::perfdata::derive); + expected.value_type(storage::perfdata::derive); expected.value(239765); expected.unit("B/s"); expected.warning(5.0); @@ -468,9 +494,9 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; // #3. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("test"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(8); expected.unit("x"); ASSERT_TRUE(expected == *it); @@ -478,9 +504,9 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; // #4. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(18.6); expected.unit("x"); ASSERT_TRUE(expected == *it); @@ -488,9 +514,9 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; // #5. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("foo"); - expected.value_type(misc::perfdata::absolute); + expected.value_type(storage::perfdata::absolute); expected.value(1234.17); expected.warning(10.0); expected.warning_low(0.0); @@ -501,9 +527,9 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; // #6. - expected = misc::perfdata(); + expected = storage::perfdata(); expected.name("bar"); - expected.value_type(misc::perfdata::counter); + expected.value_type(storage::perfdata::counter); expected.value(1234.147); expected.warning(10.0); expected.warning_low(-std::numeric_limits::infinity()); @@ -514,18 +540,22 @@ TEST_F(StorageParserParsePerfdata, Complex2) { ++it; } -// Given a misc::parser object +// Given a storage::parser object // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list TEST_F(StorageParserParsePerfdata, SimpleWithR) { - auto lst{misc::parse_perfdata(0, 0, "'total'=5;;;0;\r")}; + // Parse perfdata. + std::list lst; + storage::parser p; + // ASSERT_NO_THROW(p.parse_perfdata("'total'=5;;;0;\r", lst)); + ASSERT_NO_THROW(p.parse_perfdata(0, 0, "'total'=5;;;0;\r", lst)); // Assertions. ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; + std::list::const_iterator it(lst.begin()); + storage::perfdata expected; expected.name("total"); - expected.value_type(misc::perfdata::gauge); + expected.value_type(storage::perfdata::gauge); expected.value(5); expected.unit(""); expected.warning(NAN); @@ -537,11 +567,14 @@ TEST_F(StorageParserParsePerfdata, SimpleWithR) { ASSERT_TRUE(expected == *it); } -// Given a misc::parser object +// Given a storage::parser object // When parse_perfdata() is called with a valid perfdata string // Then perfdata are returned in a list TEST_F(StorageParserParsePerfdata, BadMetric) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3")}; + // Parse perfdata. + std::list lst; + storage::parser p; + ASSERT_NO_THROW(p.parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3", lst)); // Assertions. ASSERT_EQ(lst.size(), 3u); @@ -554,7 +587,11 @@ TEST_F(StorageParserParsePerfdata, BadMetric) { } TEST_F(StorageParserParsePerfdata, BadMetric1) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3")}; + // Parse perfdata. + std::list lst; + storage::parser p; + ASSERT_NO_THROW( + p.parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3", lst)); // Assertions. ASSERT_EQ(lst.size(), 3u); diff --git a/centreon-broker/storage/test/rebuild.cc b/centreon-broker/storage/test/rebuild.cc index 267037ea5e2..346f4a895ff 100644 --- a/centreon-broker/storage/test/rebuild.cc +++ b/centreon-broker/storage/test/rebuild.cc @@ -17,7 +17,7 @@ * */ -#include "bbdo/storage/rebuild.hh" +#include "com/centreon/broker/storage/rebuild.hh" #include #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/storage/internal.hh" @@ -42,7 +42,8 @@ TEST(StorageRebuild, DefaultCtor) { */ TEST(StorageRebuild, ReturnType) { storage::rebuild r; - auto val = io::events::data_type::value; + auto val = + io::events::data_type::value; ASSERT_TRUE(r.static_type() == val); ASSERT_TRUE(r.type() == val); diff --git a/centreon-broker/storage/test/rebuild2.cc b/centreon-broker/storage/test/rebuild2.cc deleted file mode 100644 index 93a3b8c3618..00000000000 --- a/centreon-broker/storage/test/rebuild2.cc +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright 2021 Centreon (https://www.centreon.com/) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - * - */ - -#include -#include - -#include -#include -#include -#include - -#include "com/centreon/broker/bbdo/stream.hh" -#include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/config/applier/modules.hh" -#include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/lua/macro_cache.hh" -#include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/misc/variant.hh" -#include "com/centreon/broker/neb/instance.hh" -#include "com/centreon/broker/persistent_file.hh" -#include "com/centreon/broker/storage/internal.hh" - -using namespace com::centreon::broker; -using namespace com::centreon::broker::misc; -using namespace google::protobuf::util; - -class into_memory : public io::stream { - public: - into_memory() : io::stream("into_memory"), _memory() {} - ~into_memory() override {} - - bool read(std::shared_ptr& d, - time_t deadline = (time_t)-1) override { - (void)deadline; - if (_memory.empty()) - return false; - std::shared_ptr raw(new io::raw); - raw->get_buffer() = std::move(_memory); - _memory.clear(); - d = raw; - return true; - } - - int write(std::shared_ptr const& d) override { - _memory = std::static_pointer_cast(d)->get_buffer(); - return 1; - } - - int32_t stop() override { return 0; } - - std::vector const& get_memory() const { return _memory; } - std::vector& get_mutable_memory() { return _memory; } - - private: - std::vector _memory; -}; - -class StorageRebuild2Test : public ::testing::Test { - public: - void SetUp() override { - io::data::broker_id = 0; - try { - config::applier::init(0, "broker_test"); - } catch (std::exception const& e) { - (void)e; - } - std::shared_ptr pcache( - std::make_shared("/tmp/broker_test_cache")); - } - - void TearDown() override { - // The cache must be destroyed before the applier deinit() call. - config::applier::deinit(); - ::remove("/tmp/broker_test_cache"); - ::remove(log_v2::instance().log_name().c_str()); - } -}; - -// When a script is correctly loaded and a neb event has to be sent -// Then this event is translated into a Lua table and sent to the lua write() -// function. -TEST_F(StorageRebuild2Test, WriteReadRebuild2) { - config::applier::modules modules; - modules.load_file("./storage/20-storage.so"); - - std::shared_ptr r( - std::make_shared()); - r->obj.mutable_metric()->set_metric_id(1234); - r->obj.mutable_metric()->set_value_type(0); - for (int i = 0; i < 20; i++) { - Point* p = r->obj.add_data(); - p->set_ctime(i); - p->set_value(i * i); - } - - std::shared_ptr memory_stream(std::make_shared()); - bbdo::stream stm(true); - stm.set_substream(memory_stream); - stm.set_coarse(false); - stm.set_negotiate(false); - stm.negotiate(bbdo::stream::negotiate_first); - stm.write(r); - std::vector const& mem1 = memory_stream->get_memory(); - - constexpr size_t size = 270u; - ASSERT_EQ(mem1.size(), size); - // The size is size - 16: 16 is the header size. - for (uint32_t i = 0; i < size; i++) { - printf("%02x ", static_cast(0xff & mem1[i])); - if ((i & 0x1f) == 0) - puts(""); - } - puts(""); - - ASSERT_EQ(htons(*reinterpret_cast(&mem1[0] + 2)), size - 16); - - std::shared_ptr e; - stm.read(e, time(nullptr) + 1000); - std::shared_ptr new_r = - std::static_pointer_cast(e); - ASSERT_TRUE(MessageDifferencer::Equals(r->obj, new_r->obj)); -} - -// When a script is correctly loaded and a neb event has to be sent -// Then this event is translated into a Lua table and sent to the lua write() -// function. -TEST_F(StorageRebuild2Test, LongWriteReadRebuild2) { - config::applier::modules modules; - modules.load_file("./storage/20-storage.so"); - - std::shared_ptr r( - std::make_shared()); - r->obj.mutable_metric()->set_metric_id(1234); - r->obj.mutable_metric()->set_value_type(0); - for (int i = 0; i < 20000; i++) { - Point* p = r->obj.add_data(); - p->set_ctime(i); - p->set_value(i * i); - } - - std::shared_ptr memory_stream(std::make_shared()); - bbdo::stream stm(true); - stm.set_substream(memory_stream); - stm.set_coarse(false); - stm.set_negotiate(false); - stm.negotiate(bbdo::stream::negotiate_first); - stm.write(r); - std::vector const& mem1 = memory_stream->get_memory(); - - constexpr size_t size = 283562; - ASSERT_EQ(mem1.size(), size); - - const char* tmp = &mem1[0]; - - for (int i = 0; i < 4; i++) { - std::cout << "test " << i << std::endl; - ASSERT_EQ(htons(*reinterpret_cast(tmp + 2)), 0xffff); - tmp += 16 + 0xffff; - } - ASSERT_EQ(htons(*reinterpret_cast(tmp + 2)), 21342); - - std::shared_ptr e; - stm.read(e, time(nullptr) + 1000); - std::shared_ptr new_r = - std::static_pointer_cast(e); - ASSERT_TRUE(MessageDifferencer::Equals(r->obj, new_r->obj)); -} diff --git a/centreon-broker/storage/test/remove_graph.cc b/centreon-broker/storage/test/remove_graph.cc index 92577653b83..d2a198429b4 100644 --- a/centreon-broker/storage/test/remove_graph.cc +++ b/centreon-broker/storage/test/remove_graph.cc @@ -17,7 +17,7 @@ * */ -#include "bbdo/storage/remove_graph.hh" +#include "com/centreon/broker/storage/remove_graph.hh" #include #include #include @@ -39,8 +39,8 @@ TEST(StorageRemoveGraph, Constructor) { */ TEST(StorageRemoveGraph, ReturnType) { storage::remove_graph r; - auto val = - io::events::data_type::value; + auto val = io::events::data_type::value; ASSERT_TRUE(r.static_type() == val); ASSERT_TRUE(r.type() == val); diff --git a/centreon-broker/storage/test/status-entry.cc b/centreon-broker/storage/test/status-entry.cc index 4398e12aa40..6fd46367bc3 100644 --- a/centreon-broker/storage/test/status-entry.cc +++ b/centreon-broker/storage/test/status-entry.cc @@ -24,7 +24,6 @@ #include #include -#include "bbdo/storage/status.hh" #include "com/centreon/broker/bbdo/stream.hh" #include "com/centreon/broker/config/applier/init.hh" #include "com/centreon/broker/io/events.hh" @@ -37,6 +36,7 @@ #include "com/centreon/broker/modules/handle.hh" #include "com/centreon/broker/neb/instance.hh" #include "com/centreon/broker/storage/factory.hh" +#include "com/centreon/broker/storage/status.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::misc; @@ -98,8 +98,12 @@ class StatusEntryTest : public ::testing::Test { TEST_F(StatusEntryTest, WriteStatus) { io::events& e(io::events::instance()); + // Register category. + int storage_category(e.register_category("storage", io::events::storage)); + ASSERT_TRUE(storage_category == io::events::storage); + // Register event status. - e.register_event(make_type(io::storage, storage::de_status), "status", + e.register_event(io::events::storage, storage::de_status, "status", &storage::status::operations, storage::status::entries); // Register storage layer. @@ -125,6 +129,6 @@ TEST_F(StatusEntryTest, WriteStatus) { ASSERT_EQ(st->index_id, new_st->index_id); ASSERT_EQ(st->state, new_st->state); - io::events::instance().unregister_category(io::storage); + io::events::instance().unregister_category(io::events::storage); io::protocols::instance().unreg("storage"); } diff --git a/centreon-broker/storage/test/status.cc b/centreon-broker/storage/test/status.cc index d99e1ae70bf..580bbb7c907 100644 --- a/centreon-broker/storage/test/status.cc +++ b/centreon-broker/storage/test/status.cc @@ -17,7 +17,7 @@ * */ -#include "bbdo/storage/status.hh" +#include "com/centreon/broker/storage/status.hh" #include #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/storage/internal.hh" @@ -119,7 +119,8 @@ TEST(StorageStatus, DefaultCtor) { // Build object. storage::status s; - auto val(io::events::data_type::value); + auto val( + io::events::data_type::value); // Check properties values. ASSERT_FALSE(s.ctime != 0); diff --git a/centreon-broker/tcp/src/tcp_async.cc b/centreon-broker/tcp/src/tcp_async.cc index 0bc8bd6eb5e..76f164fccd5 100644 --- a/centreon-broker/tcp/src/tcp_async.cc +++ b/centreon-broker/tcp/src/tcp_async.cc @@ -68,8 +68,8 @@ void tcp_async::unload() { * method. */ tcp_async::tcp_async() - : _strand{pool::instance().io_context()}, - _clear_available_con_running(false) {} + : _clear_available_con_running(false), + _strand{pool::instance().io_context()} {} /** * @brief Stop the timer that clears available connections. diff --git a/centreon-broker/tcp/src/tcp_connection.cc b/centreon-broker/tcp/src/tcp_connection.cc index ee69590cd65..83ca6201cbf 100644 --- a/centreon-broker/tcp/src/tcp_connection.cc +++ b/centreon-broker/tcp/src/tcp_connection.cc @@ -94,7 +94,7 @@ int32_t tcp_connection::flush() { { std::lock_guard lck(_error_m); if (_current_error) { - std::string msg{_current_error.message()}; + std::string msg{std::move(_current_error.message())}; _current_error.clear(); throw msg_fmt(msg); } @@ -173,7 +173,7 @@ int32_t tcp_connection::write(const std::vector& v) { { std::lock_guard lck(_error_m); if (_current_error) { - std::string msg{_current_error.message()}; + std::string msg{std::move(_current_error.message())}; _current_error.clear(); throw msg_fmt(msg); } @@ -329,7 +329,7 @@ std::vector tcp_connection::read(time_t timeout_time, bool* timeout) { { std::lock_guard lck(_error_m); if (_current_error) { - std::string msg{_current_error.message()}; + std::string msg{std::move(_current_error.message())}; _current_error.clear(); throw msg_fmt(msg); } diff --git a/centreon-broker/tcp/test/acceptor.cc b/centreon-broker/tcp/test/acceptor.cc index 44128b65d02..659a6a827d4 100644 --- a/centreon-broker/tcp/test/acceptor.cc +++ b/centreon-broker/tcp/test/acceptor.cc @@ -25,9 +25,9 @@ #include #include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/pool.hh" #include "com/centreon/broker/tcp/connector.hh" +#include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tcp/tcp_async.hh" #include "com/centreon/exceptions/msg_fmt.hh" @@ -39,10 +39,8 @@ constexpr static uint16_t test_port(4444); class TcpAcceptor : public ::testing::Test { public: - void SetUp() override { - pool::load(0); - tcp::tcp_async::load(); - } + void SetUp() override { pool::load(0); + tcp::tcp_async::load(); } void TearDown() override { log_v2::tcp()->info("TCP TearDown"); @@ -145,8 +143,7 @@ TEST_F(TcpAcceptor, QuestionAnswer) { bool cbd_finished = false; std::thread cbd([&cbd_m, &cbd_cv, &cbd_finished] { - std::unique_ptr endp( - std::make_unique(4141, -1)); + std::unique_ptr endp(std::make_unique(4141, -1)); /* Nominal case, cbd is acceptor and read on the socket */ std::unique_ptr u_cbd; @@ -392,8 +389,7 @@ TEST_F(TcpAcceptor, NominalReversed) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); std::thread cbd([&cbd_m, &cbd_finished, &cbd_cv] { - std::unique_ptr endp( - std::make_unique(4141, -1)); + std::unique_ptr endp(std::make_unique(4141, -1)); std::unique_ptr u_cbd; do { diff --git a/centreon-broker/test/CMakeLists.txt b/centreon-broker/test/CMakeLists.txt index 52fc0b9cc55..262c663c65a 100644 --- a/centreon-broker/test/CMakeLists.txt +++ b/centreon-broker/test/CMakeLists.txt @@ -1,5 +1,5 @@ ## -## Copyright 2016-2021 Centreon +## Copyright 2016-2017 Centreon ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ ## For more information : contact@centreon.com ## +find_package(GTest REQUIRED) include_directories(${GTest_INCLUDE_DIRS}) link_directories(${GTest_LIB_DIRS}) @@ -27,9 +28,7 @@ set(WDOG_TESTS_DIR ${PROJECT_SOURCE_DIR}/watchdog/test) # Include directories. include_directories(${PROJECT_SOURCE_DIR}/bam/inc) include_directories(${PROJECT_SOURCE_DIR}/bam/test) -include_directories(${PROJECT_SOURCE_DIR}/storage/src) include_directories(${PROJECT_SOURCE_DIR}/storage/inc) -include_directories(${PROJECT_SOURCE_DIR}/unified_sql/inc) include_directories(${PROJECT_SOURCE_DIR}/graphite/inc) include_directories(${PROJECT_SOURCE_DIR}/sql/inc) include_directories(${PROJECT_SOURCE_DIR}/influxdb/inc) @@ -83,11 +82,13 @@ add_executable(ut ${TESTS_DIR}/misc/filesystem.cc ${TESTS_DIR}/misc/math.cc ${TESTS_DIR}/misc/misc.cc - ${TESTS_DIR}/misc/perfdata.cc ${TESTS_DIR}/misc/string.cc ${TESTS_DIR}/misc/stringifier.cc ${TESTS_DIR}/modules/module.cc + ${TESTS_DIR}/multiplexing/engine/hook.cc + ${TESTS_DIR}/multiplexing/engine/hooker.cc ${TESTS_DIR}/multiplexing/engine/start_stop.cc + ${TESTS_DIR}/multiplexing/engine/unhook.cc ${TESTS_DIR}/multiplexing/muxer/read.cc ${TESTS_DIR}/multiplexing/publisher/read.cc ${TESTS_DIR}/multiplexing/publisher/write.cc @@ -105,7 +106,9 @@ add_executable(ut ${TESTS_SOURCES} ) -target_link_libraries(ut roker rokerbase ${TESTS_LIBRARIES} conflictmgr +#set_target_properties("ut" PROPERTIES COMPILE_FLAGS "${MYSQL_CFLAGS}") + +target_link_libraries(ut rokerbase roker ${TESTS_LIBRARIES} conflictmgr ${nlohmann_json_LIBS} ${asio_LIBS} ${fmt_LIBS} ${spdlog_LIBS} ${GTest_LIBS} ${mariadb-connector-c_LIBS} ${OpenSSL_LIBS} ${gRPC_LIBS} ${absl_LIBS} ) add_test(NAME tests COMMAND ut) diff --git a/centreon-broker/unified_sql/CMakeLists.txt b/centreon-broker/unified_sql/CMakeLists.txt deleted file mode 100644 index 6d27abf2bd5..00000000000 --- a/centreon-broker/unified_sql/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -## -## Copyright 2021 Centreon -## -## Licensed under the Apache License, Version 2.0 (the "License"); -## you may not use this file except in compliance with the License. -## You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## -## For more information : contact@centreon.com -## - -# Global options. -set(INC_DIR "${PROJECT_SOURCE_DIR}/unified_sql/inc") -set(SRC_DIR "${PROJECT_SOURCE_DIR}/unified_sql/src") -set(TEST_DIR "${PROJECT_SOURCE_DIR}/unified_sql/test") -include_directories("${INC_DIR}" "${SRC_DIR}") -include_directories("${PROJECT_SOURCE_DIR}/neb/inc") -include_directories("${CMAKE_SOURCE_DIR}") -set(INC_DIR "${INC_DIR}/com/centreon/broker/unified_sql") - -get_protobuf_files(rebuild) - -# Storage module. -set(UNIFIED_SQL "20-unified_sql") -set(UNIFIED_SQL "${UNIFIED_SQL}" PARENT_SCOPE) -add_library("${UNIFIED_SQL}" SHARED - # Sources. - "${SRC_DIR}/connector.cc" - "${SRC_DIR}/factory.cc" - "${SRC_DIR}/main.cc" - "${SRC_DIR}/rebuilder.cc" - "${SRC_DIR}/stored_timestamp.cc" - "${SRC_DIR}/stream.cc" - "${SRC_DIR}/stream_sql.cc" - "${SRC_DIR}/stream_storage.cc" - ${proto_rebuild} - # Headers. - "${INC_DIR}/connector.hh" - "${INC_DIR}/events.hh" - "${INC_DIR}/factory.hh" - "${INC_DIR}/internal.hh" - "${INC_DIR}/rebuilder.hh" - "${INC_DIR}/stored_timestamp.hh" - "${INC_DIR}/stream.hh" -) -set_target_properties("${UNIFIED_SQL}" PROPERTIES - PREFIX "" - COMPILE_FLAGS "-fPIC") -target_link_libraries(${UNIFIED_SQL} rokerbase bbdo_storage) - -# Testing. -if (WITH_TESTING) - if (WITH_SQL_TESTS) - set(TEST_SOURCES ${TESTS_SOURCES} ${TEST_DIR}/conflict_manager.cc) - endif (WITH_SQL_TESTS) - - # Testing. - set( - TESTS_SOURCES - ${TESTS_SOURCES} - ${TEST_DIR}/connector.cc - ${TEST_DIR}/metric.cc - ${TEST_DIR}/rebuild.cc - ${TEST_DIR}/rebuild2.cc - ${TEST_DIR}/remove_graph.cc - ${TEST_DIR}/status.cc - ${TEST_DIR}/status-entry.cc - PARENT_SCOPE - ) - set( - TESTS_LIBRARIES - ${TESTS_LIBRARIES} - ${UNIFIED_SQL} - PARENT_SCOPE - ) -endif() - -# Install rule. -install(TARGETS "${UNIFIED_SQL}" - LIBRARY DESTINATION "${PREFIX_MODULES}" -) diff --git a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/connector.hh b/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/connector.hh deleted file mode 100644 index 6f86d8aa592..00000000000 --- a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/connector.hh +++ /dev/null @@ -1,63 +0,0 @@ -/* -** Copyright 2011-2013,2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#ifndef CCB_UNIFIED_SQL_CONNECTOR_HH -#define CCB_UNIFIED_SQL_CONNECTOR_HH - -#include "com/centreon/broker/database_config.hh" -#include "com/centreon/broker/io/endpoint.hh" -#include "com/centreon/broker/namespace.hh" - -CCB_BEGIN() - -namespace unified_sql { -/** - * @class connector connector.hh "com/centreon/broker/unified_sql/connector.hh" - * @brief Connect to a database. - * - * Send perfdata in a Centreon Storage database. - */ -class connector : public io::endpoint { - database_config _dbcfg; - uint32_t _interval_length; - uint32_t _loop_timeout; - uint32_t _instance_timeout; - uint32_t _rebuild_check_interval; - uint32_t _rrd_len; - bool _store_in_data_bin; - - public: - connector(); - ~connector() noexcept = default; - connector(const connector&) = delete; - connector& operator=(const connector&) = delete; - bool operator==(const connector& other) = delete; - void connect_to(const database_config& dbcfg, - uint32_t rrd_len, - uint32_t interval_length, - uint32_t loop_timeout, - uint32_t instance_timeout, - uint32_t rebuild_check_interval, - bool store_in_data_bin = true); - std::unique_ptr open() override; -}; -} // namespace unified_sql - -CCB_END() - -#endif // !CCB_UNIFIED_SQL_CONNECTOR_HH diff --git a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/rebuilder.hh b/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/rebuilder.hh deleted file mode 100644 index e17b4d1516f..00000000000 --- a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/rebuilder.hh +++ /dev/null @@ -1,105 +0,0 @@ -/* -** Copyright 2012-2015,2017-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#ifndef CCB_UNIFIED_SQL_REBUILDER_HH -#define CCB_UNIFIED_SQL_REBUILDER_HH - -#include - -#include "com/centreon/broker/database_config.hh" -#include "com/centreon/broker/mysql.hh" -#include "com/centreon/broker/namespace.hh" -#include "com/centreon/broker/pool.hh" - -CCB_BEGIN() - -namespace unified_sql { -/** - * @class rebuilder rebuilder.hh "com/centreon/broker/unified_sql/rebuilder.hh" - * @brief Check for graphs to be rebuild. - * - * Check for graphs to be rebuild at fixed interval. - * - * We don't instantiate a thread to work on the rebuilder. Instead, we use - * the asio mechanism with a steady_timer. The main function is - * rebuilder::_run(). When the rebuilder is constructed, we instanciate _timer - * and ask to execute the _run function when it expires. When the _run() - * function finishes, it reschedules the timer to be executed a new time after - * _rebuild_check_interval seconds. The rebuild destructor cancels the timer. - * - * Each execution of the timer is done using the thread pool accessible from - * the pool object. No new thread is created. - */ -class stream; - -class rebuilder { - asio::steady_timer _timer; - std::atomic_bool _should_exit; - database_config _db_cfg; - std::shared_ptr _connection; - uint32_t _interval_length; - uint32_t _rebuild_check_interval; - uint32_t _rrd_len; - stream* _parent; - - // Local types. - struct index_info { - uint64_t index_id; - uint32_t host_id; - uint32_t service_id; - uint32_t rrd_retention; - }; - - struct metric_info { - uint32_t metric_id; - std::string metric_name; - int16_t metric_type; - }; - - void _next_index_to_rebuild(index_info& info, mysql& ms); - void _rebuild_metric(mysql& ms, - uint32_t metric_id, - uint32_t host_id, - uint32_t service_id, - std::string const& metric_name, - int16_t metric_type, - uint32_t interval, - int64_t length); - void _rebuild_status(mysql& ms, - uint64_t index_id, - uint32_t interval, - int64_t length); - void _send_rebuild_event(bool end, uint64_t id, bool is_index); - void _set_index_rebuild(mysql& db, uint64_t index_id, int16_t state); - void _run(asio::error_code ec); - - public: - rebuilder(database_config const& db_cfg, - stream* parent, - uint32_t interval_length = 60, - uint32_t rebuild_check_interval = 600, - uint32_t rrd_length = 15552000); - ~rebuilder(); - rebuilder(const rebuilder&) = delete; - rebuilder& operator=(const rebuilder&) = delete; -}; -} // namespace unified_sql - -CCB_END() - -#endif // !CCB_UNIFIED_SQL_REBUILDER_HH diff --git a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/stored_timestamp.hh b/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/stored_timestamp.hh deleted file mode 100644 index deef7b2d41a..00000000000 --- a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/stored_timestamp.hh +++ /dev/null @@ -1,64 +0,0 @@ -/* -** Copyright 2014 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#ifndef CCB_UNIFIED_SQL_STORED_TIMESTAMP_HH -#define CCB_UNIFIED_SQL_STORED_TIMESTAMP_HH - -#include "com/centreon/broker/timestamp.hh" - -CCB_BEGIN() - -namespace unified_sql { -/** - * @class stored_timestamp stored_timestamp.hh - * "com/centreon/broker/sql/stored_timestamp.hh" - * @brief Store a timestamp associated to an instance. - * - * The instance can be in a responsive or unresponsive state, and its id is - * stored. - */ -class stored_timestamp { - public: - enum state_type { responsive, unresponsive }; - - private: - uint32_t _instance_id; - timestamp _ts; - state_type _state; - - public: - stored_timestamp() noexcept; - stored_timestamp(uint32_t id, state_type s) noexcept; - stored_timestamp(stored_timestamp const& right) noexcept; - ~stored_timestamp() noexcept = default; - - stored_timestamp& operator=(stored_timestamp const&) = default; - - uint32_t get_id() const noexcept; - state_type get_state() const noexcept; - void set_state(state_type state) noexcept; - void update_timestamp() noexcept; - timestamp get_timestamp() const noexcept; - void set_timestamp(timestamp ts) noexcept; - bool timestamp_outdated(uint32_t timeout) const noexcept; -}; -} // namespace unified_sql - -CCB_END() - -#endif //! CCB_UNIFIED_SQL_STORED_TIMESTAMP_HH diff --git a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh b/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh deleted file mode 100644 index 30ae97b6379..00000000000 --- a/centreon-broker/unified_sql/inc/com/centreon/broker/unified_sql/stream.hh +++ /dev/null @@ -1,340 +0,0 @@ -/* -** Copyright 2019-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ -#ifndef CCB_UNIFIED_SQL_STREAM_HH -#define CCB_UNIFIED_SQL_STREAM_HH -#include -#include -#include -#include -#include -#include -#include -#include - -#include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/io/stream.hh" -#include "com/centreon/broker/misc/pair.hh" -#include "com/centreon/broker/misc/perfdata.hh" -#include "com/centreon/broker/mysql.hh" -#include "com/centreon/broker/unified_sql/rebuilder.hh" -#include "com/centreon/broker/unified_sql/stored_timestamp.hh" - -CCB_BEGIN() -/* Forward declarations */ -namespace neb { -class service_status; -} - -namespace unified_sql { - -/** - * @brief The conflict manager. - * - * Many queries are executed by Broker through the sql connector and also - * the unified_sql connector. Thos queries are made with several connections to - * the database and we don't commit after each query. All those constraints - * are there for performance purpose but they can lead us to database - * deadlocks. To avoid such locks, there is the conflict manager. Sent queries - * are sent to connections through it. The idea behind the conflict manager - * is the following: - * - * * determine the connection to use for the upcoming query. - * * Check that the "action" to execute is compatible with actions already - * running on our connection and also others. If not, solve the issue with - * commits. - * * Send the query to the connection. - * * Add or not an action flag to this connection for next queries. - * - * Another task of the conflict manager is to keep informations for queries. - * Metrics, customvariables are sent in bulk to avoid locks on the database, - * so we keep some containers here to build those big queries. - * - * The conflict manager works with two streams: sql and unified_sql. - * - * To initialize it, two functions are used: - * * init_unified_sql(): initialization of the unified_sql part. This one needs - * the sql part to be initialized before. If it is not already initialized, this - * function waits for it (with a timeout). - * - * Once the object is initialized, we have the classical static internal method - * `instance()`. - */ -class stream : public io::stream { - /* Forward declarations */ - public: - enum instance_state { not_started, running, finished }; - enum stream_type { sql, unified_sql }; - - private: - enum special_conn { - custom_variable, - downtime, - host_dependency, - host_group, - host_parent, - log, - service_dependency, - service_group, - }; - - enum actions { - none = 0, - acknowledgements = 1 << 0, - comments = 1 << 1, - custom_variables = 1 << 2, - downtimes = 1 << 3, - host_dependencies = 1 << 4, - host_hostgroups = 1 << 5, - host_parents = 1 << 6, - hostgroups = 1 << 7, - hosts = 1 << 8, - instances = 1 << 9, - modules = 1 << 10, - service_dependencies = 1 << 11, - service_servicegroups = 1 << 12, - servicegroups = 1 << 13, - services = 1 << 14, - index_data = 1 << 15, - metrics = 1 << 16, - }; - - struct index_info { - std::string host_name; - uint64_t index_id; - bool locked; - uint32_t rrd_retention; - std::string service_description; - bool special; - }; - - static const std::array metric_type_name; - - struct metric_info { - bool locked; - uint32_t metric_id; - uint32_t type; - double value; - std::string unit_name; - double warn; - double warn_low; - bool warn_mode; - double crit; - double crit_low; - bool crit_mode; - double min; - double max; - bool metric_mapping_sent; - }; - struct metric_value { - time_t c_time; - uint32_t metric_id; - short status; - double value; - }; - - static void (stream::*const _neb_processing_table[])( - const std::shared_ptr&); - instance_state _state; - - mutable std::mutex _fifo_m; - std::atomic_int _processed; - std::atomic_int _ack; - - std::atomic_int _pending_events; - uint32_t _count; - - /* Current actions by connection */ - std::vector _action; - - // bool _exit; - uint32_t _loop_timeout; - uint32_t _max_pending_queries; - mysql _mysql; - uint32_t _instance_timeout; - rebuilder _rebuilder; - bool _store_in_db; - uint32_t _rrd_len; - uint32_t _interval_length; - uint32_t _max_perfdata_queries; - uint32_t _max_metrics_queries; - uint32_t _max_cv_queries; - uint32_t _max_log_queries; - - std::time_t _next_insert_perfdatas; - std::time_t _next_update_metrics; - std::time_t _next_update_cv; - std::time_t _next_insert_logs; - std::time_t _next_loop_timeout; - - asio::steady_timer _timer; - /* Stats */ - ConflictManagerStats* _stats; - - /* How many streams are using this stream? */ - std::atomic _ref_count; - - std::unordered_set _cache_deleted_instance_id; - std::unordered_map _cache_host_instance; - std::unordered_map _cache_hst_cmd; - std::unordered_map, size_t> _cache_svc_cmd; - std::unordered_map, index_info> _index_cache; - std::unordered_map, metric_info> - _metric_cache; - std::mutex _metric_cache_m; - - std::unordered_set _hostgroup_cache; - std::unordered_set _servicegroup_cache; - - /* The queue of metrics sent in bulk to the database. The insert is done if - * the loop timeout is reached or if the queue size is greater than - * _max_perfdata_queries. The filled table here is 'data_bin'. */ - mutable std::mutex _queues_m; - std::deque _perfdata_queue; - /* This map is also sent in bulk to the database. The insert is done if - * the loop timeout is reached or if the queue size is greater than - * _max_metrics_queries. Values here are the real time values, so if the - * same metric is recevied two times, the new value can overwrite the old - * one, that's why we store those values in a map. The filled table here is - * 'metrics'. */ - std::unordered_map _metrics; - - /* These queues are sent in bulk to the database. The insert/update is done - * if the loop timeout is reached or if the queue size is greater than - * _max_cv_queries/_max_log_queries. The filled table here is respectively - * 'customvariables'/'logs'. The queue elements are pairs of a string used - * for the query and a pointer to a boolean so that we can acknowledge the - * BBDO event when written. */ - std::deque _cv_queue; - std::deque _cvs_queue; - std::deque _log_queue; - - timestamp _oldest_timestamp; - std::unordered_map _stored_timestamps; - - database::mysql_stmt _acknowledgement_insupdate; - database::mysql_stmt _comment_insupdate; - database::mysql_stmt _custom_variable_delete; - database::mysql_stmt _custom_variable_status_insupdate; - database::mysql_stmt _downtime_insupdate; - database::mysql_stmt _event_handler_insupdate; - database::mysql_stmt _flapping_status_insupdate; - database::mysql_stmt _host_check_update; - database::mysql_stmt _host_dependency_insupdate; - database::mysql_stmt _host_group_insupdate; - database::mysql_stmt _host_group_member_delete; - database::mysql_stmt _host_group_member_insert; - database::mysql_stmt _host_insupdate; - database::mysql_stmt _host_parent_delete; - database::mysql_stmt _host_parent_insert; - database::mysql_stmt _host_status_update; - database::mysql_stmt _instance_insupdate; - database::mysql_stmt _instance_status_insupdate; - database::mysql_stmt _module_insert; - database::mysql_stmt _service_check_update; - database::mysql_stmt _service_dependency_insupdate; - database::mysql_stmt _service_group_insupdate; - database::mysql_stmt _service_group_member_delete; - database::mysql_stmt _service_group_member_insert; - database::mysql_stmt _service_insupdate; - database::mysql_stmt _service_status_update; - - database::mysql_stmt _index_data_insert; - database::mysql_stmt _index_data_update; - database::mysql_stmt _index_data_query; - database::mysql_stmt _metrics_insert; - - // bool _should_exit() const; - // void _callback(); - - void _update_hosts_and_services_of_unresponsive_instances(); - void _update_hosts_and_services_of_instance(uint32_t id, bool responsive); - void _update_timestamp(uint32_t instance_id); - bool _is_valid_poller(uint32_t instance_id); - void _check_deleted_index(asio::error_code ec); - - void _process_acknowledgement(const std::shared_ptr& d); - void _process_comment(const std::shared_ptr& d); - void _process_custom_variable(const std::shared_ptr& d); - void _process_custom_variable_status(const std::shared_ptr& d); - void _process_downtime(const std::shared_ptr& d); - void _process_event_handler(const std::shared_ptr& d); - void _process_flapping_status(const std::shared_ptr& d); - void _process_host_check(const std::shared_ptr& d); - void _process_host_dependency(const std::shared_ptr& d); - void _process_host_group(const std::shared_ptr& d); - void _process_host_group_member(const std::shared_ptr& d); - void _process_host(const std::shared_ptr& d); - void _process_host_parent(const std::shared_ptr& d); - void _process_host_status(const std::shared_ptr& d); - void _process_instance(const std::shared_ptr& d); - void _process_instance_status(const std::shared_ptr& d); - void _process_log(const std::shared_ptr& d); - void _process_module(const std::shared_ptr& d); - void _process_service_check(const std::shared_ptr& d); - void _process_service_dependency(const std::shared_ptr& d); - void _process_service_group(const std::shared_ptr& d); - void _process_service_group_member(const std::shared_ptr& d); - void _process_service(const std::shared_ptr& d); - void _process_service_status(const std::shared_ptr& d); - void _process_instance_configuration(const std::shared_ptr& d); - void _process_responsive_instance(const std::shared_ptr& d); - - void _unified_sql_process_service_status(const std::shared_ptr& d); - - void _load_deleted_instances(); - void _load_caches(); - void _clean_tables(uint32_t instance_id); - void _prepare_hg_insupdate_statement(); - void _prepare_sg_insupdate_statement(); - void _finish_action(int32_t conn, uint32_t action); - void _finish_actions(); - void _add_action(int32_t conn, actions action); - void _update_metrics(); - void _insert_perfdatas(); - void _update_customvariables(); - void _insert_logs(); - // void __exit(); - - public: - stream(database_config const& dbcfg, - uint32_t rrd_len, - uint32_t interval_length, - uint32_t loop_timeout, - uint32_t instance_timeout, - uint32_t rebuild_check_interval, - bool store_in_data_bin); - stream() = delete; - stream& operator=(const stream&) = delete; - stream(const stream&) = delete; - ~stream() noexcept; - - int32_t get_acks(stream_type c); - void update_metric_info_cache(uint64_t index_id, - uint32_t metric_id, - std::string const& metric_name, - short metric_type); - int32_t write(const std::shared_ptr& d) override; - int32_t flush() override; - bool read(std::shared_ptr& d, time_t deadline = -1) override; - int32_t stop() override; - void statistics(nlohmann::json& tree) const; -}; -} // namespace unified_sql -CCB_END() - -#endif /* !CCB_UNIFIED_SQL_STREAM_HH */ diff --git a/centreon-broker/unified_sql/src/connector.cc b/centreon-broker/unified_sql/src/connector.cc deleted file mode 100644 index cff1e5417a0..00000000000 --- a/centreon-broker/unified_sql/src/connector.cc +++ /dev/null @@ -1,66 +0,0 @@ -/* -** Copyright 2011-2015,2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#include "com/centreon/broker/unified_sql/connector.hh" - -#include "com/centreon/broker/unified_sql/stream.hh" - -using namespace com::centreon::broker; -using namespace com::centreon::broker::unified_sql; - -/** - * Default constructor. - */ -connector::connector() : io::endpoint(false) {} - -/** - * Set connection parameters. - * - * @param[in] rrd_len RRD unified_sql length. - * @param[in] interval_length Length of a time unit. - * @param[in] rebuild_check_interval How often the unified_sql endpoint - * must check for graph rebuild. - * @param[in] store_in_data_bin True to store performance data in - * the data_bin table. - */ -void connector::connect_to(const database_config& dbcfg, - uint32_t rrd_len, - uint32_t interval_length, - uint32_t loop_timeout, - uint32_t instance_timeout, - uint32_t rebuild_check_interval, - bool store_in_data_bin) { - _dbcfg = dbcfg; - _rrd_len = rrd_len; - _interval_length = interval_length; - _loop_timeout = loop_timeout; - _instance_timeout = instance_timeout; - _rebuild_check_interval = rebuild_check_interval; - _store_in_data_bin = store_in_data_bin; -} - -/** - * @brief Open a connection object to the database. - * - * @return Storage connection object. - */ -std::unique_ptr connector::open() { - return std::make_unique(_dbcfg, _rrd_len, _interval_length, - _loop_timeout, _instance_timeout, - _rebuild_check_interval, _store_in_data_bin); -} diff --git a/centreon-broker/unified_sql/src/factory.cc b/centreon-broker/unified_sql/src/factory.cc deleted file mode 100644 index 6a8d2387061..00000000000 --- a/centreon-broker/unified_sql/src/factory.cc +++ /dev/null @@ -1,180 +0,0 @@ -/* -** Copyright 2011-2015,2017 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#include "com/centreon/broker/unified_sql/factory.hh" - -#include -#include - -#include "com/centreon/broker/config/parser.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/unified_sql/connector.hh" -#include "com/centreon/exceptions/msg_fmt.hh" - -using namespace com::centreon::exceptions; -using namespace com::centreon::broker; -using namespace com::centreon::broker::unified_sql; - -/************************************** - * * - * Static Objects * - * * - **************************************/ - -/** - * Find a parameter in configuration. - * - * @param[in] cfg Configuration object. - * @param[in] key Property to get. - * - * @return Property value. - */ -static std::string const& find_param(config::endpoint const& cfg, - std::string const& key) { - std::map::const_iterator it{cfg.params.find(key)}; - if (cfg.params.end() == it) - throw msg_fmt( - "unified_sql: no '{}" - "' defined for endpoint '{}'", - key, cfg.name); - return it->second; -} - -/************************************** - * * - * Public Methods * - * * - **************************************/ - -/** - * Check if a configuration match the unified_sql layer. - * - * @param[in] cfg Endpoint configuration. - * - * @return true if the configuration matches the unified_sql layer. - */ -bool factory::has_endpoint(config::endpoint& cfg, io::extension* ext) { - if (ext) - *ext = io::extension("STORAGE", false, false); - bool is_unified_sql(!strncasecmp(cfg.type.c_str(), "unified_sql", 8)); - return is_unified_sql; -} - -/** - * Build a unified_sql endpoint from a configuration. - * - * @param[in] cfg Endpoint configuration. - * @param[out] is_acceptor Will be set to false. - * @param[in] cache Unused. - * - * @return Endpoint matching the given configuration. - */ -io::endpoint* factory::new_endpoint( - config::endpoint& cfg, - bool& is_acceptor, - std::shared_ptr cache) const { - (void)cache; - - // Find RRD length. - uint32_t rrd_length; - try { - rrd_length = static_cast(std::stoul(find_param(cfg, "length"))); - } catch (std::exception const& e) { - /* This default length represents 180 days. */ - rrd_length = 15552000; - log_v2::sql()->error( - "unified_sql: the length field should contain " - "a string containing a number. We use the " - "default value in replacement 15552000."); - } - - // Find interval length if set. - uint32_t interval_length{0}; - { - std::map::const_iterator it{ - cfg.params.find("interval")}; - if (it != cfg.params.end()) { - try { - interval_length = std::stoul(it->second); - } catch (std::exception const& e) { - interval_length = 60; - log_v2::sql()->error( - "unified_sql: the interval field should " - "contain a string containing a " - "number. We use the default value in " - "replacement 60."); - } - } - if (!interval_length) - interval_length = 60; - } - - // Find unified_sql DB parameters. - database_config dbcfg(cfg); - - // Rebuild check interval. - uint32_t rebuild_check_interval(0); - { - std::map::const_iterator it{ - cfg.params.find("rebuild_check_interval")}; - if (it != cfg.params.end()) { - try { - rebuild_check_interval = std::stoul(it->second); - } catch (std::exception const& e) { - rebuild_check_interval = 300; - log_v2::sql()->error( - "unified_sql: the rebuild_check_interval field should " - "contain a string containing a number. We use the default value " - "in " - "replacement 300."); - } - } else - rebuild_check_interval = 300; - } - - // Store or not in data_bin. - bool store_in_data_bin(true); - { - std::map::const_iterator it{ - cfg.params.find("store_in_data_bin")}; - if (it != cfg.params.end()) - store_in_data_bin = config::parser::parse_boolean(it->second); - } - - // Loop timeout - // By default, 30 seconds - int32_t loop_timeout = cfg.read_timeout; - if (loop_timeout < 0) - loop_timeout = 30; - - // Instance timeout - // By default, 5 minutes. - uint32_t instance_timeout = 5 * 60; - { - auto it = cfg.params.find("instance_timeout"); - if (it != cfg.params.end()) - instance_timeout = std::stoul(it->second); - } - - // Connector. - auto c = std::make_unique(); - c->connect_to(dbcfg, rrd_length, interval_length, loop_timeout, - instance_timeout, rebuild_check_interval, store_in_data_bin); - is_acceptor = false; - return c.release(); -} diff --git a/centreon-broker/unified_sql/src/main.cc b/centreon-broker/unified_sql/src/main.cc deleted file mode 100644 index 41e5ca4c73f..00000000000 --- a/centreon-broker/unified_sql/src/main.cc +++ /dev/null @@ -1,115 +0,0 @@ -/* -** Copyright 2011-2013 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#include "bbdo/events.hh" -#include "bbdo/storage/index_mapping.hh" -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/metric_mapping.hh" -#include "bbdo/storage/rebuild.hh" -#include "bbdo/storage/remove_graph.hh" -#include "bbdo/storage/status.hh" -#include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/unified_sql/factory.hh" -#include "com/centreon/broker/unified_sql/internal.hh" -#include "com/centreon/broker/unified_sql/stream.hh" -#include "com/centreon/exceptions/msg_fmt.hh" - -using namespace com::centreon::exceptions; -using namespace com::centreon::broker; - -// Load count. -static uint32_t instances(0); - -extern "C" { -/** - * Module version symbol. Used to check for version mismatch. - */ -const char* broker_module_version = CENTREON_BROKER_VERSION; - -/** - * @brief Return an array with modules needed for this one to work. - * - * @return An array of const char* - */ -const char* const* broker_module_parents() { - constexpr static const char* retval[]{"10-neb.so", nullptr}; - return retval; -} - -/** - * Module deinitialization routine. - */ -void broker_module_deinit() { - // Decrement instance number. - if (!--instances) { - // Deregister unified_sql layer. - // Remove events. - io::events::instance().unregister_category(io::storage); - io::protocols::instance().unreg("storage"); - } -} - -/** - * Module initialization routine. - * - * @param[in] arg Configuration object. - */ -void broker_module_init(void const* arg) { - (void)arg; - - // Increment instance number. - if (!instances++) { - // Storage module. - log_v2::sql()->info("unified_sql: module for Centreon Broker {}", - CENTREON_BROKER_VERSION); - - io::events& e(io::events::instance()); - - // Register events. - { - e.register_event(make_type(io::storage, storage::de_metric), "metric", - &storage::metric::operations, storage::metric::entries, - "rt_metrics"); - e.register_event(make_type(io::storage, storage::de_rebuild), "rebuild", - &storage::rebuild::operations, - storage::rebuild::entries); - e.register_event(make_type(io::storage, storage::de_remove_graph), - "remove_graph", &storage::remove_graph::operations, - storage::remove_graph::entries); - e.register_event(make_type(io::storage, storage::de_status), "status", - &storage::status::operations, storage::status::entries); - e.register_event(make_type(io::storage, storage::de_index_mapping), - "index_mapping", &storage::index_mapping::operations, - storage::index_mapping::entries); - e.register_event(make_type(io::storage, storage::de_metric_mapping), - "metric_mapping", &storage::metric_mapping::operations, - storage::metric_mapping::entries); - log_v2::bbdo()->info("registering protobuf pb_rebuild as {:x}:{:x}", - io::storage, storage::de_pb_rebuild); - e.register_event(storage_pb_rebuild, "pb_rebuild", - &unified_sql::pb_rebuild::operations); - } - - // Register unified_sql layer. - io::protocols::instance().reg( - "unified_sql", std::make_shared(), 1, 7); - } -} -} diff --git a/centreon-broker/unified_sql/src/rebuild.proto b/centreon-broker/unified_sql/src/rebuild.proto deleted file mode 100644 index 26bea825e80..00000000000 --- a/centreon-broker/unified_sql/src/rebuild.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; - -package com.centreon.broker; - -message Point { - int64 ctime = 1; - double value = 2; - int32 status = 3; -} - -message Metric { - int32 value_type = 1; - uint64 metric_id = 2; -} - -message Rebuild { - oneof type { - uint64 index_id = 1; - Metric metric = 2; - } - uint32 interval = 3; - uint32 length = 4; - repeated Point data = 5; -} diff --git a/centreon-broker/unified_sql/src/rebuilder.cc b/centreon-broker/unified_sql/src/rebuilder.cc deleted file mode 100644 index edb26e6ec4e..00000000000 --- a/centreon-broker/unified_sql/src/rebuilder.cc +++ /dev/null @@ -1,465 +0,0 @@ -/* -** Copyright 2012-2015,2017,2020-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#include "com/centreon/broker/unified_sql/rebuilder.hh" - -#include -#include -#include -#include -#include -#include - -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/rebuild.hh" -#include "bbdo/storage/status.hh" -#include "com/centreon/broker/database/mysql_error.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/multiplexing/publisher.hh" -#include "com/centreon/broker/unified_sql/internal.hh" -#include "com/centreon/broker/unified_sql/stream.hh" -#include "com/centreon/exceptions/msg_fmt.hh" - -#define USE_PROTOBUF - -using namespace com::centreon::exceptions; -using namespace com::centreon::broker; -using namespace com::centreon::broker::unified_sql; - -/** - * Constructor. - * - * @param[in] db_cfg Database configuration. - * @param[in] rebuild_check_interval How often the rebuild thread will - * check for rebuild. - * @param[in] rrd_length Length of RRD files. - * @param[in] interval_length Length in seconds of a time unit. - */ -rebuilder::rebuilder(const database_config& db_cfg, - stream* parent, - uint32_t rebuild_check_interval, - uint32_t rrd_length, - uint32_t interval_length) - : _timer{pool::io_context()}, - _should_exit{false}, - _db_cfg(db_cfg), - _interval_length(interval_length), - _rebuild_check_interval(rebuild_check_interval), - _rrd_len(rrd_length), - _parent(parent) { - _db_cfg.set_connections_count(1); - _db_cfg.set_queries_per_transaction(1); - _timer.expires_after(std::chrono::seconds(1)); - _timer.async_wait(std::bind(&rebuilder::_run, this, std::placeholders::_1)); -} - -/** - * Destructor. - */ -rebuilder::~rebuilder() { - _should_exit = true; - std::promise p; - std::future f(p.get_future()); - asio::post(_timer.get_executor(), [this, &p] { - _timer.cancel(); - p.set_value(true); - }); - f.get(); -} - -/** - * @brief This internal function is called by the asio::steady_timer _timer - * every _rebuild_check_interval seconds. It is the main procedure of the - * rebuilder. - * - * @param ec Contains errors if any. In that case, the timer is stopped. - * One particular error is asio::error_code::aborted which means the rebuilder - * is stopped. - */ -void rebuilder::_run(asio::error_code ec) { - if (ec) - log_v2::sql()->info("unified_sql: rebuilder timer error: {}", ec.message()); - else { - try { - // Open DB. - mysql ms(_db_cfg); - - // Fetch index to rebuild. - index_info info; - _next_index_to_rebuild(info, ms); - while (!_should_exit && info.index_id) { - // Get check interval of host/service. - uint64_t index_id; - uint32_t host_id; - uint32_t service_id; - uint32_t check_interval(0); - uint32_t rrd_len; - { - index_id = info.index_id; - host_id = info.host_id; - service_id = info.service_id; - rrd_len = info.rrd_retention; - - std::string query; - if (!info.service_id) - query = - fmt::format("SELECT check_interval FROM hosts WHERE host_id={}", - info.host_id); - else - query = fmt::format( - "SELECT check_interval FROM services WHERE host_id={} AND " - "service_id={}", - info.host_id, info.service_id); - std::promise promise; - ms.run_query_and_get_result(query, &promise); - database::mysql_result res(promise.get_future().get()); - if (ms.fetch_row(res)) - check_interval = res.value_as_f64(0) * _interval_length; - if (!check_interval) - check_interval = 5 * 60; - } - log_v2::sql()->info( - "unified_sql: rebuilder: index {} (interval {}) will be rebuild", - index_id, check_interval); - - // Set index as being rebuilt. - _set_index_rebuild(ms, index_id, 2); - - try { - // Fetch metrics to rebuild. - std::list metrics_to_rebuild; - { - std::string query{ - fmt::format("SELECT metric_id, metric_name, data_source_type " - "FROM metrics WHERE index_id={}", - index_id)}; - - std::promise promise; - ms.run_query_and_get_result(query, &promise); - try { - database::mysql_result res(promise.get_future().get()); - - while (!_should_exit && ms.fetch_row(res)) { - metric_info info; - info.metric_id = res.value_as_u32(0); - info.metric_name = res.value_as_str(1); - info.metric_type = res.value_as_str(2)[0] - '0'; - metrics_to_rebuild.push_back(info); - } - } catch (const std::exception& e) { - throw msg_fmt( - "unified_sql: rebuilder: could not fetch metrics of index {}" - ": {}", - index_id, e.what()); - } - } - - // Browse metrics to rebuild. - while (!_should_exit && !metrics_to_rebuild.empty()) { - metric_info& info(metrics_to_rebuild.front()); - _rebuild_metric(ms, info.metric_id, host_id, service_id, - info.metric_name, info.metric_type, check_interval, - rrd_len); - // We need to update the stream for metrics that could - // change of type. - _parent->update_metric_info_cache( - index_id, info.metric_id, info.metric_name, info.metric_type); - metrics_to_rebuild.pop_front(); - } - - // Rebuild status. - _rebuild_status(ms, index_id, check_interval, rrd_len); - } catch (...) { - // Set index as to-be-rebuilt. - _set_index_rebuild(ms, index_id, 1); - - // Rethrow exception. - throw; - } - - // Set index as rebuilt or to-be-rebuild - // if we were interrupted. - _set_index_rebuild( - ms, index_id, - (_should_exit ? static_cast(1) : static_cast(0))); - - // Get next index to rebuild. - _next_index_to_rebuild(info, ms); - } - } catch (const std::exception& e) { - log_v2::sql()->error( - "unified_sql: rebuilder: Unable to connect to the database: {}", - e.what()); - } catch (...) { - log_v2::sql()->error( - "unified_sql: rebuilder: Unable to connect to the database: unknown " - "error"); - } - if (!_should_exit) { - _timer.expires_after(std::chrono::seconds(_rebuild_check_interval)); - _timer.async_wait( - std::bind(&rebuilder::_run, this, std::placeholders::_1)); - } - } -} - -/** - * Get next index to rebuild. - * - * @param[out] info Information about the next index to rebuild. - * Zero'd if no index is waiting for rebuild. - * @param[in] db Database object. - */ -void rebuilder::_next_index_to_rebuild(index_info& info, mysql& ms) { - const std::string query( - "SELECT id,host_id,service_id,rrd_retention FROM" - " index_data WHERE must_be_rebuild='1' LIMIT 1"); - std::promise promise; - ms.run_query_and_get_result(query, &promise); - - try { - database::mysql_result res(promise.get_future().get()); - if (ms.fetch_row(res)) { - info.index_id = res.value_as_u64(0); - info.host_id = res.value_as_u32(1); - info.service_id = res.value_as_u32(2); - info.rrd_retention = res.value_as_u32(3); - if (!info.rrd_retention) - info.rrd_retention = _rrd_len; - } else - memset(&info, 0, sizeof(info)); - } catch (const std::exception& e) { - throw msg_fmt( - "unified_sql: rebuilder: could not fetch index to rebuild: {} ", - e.what()); - } -} - -/** - * Rebuild a metric. - * - * @param[in] db Database object. - * @param[in] metric_id Metric ID. - * @param[in] host_id Id of the host this metric belong to. - * @param[in] service_id Id of the service this metric belong to. - * @param[in] metric_name Metric name. - * @param[in] type Metric type. - * @param[in] interval Host/service check interval. - * @param[in] length Metric RRD length in seconds. - */ -void rebuilder::_rebuild_metric(mysql& ms, - uint32_t metric_id, - uint32_t host_id, - uint32_t service_id, - std::string const& metric_name, - int16_t metric_type, - uint32_t interval, - int64_t length) { - // Log. - log_v2::sql()->info( - "unified_sql: rebuilder: rebuilding metric {} (name {}, type {}, " - "interval " - "{})", - metric_id, metric_name, metric_type, interval); - -#ifdef USE_PROTOBUF - auto r = std::make_shared(); - r->obj.mutable_metric()->set_metric_id(metric_id); - r->obj.mutable_metric()->set_value_type(metric_type); -#else - // Send rebuild start event. - _send_rebuild_event(false, metric_id, false); -#endif - - time_t start{time(nullptr) - length}; - - try { - // Get data. - std::string query{ - fmt::format("SELECT ctime,value FROM data_bin WHERE id_metric={} AND " - "ctime>={} ORDER BY ctime ASC", - metric_id, start)}; - std::promise promise; - ms.run_query_and_get_result(query, &promise); - log_v2::sql()->debug( - "unified_sql(rebuilder): rebuild of metric {}: SQL query: \"{}\"", - metric_id, query); - - try { - database::mysql_result res(promise.get_future().get()); - while (!_should_exit && ms.fetch_row(res)) { -#ifndef USE_PROTOBUF - std::shared_ptr entry = - std::make_shared( - host_id, service_id, metric_name, res.value_as_u32(0), interval, - true, metric_id, length, res.value_as_f64(1), metric_type); - if (entry->value > FLT_MAX * 0.999) - entry->value = std::numeric_limits::infinity(); - else if (entry->value < -FLT_MAX * 0.999) - entry->value = -std::numeric_limits::infinity(); - log_v2::perfdata()->trace( - "unified_sql(rebuilder): Sending metric with host_id {}, " - "service_id " - "{}, metric_name {}, ctime {}, interval {}, is_for_rebuild {}, " - "metric_id {}, rrd_len {}, value {}, value_type{}", - host_id, service_id, metric_name, res.value_as_u32(0), interval, - true, metric_id, length, res.value_as_f64(1), metric_type); - - multiplexing::publisher().write(entry); -#else - Point* p = r->obj.add_data(); - p->set_ctime(res.value_as_u32(0)); - p->set_value(res.value_as_f64(1)); - if (p->value() > FLT_MAX * 0.999) - p->set_value(std::numeric_limits::infinity()); - else if (p->value() < -FLT_MAX * 0.999) - p->set_value(-std::numeric_limits::infinity()); - log_v2::perfdata()->trace( - "unified_sql(rebuilder): Sending metric with host_id {}, " - "service_id " - "{}, metric_name {}, ctime {}, interval {}, is_for_rebuild {}, " - "metric_id {}, rrd_len {}, value {}, value_type{}", - host_id, service_id, metric_name, p->ctime(), interval, true, - metric_id, length, p->value(), metric_type); -#endif - } -#ifdef USE_PROTOBUF - multiplexing::publisher().write(r); -#endif - - } catch (const std::exception& e) { - throw msg_fmt( - "unified_sql: rebuilder: cannot fetch data of metric {} : {}", - metric_id, e.what()); - } - } catch (...) { -#ifndef USE_PROTOBUF - // Send rebuild end event. - _send_rebuild_event(true, metric_id, false); -#endif - // Rethrow exception. - throw; - } -#ifndef USE_PROTOBUF - // Send rebuild end event. - _send_rebuild_event(true, metric_id, false); -#endif -} - -/** - * Rebuild a status. - * - * @param[in] db Database object. - * @param[in] index_id Index ID. - * @param[in] interval Host/service check interval. - */ -void rebuilder::_rebuild_status(mysql& ms, - uint64_t index_id, - uint32_t interval, - int64_t length) { - // Log. - log_v2::sql()->info( - "unified_sql: rebuilder: rebuilding status {} (interval {})", index_id, - interval); - -#ifdef USE_PROTOBUF - auto r = std::make_shared(); - r->obj.set_index_id(index_id); - r->obj.set_interval(interval); - r->obj.set_length(length); -#else - // Send rebuild start event. - _send_rebuild_event(false, index_id, true); -#endif - - time_t start{time(nullptr) - length}; - - try { - // Get data. - std::string query{ - fmt::format("SELECT d.ctime,d.status FROM metrics AS m JOIN data_bin " - "AS d ON m.metric_id=d.id_metric WHERE m.index_id={} AND " - "ctime>={} ORDER BY d.ctime ASC", - index_id, start)}; - std::promise promise; - ms.run_query_and_get_result(query, &promise); - try { - database::mysql_result res(promise.get_future().get()); - while (!_should_exit && ms.fetch_row(res)) { -#ifndef USE_PROTOBUF - std::shared_ptr entry( - std::make_shared(res.value_as_u32(0), index_id, - interval, true, _rrd_len, - res.value_as_i32(1))); - multiplexing::publisher().write(entry); -#else - Point* p = r->obj.add_data(); - p->set_ctime(res.value_as_u32(0)); - p->set_status(res.value_as_i32(1)); -#endif - } - } catch (const std::exception& e) { - throw msg_fmt( - "unified_sql: rebuilder: cannot fetch data of index {} : {}", - index_id, e.what()); - } - } catch (...) { -#ifndef USE_PROTOBUF - // Send rebuild end event. - _send_rebuild_event(true, index_id, true); - - // Rethrow exception. -#endif - throw; - } -#ifndef USE_PROTOBUF - // Send rebuild end event. - _send_rebuild_event(true, index_id, true); -#endif -} - -#ifndef USE_PROTOBUF -/** - * Send a rebuild event. - * - * @param[in] end false if rebuild is starting, true if it is ending. - * @param[in] id Index or metric ID. - * @param[in] is_index true for an index ID, false for a metric ID. - */ -void rebuilder::_send_rebuild_event(bool end, uint64_t id, bool is_index) { - std::shared_ptr rb = - std::make_shared(end, id, is_index); - multiplexing::publisher().write(rb); -} -#endif - -/** - * Set index rebuild flag. - * - * @param[in] db Database object. - * @param[in] index_id Index to update. - * @param[in] state Rebuild state (0, 1 or 2). - */ -void rebuilder::_set_index_rebuild(mysql& ms, - uint64_t index_id, - int16_t state) { - std::string query( - fmt::format("UPDATE index_data SET must_be_rebuild='{}' WHERE id={}", - state, index_id)); - ms.run_query(query, database::mysql_error::update_index_state, false); -} diff --git a/centreon-broker/unified_sql/src/stored_timestamp.cc b/centreon-broker/unified_sql/src/stored_timestamp.cc deleted file mode 100644 index 5b7765aa05e..00000000000 --- a/centreon-broker/unified_sql/src/stored_timestamp.cc +++ /dev/null @@ -1,114 +0,0 @@ -/* -** 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/unified_sql/stored_timestamp.hh" - -#include - -using namespace com::centreon::broker; -using namespace com::centreon::broker::unified_sql; - -/** - * Default constructor. Create a stored timestamp updated to now. - */ -stored_timestamp::stored_timestamp() noexcept - : _instance_id{0}, _ts(), _state{responsive} { - update_timestamp(); -} - -/** - * Stored timestamp constructor. - * - * @param id Id of the instance associated with this timestamp. - * @param s State of the instance associated with this timestamp. - */ -stored_timestamp::stored_timestamp(uint32_t id, state_type s) noexcept - : _instance_id{id}, _state{s} { - update_timestamp(); -} - -/** - * Default copy constructor. - * - * @param[in] right Te stored_timestamp to copy. - */ -stored_timestamp::stored_timestamp(stored_timestamp const& right) noexcept - : _instance_id{right._instance_id}, _ts{right._ts}, _state{right._state} {} - -/** - * Get the the id of the instance associated with this timestamp. - * - * @return The id of the instance associated with this timestamp. - */ -uint32_t stored_timestamp::get_id() const noexcept { - return _instance_id; -} - -/** - * Get the state of the instance associated with this timestamp. - * - * @return The state of the instance associated with this timestamp. - */ -stored_timestamp::state_type stored_timestamp::get_state() const noexcept { - return _state; -} - -/** - * Set the state of the instance associated with this timestamp. - * - * @param[in] state the new state. - */ -void stored_timestamp::set_state(state_type state) noexcept { - _state = state; -} - -/** - * Update the internal timestamp to now. - */ -void stored_timestamp::update_timestamp() noexcept { - _ts = timestamp(std::time(nullptr)); -} - -/** - * Get the internal timestamp. - * - * @return The timestamp. - */ -timestamp stored_timestamp::get_timestamp() const noexcept { - return _ts; -} - -/** - * Set the internal timestamp. - * - * @param[in] ts The timestamp to set. - */ -void stored_timestamp::set_timestamp(timestamp ts) noexcept { - _ts = ts; -} - -/** - * Check to see if the timestamp is outdated. - * - * @param[in] timeout The timeout, in seconds. - * - * @return true if the timestamp is outdated. - */ -bool stored_timestamp::timestamp_outdated(uint32_t timeout) const noexcept { - return std::difftime(std::time(nullptr), _ts) > timeout; -} diff --git a/centreon-broker/unified_sql/src/stream.cc b/centreon-broker/unified_sql/src/stream.cc deleted file mode 100644 index 6fea8235938..00000000000 --- a/centreon-broker/unified_sql/src/stream.cc +++ /dev/null @@ -1,545 +0,0 @@ -/* -** Copyright 2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ -#include "com/centreon/broker/unified_sql/stream.hh" - -#include -#include -#include - -#include "bbdo/storage/index_mapping.hh" -#include "com/centreon/broker/database/mysql_result.hh" -#include "com/centreon/broker/exceptions/shutdown.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/misc/perfdata.hh" -#include "com/centreon/broker/multiplexing/publisher.hh" -#include "com/centreon/broker/neb/events.hh" -#include "com/centreon/broker/stats/center.hh" -#include "com/centreon/exceptions/msg_fmt.hh" - -using namespace com::centreon::exceptions; -using namespace com::centreon::broker; -using namespace com::centreon::broker::database; -using namespace com::centreon::broker::unified_sql; - -const std::array stream::metric_type_name{ - "GAUGE", "COUNTER", "DERIVE", "ABSOLUTE", "AUTOMATIC"}; - -void (stream::*const stream::_neb_processing_table[])( - const std::shared_ptr&) = { - nullptr, - &stream::_process_acknowledgement, - &stream::_process_comment, - &stream::_process_custom_variable, - &stream::_process_custom_variable_status, - &stream::_process_downtime, - &stream::_process_event_handler, - &stream::_process_flapping_status, - &stream::_process_host_check, - &stream::_process_host_dependency, - &stream::_process_host_group, - &stream::_process_host_group_member, - &stream::_process_host, - &stream::_process_host_parent, - &stream::_process_host_status, - &stream::_process_instance, - &stream::_process_instance_status, - &stream::_process_log, - &stream::_process_module, - &stream::_process_service_check, - &stream::_process_service_dependency, - &stream::_process_service_group, - &stream::_process_service_group_member, - &stream::_process_service, - &stream::_process_service_status, - &stream::_process_instance_configuration, - &stream::_process_responsive_instance, -}; - -stream::stream(const database_config& dbcfg, - uint32_t rrd_len, - uint32_t interval_length, - uint32_t loop_timeout, - uint32_t instance_timeout, - uint32_t rebuild_check_interval, - bool store_in_data_bin) - : io::stream("unified_sql"), - _state{not_started}, - _processed{0}, - _ack{0}, - _pending_events{0}, - _count{0}, - _loop_timeout{loop_timeout}, - _max_pending_queries(dbcfg.get_queries_per_transaction()), - _mysql{dbcfg}, - _instance_timeout{instance_timeout}, - _rebuilder{dbcfg, this, rebuild_check_interval, - rrd_len ? rrd_len : 15552000, interval_length}, - _store_in_db{store_in_data_bin}, - _rrd_len{rrd_len}, - _interval_length{interval_length}, - _max_perfdata_queries{_max_pending_queries}, - _max_metrics_queries{_max_pending_queries}, - _max_cv_queries{_max_pending_queries}, - _max_log_queries{_max_pending_queries}, - _next_insert_perfdatas{std::time_t(nullptr) + 10}, - _next_update_metrics{std::time_t(nullptr) + 10}, - _next_loop_timeout{std::time_t(nullptr) + _loop_timeout}, - _timer{pool::io_context()}, - _stats{stats::center::instance().register_conflict_manager()}, - _oldest_timestamp{std::numeric_limits::max()} { - log_v2::sql()->debug("unified sql: stream class instanciation"); - stats::center::instance().execute([stats = _stats, - loop_timeout = _loop_timeout, - max_queries = _max_pending_queries] { - stats->set_loop_timeout(loop_timeout); - stats->set_max_pending_events(max_queries); - }); - _state = running; - _action.resize(_mysql.connections_count()); - - try { - _load_caches(); - } catch (const std::exception& e) { - log_v2::sql()->error("error while loading caches: {}", e.what()); - throw; - } - _timer.expires_after(std::chrono::minutes(5)); - _timer.async_wait( - std::bind(&stream::_check_deleted_index, this, std::placeholders::_1)); -} - -stream::~stream() noexcept { - log_v2::sql()->debug("unified sql: stream destruction"); -} - -void stream::_load_deleted_instances() { - _cache_deleted_instance_id.clear(); - std::string query{"SELECT instance_id FROM instances WHERE deleted=1"}; - std::promise promise; - _mysql.run_query_and_get_result(query, &promise); - try { - mysql_result res(promise.get_future().get()); - while (_mysql.fetch_row(res)) - _cache_deleted_instance_id.insert(res.value_as_u32(0)); - } catch (std::exception const& e) { - throw msg_fmt("could not get list of deleted instances: {}", e.what()); - } -} - -void stream::_load_caches() { - // Fill index cache. - - /* get deleted cache of instance ids => _cache_deleted_instance_id */ - _load_deleted_instances(); - - /* get all outdated instances from the database => _stored_timestamps */ - { - std::string query{"SELECT instance_id FROM instances WHERE outdated=TRUE"}; - std::promise promise; - _mysql.run_query_and_get_result(query, &promise); - try { - mysql_result res(promise.get_future().get()); - while (_mysql.fetch_row(res)) { - uint32_t instance_id = res.value_as_i32(0); - _stored_timestamps.insert( - {instance_id, - stored_timestamp(instance_id, stored_timestamp::unresponsive)}); - stored_timestamp& ts = _stored_timestamps[instance_id]; - ts.set_timestamp(timestamp(std::numeric_limits::max())); - } - } catch (std::exception const& e) { - throw msg_fmt( - "unified sql: could not get the list of outdated instances: {}", - e.what()); - } - } - - /* index_data => _index_cache */ - { - // Execute query. - std::promise promise; - _mysql.run_query_and_get_result( - "SELECT " - "id,host_id,service_id,host_name,rrd_retention,service_description," - "special,locked FROM index_data", - &promise); - try { - database::mysql_result res(promise.get_future().get()); - - // Loop through result set. - while (_mysql.fetch_row(res)) { - index_info info{.host_name = res.value_as_str(3), - .index_id = res.value_as_u64(0), - .locked = res.value_as_bool(7), - .rrd_retention = res.value_as_u32(4) - ? res.value_as_u32(4) - : _rrd_len, - .service_description = res.value_as_str(5), - .special = res.value_as_u32(6) == 2}; - uint32_t host_id(res.value_as_u32(1)); - uint32_t service_id(res.value_as_u32(2)); - log_v2::perfdata()->debug( - "unified_sql: loaded index {} of ({}, {}) with rrd_len={}", - info.index_id, host_id, service_id, info.rrd_retention); - _index_cache[{host_id, service_id}] = std::move(info); - - // Create the metric mapping. - auto im{std::make_shared(info.index_id, host_id, - service_id)}; - multiplexing::publisher pblshr; - pblshr.write(im); - } - } catch (std::exception const& e) { - throw msg_fmt("unified_sql: could not fetch index list from data DB: {}", - e.what()); - } - } - - /* hosts => _cache_host_instance */ - { - _cache_host_instance.clear(); - - std::promise promise; - _mysql.run_query_and_get_result("SELECT host_id,instance_id FROM hosts", - &promise); - - try { - mysql_result res(promise.get_future().get()); - while (_mysql.fetch_row(res)) - _cache_host_instance[res.value_as_u32(0)] = res.value_as_u32(1); - } catch (std::exception const& e) { - throw msg_fmt("SQL: could not get the list of host/instance pairs: {}", - e.what()); - } - } - - /* hostgroups => _hostgroup_cache */ - { - _hostgroup_cache.clear(); - - std::promise promise; - _mysql.run_query_and_get_result("SELECT hostgroup_id FROM hostgroups", - &promise); - - try { - mysql_result res(promise.get_future().get()); - while (_mysql.fetch_row(res)) - _hostgroup_cache.insert(res.value_as_u32(0)); - } catch (std::exception const& e) { - throw msg_fmt("SQL: could not get the list of hostgroups id: {}", - e.what()); - } - } - - /* servicegroups => _servicegroup_cache */ - { - _servicegroup_cache.clear(); - - std::promise promise; - _mysql.run_query_and_get_result("SELECT servicegroup_id FROM servicegroups", - &promise); - - try { - mysql_result res(promise.get_future().get()); - while (_mysql.fetch_row(res)) - _servicegroup_cache.insert(res.value_as_u32(0)); - } catch (std::exception const& e) { - throw msg_fmt("SQL: could not get the list of servicegroups id: {}", - e.what()); - } - } - - _cache_svc_cmd.clear(); - _cache_hst_cmd.clear(); - - /* metrics => _metric_cache */ - { - std::lock_guard lock(_metric_cache_m); - _metric_cache.clear(); - { - std::lock_guard lck(_queues_m); - _metrics.clear(); - } - - std::promise promise; - _mysql.run_query_and_get_result( - "SELECT " - "metric_id,index_id,metric_name,unit_name,warn,warn_low," - "warn_threshold_mode,crit,crit_low,crit_threshold_mode,min,max," - "current_value,data_source_type FROM metrics", - &promise); - - try { - mysql_result res{promise.get_future().get()}; - while (_mysql.fetch_row(res)) { - metric_info info; - info.metric_id = res.value_as_u32(0); - info.locked = false; - info.unit_name = res.value_as_str(3); - info.warn = res.value_as_f32(4); - info.warn_low = res.value_as_f32(5); - info.warn_mode = res.value_as_i32(6); - info.crit = res.value_as_f32(7); - info.crit_low = res.value_as_f32(8); - info.crit_mode = res.value_as_i32(9); - info.min = res.value_as_f32(10); - info.max = res.value_as_f32(11); - info.value = res.value_as_f32(12); - info.type = res.value_as_str(13)[0] - '0'; - info.metric_mapping_sent = false; - _metric_cache[{res.value_as_u64(1), res.value_as_str(2)}] = info; - } - } catch (std::exception const& e) { - throw msg_fmt("unified sql: could not get the list of metrics: {}", - e.what()); - } - } -} - -void stream::update_metric_info_cache(uint64_t index_id, - uint32_t metric_id, - std::string const& metric_name, - short metric_type) { - auto it = _metric_cache.find({index_id, metric_name}); - if (it != _metric_cache.end()) { - log_v2::perfdata()->info( - "unified sql: updating metric '{}' of id {} at index {} to " - "metric_type {}", - metric_name, metric_id, index_id, - metric_type_name[metric_type]); - std::lock_guard lock(_metric_cache_m); - it->second.type = metric_type; - if (it->second.metric_id != metric_id) { - it->second.metric_id = metric_id; - // We need to repopulate a new metric_mapping - it->second.metric_mapping_sent = false; - } - } -} - -/** - * Take a look if a given action is done on a mysql connection. If it is - * done, the method waits for tasks on this connection to be finished and - * clear the flag. - * In case of a conn < 0, the methods checks all the connections. - * - * @param conn The connection number or a negative number to check all the - * connections - * @param action An action. - */ -void stream::_finish_action(int32_t conn, uint32_t action) { - if (conn < 0) { - for (std::size_t i = 0; i < _action.size(); i++) { - if (_action[i] & action) { - _mysql.commit(i); - _action[i] = actions::none; - } - } - } else if (_action[conn] & action) { - _mysql.commit(conn); - _action[conn] = actions::none; - } -} - -/** - * The main goal of this method is to commit queries sent to the db. - * When the commit is done (all the connections commit), we count how - * many events can be acknowledged. So we can also update the number of pending - * events. - */ -void stream::_finish_actions() { - log_v2::sql()->trace("unified sql: finish actions"); - _mysql.commit(); - for (uint32_t& v : _action) - v = actions::none; - _ack += _processed; - _processed = 0; - log_v2::sql()->trace("finish actions processed = {}", _processed); -} - -/** - * Add an action on the connection conn in the list of current actions. - * If conn < 0, the action is added to all the connections. - * - * @param conn The connection number or a negative number to add to all the - * connections - * @param action An action. - */ -void stream::_add_action(int32_t conn, actions action) { - if (conn < 0) { - for (uint32_t& v : _action) - v |= action; - } else - _action[conn] |= action; -} - -/** - * @brief Returns statistics about the stream. Those statistics - * are stored directly in a json tree. - * - * @return A nlohmann::json with the statistics. - */ -void stream::statistics(nlohmann::json& tree) const { - size_t perfdata; - size_t sz_metrics; - size_t sz_logs; - size_t sz_cv; - size_t sz_cvs; - size_t count; - { - std::lock_guard lck(_queues_m); - perfdata = _perfdata_queue.size(); - sz_metrics = _metrics.size(); - sz_logs = _log_queue.size(); - sz_cv = _cv_queue.size(); - sz_cvs = _cvs_queue.size(); - count = _count; - } - - tree["cv events"] = static_cast(sz_cv); - tree["cvs events"] = static_cast(sz_cvs); - tree["logs events"] = static_cast(sz_logs); - tree["loop timeout"] = static_cast(_loop_timeout); - tree["max pending events"] = static_cast(_max_pending_queries); - tree["max perfdata events"] = static_cast(_max_perfdata_queries); - tree["metrics events"] = static_cast(sz_metrics); - tree["pending_events"] = static_cast(_pending_events); - tree["count"] = static_cast(count); - tree["perfdata events"] = static_cast(perfdata); - tree["processed_events"] = static_cast(_processed); -} - -int32_t stream::write(const std::shared_ptr& data) { - ++_pending_events; - assert(data); - - log_v2::sql()->trace("unified sql: write event category:{}, element:{}", - category_of_type(data->type()), - element_of_type(data->type())); - - uint32_t type = data->type(); - uint16_t cat = category_of_type(type); - uint16_t elem = element_of_type(type); - if (cat == io::neb) { - (this->*(_neb_processing_table[elem]))(data); - if (type == neb::service_status::static_type()) - _unified_sql_process_service_status(data); - } else { - log_v2::sql()->trace( - "unified sql: event of type {} thrown away ; no need to " - "store it in the database.", - type); - } - _processed++; - _count++; - - time_t now = std::time(nullptr); - if (now >= _next_loop_timeout || _count >= _max_pending_queries) { - _count = 0; - _next_loop_timeout = now + 10; - _finish_actions(); - } - - size_t sz_perfdatas; - size_t sz_metrics; - size_t sz_cv, sz_cvs; - size_t sz_logs; - { - std::lock_guard lck(_queues_m); - sz_perfdatas = _perfdata_queue.size(); - sz_metrics = _metrics.size(); - sz_cv = _cv_queue.size(); - sz_cvs = _cvs_queue.size(); - sz_logs = _log_queue.size(); - } - - if (now >= _next_insert_perfdatas || sz_perfdatas >= _max_perfdata_queries) { - _next_insert_perfdatas = now + 10; - asio::post(pool::instance().io_context(), - std::bind(&stream::_insert_perfdatas, this)); - } - - if (now >= _next_update_metrics || sz_metrics >= _max_metrics_queries) { - _next_update_metrics = now + 10; - asio::post(pool::instance().io_context(), - std::bind(&stream::_update_metrics, this)); - } - - if (now >= _next_update_cv || sz_cv >= _max_cv_queries || - sz_cvs >= _max_cv_queries) { - _next_update_cv = now + 10; - asio::post(pool::instance().io_context(), - std::bind(&stream::_update_customvariables, this)); - } - - if (now >= _next_insert_logs || sz_logs >= _max_log_queries) { - _next_insert_logs = now + 10; - asio::post(pool::instance().io_context(), - std::bind(&stream::_insert_logs, this)); - } - - int32_t retval = _ack; - _ack -= retval; - - _pending_events -= retval; - return retval; -} - -/** - * @brief Flush the stream. - * - * @return Number of acknowledged events. - */ -int32_t stream::flush() { - if (!_ack) - _finish_actions(); - int32_t retval = _ack; - _ack -= retval; - _pending_events -= retval; - return retval; -} - -/** - * @brief Read from the database. - * - * @param d cleared. - * @param deadline timeout. - * - * @return This method throws shutdown exception. - */ -bool stream::read(std::shared_ptr& d, time_t deadline) { - (void)deadline; - d.reset(); - throw broker::exceptions::shutdown("cannot read from a unified sql stream"); - return true; -} - -/** - * @brief The stop() internal function that stops the stream thread and - * returns last events to ack. - * - * @return the number of events to ack. - */ -int32_t stream::stop() { - flush(); - - /* Let's return how many events to ack */ - int32_t retval = _ack; - _ack -= retval; - return retval; -} diff --git a/centreon-broker/unified_sql/src/stream_sql.cc b/centreon-broker/unified_sql/src/stream_sql.cc deleted file mode 100644 index abde7642aac..00000000000 --- a/centreon-broker/unified_sql/src/stream_sql.cc +++ /dev/null @@ -1,1680 +0,0 @@ -/* -** Copyright 2019-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ -#include - -#include "com/centreon/broker/database/mysql_result.hh" -#include "com/centreon/broker/database/table_max_size.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/neb/events.hh" -#include "com/centreon/broker/query_preparator.hh" -#include "com/centreon/broker/unified_sql/stream.hh" -#include "com/centreon/engine/host.hh" -#include "com/centreon/engine/service.hh" - -using namespace com::centreon::broker; -using namespace com::centreon::broker::database; -using namespace com::centreon::broker::unified_sql; - -/** - * @brief Clean tables with data associated to the instance. - * - * Rather than delete appropriate entries in tables, they are instead - * deactivated using a specific flag. - * - * @param[in] instance_id Instance ID to remove. - */ -void stream::_clean_tables(uint32_t instance_id) { - /* Database version. */ - - int32_t conn = _mysql.choose_connection_by_instance(instance_id); - log_v2::sql()->debug( - "unified sql: disable hosts and services (instance_id: {})", instance_id); - /* Disable hosts and services. */ - std::string query(fmt::format( - "UPDATE hosts AS h LEFT JOIN services AS s ON h.host_id = s.host_id " - "SET h.enabled=0, s.enabled=0 WHERE h.instance_id={}", - instance_id)); - _mysql.run_query(query, database::mysql_error::clean_hosts_services, false, - conn); - _add_action(conn, actions::hosts); - - /* Remove host group memberships. */ - log_v2::sql()->debug( - "unified sql: remove host group memberships (instance_id: {})", - instance_id); - query = fmt::format( - "DELETE hosts_hostgroups FROM hosts_hostgroups LEFT JOIN hosts ON " - "hosts_hostgroups.host_id=hosts.host_id WHERE hosts.instance_id={}", - instance_id); - _mysql.run_query(query, database::mysql_error::clean_hostgroup_members, false, - conn); - _add_action(conn, actions::hostgroups); - - /* Remove service group memberships */ - log_v2::sql()->debug( - "unified sql: remove service group memberships (instance_id: {})", - instance_id); - query = fmt::format( - "DELETE services_servicegroups FROM services_servicegroups LEFT JOIN " - "hosts ON services_servicegroups.host_id=hosts.host_id WHERE " - "hosts.instance_id={}", - instance_id); - _mysql.run_query(query, database::mysql_error::clean_servicegroup_members, - false, conn); - _add_action(conn, actions::servicegroups); - - /* Remove host groups. */ - log_v2::sql()->debug( - "unified sql: remove empty host groups (instance_id: {})", instance_id); - _mysql.run_query( - "DELETE hg FROM hostgroups AS hg LEFT JOIN hosts_hostgroups AS hhg ON " - "hg.hostgroup_id=hhg.hostgroup_id WHERE hhg.hostgroup_id IS NULL", - database::mysql_error::clean_empty_hostgroups, false, conn); - _add_action(conn, actions::hostgroups); - - /* Remove service groups. */ - log_v2::sql()->debug( - "unified sql: remove empty service groups (instance_id: {})", - instance_id); - - _mysql.run_query( - "DELETE sg FROM servicegroups AS sg LEFT JOIN services_servicegroups as " - "ssg ON sg.servicegroup_id=ssg.servicegroup_id WHERE ssg.servicegroup_id " - "IS NULL", - database::mysql_error::clean_empty_servicegroups, false, conn); - _add_action(conn, actions::servicegroups); - - /* Remove host dependencies. */ - log_v2::sql()->debug( - "unified sql: remove host dependencies (instance_id: {})", instance_id); - query = fmt::format( - "DELETE hhd FROM hosts_hosts_dependencies AS hhd INNER JOIN hosts as " - "h ON hhd.host_id=h.host_id OR hhd.dependent_host_id=h.host_id WHERE " - "h.instance_id={}", - instance_id); - _mysql.run_query(query, database::mysql_error::clean_host_dependencies, false, - conn); - _add_action(conn, actions::host_dependencies); - - /* Remove host parents. */ - log_v2::sql()->debug("unified sql: remove host parents (instance_id: {})", - instance_id); - query = fmt::format( - "DELETE hhp FROM hosts_hosts_parents AS hhp INNER JOIN hosts as h ON " - "hhp.child_id=h.host_id OR hhp.parent_id=h.host_id WHERE " - "h.instance_id={}", - instance_id); - _mysql.run_query(query, database::mysql_error::clean_host_parents, false, - conn); - _add_action(conn, actions::host_parents); - - /* Remove service dependencies. */ - log_v2::sql()->debug( - "unified sql: remove service dependencies (instance_id: {})", - instance_id); - query = fmt::format( - "DELETE ssd FROM services_services_dependencies AS ssd" - " INNER JOIN services as s" - " ON ssd.service_id=s.service_id OR " - "ssd.dependent_service_id=s.service_id" - " INNER JOIN hosts as h" - " ON s.host_id=h.host_id" - " WHERE h.instance_id={}", - instance_id); - _mysql.run_query(query, database::mysql_error::clean_service_dependencies, - false, conn); - _add_action(conn, actions::service_dependencies); - - /* Remove list of modules. */ - log_v2::sql()->debug("SQL: remove list of modules (instance_id: {})", - instance_id); - query = fmt::format("DELETE FROM modules WHERE instance_id={}", instance_id); - _mysql.run_query(query, database::mysql_error::clean_modules, false, conn); - _add_action(conn, actions::modules); - - // Cancellation of downtimes. - log_v2::sql()->debug("SQL: Cancellation of downtimes (instance_id: {})", - instance_id); - query = fmt::format( - "UPDATE downtimes SET cancelled=1 WHERE actual_end_time IS NULL AND " - "cancelled=0 " - "AND instance_id={}", - instance_id); - - _mysql.run_query(query, database::mysql_error::clean_downtimes, false, conn); - _add_action(conn, actions::downtimes); - - // Remove comments. - log_v2::sql()->debug("unified sql: remove comments (instance_id: {})", - instance_id); - - query = fmt::format( - "UPDATE comments SET deletion_time={} WHERE instance_id={} AND " - "persistent=0 AND " - "(deletion_time IS NULL OR deletion_time=0)", - time(nullptr), instance_id); - - _mysql.run_query(query, database::mysql_error::clean_comments, false, conn); - _add_action(conn, actions::comments); - - // Remove custom variables. No need to choose the good instance, there are - // no constraint between custom variables and instances. - log_v2::sql()->debug("Removing custom variables (instance_id: {})", - instance_id); - query = fmt::format( - "DELETE cv FROM customvariables AS cv INNER JOIN hosts AS h ON " - "cv.host_id = h.host_id WHERE h.instance_id={}", - instance_id); - - _finish_action(conn, actions::custom_variables | actions::hosts); - _mysql.run_query(query, database::mysql_error::clean_customvariables, false, - conn); - _add_action(conn, actions::custom_variables); -} - -/** - * Update all the hosts and services of unresponsive instances. - */ -void stream::_update_hosts_and_services_of_unresponsive_instances() { - log_v2::sql()->debug("unified sql: checking for outdated instances"); - - /* Don't do anything if timeout is deactivated. */ - if (_instance_timeout == 0) - return; - - if (_stored_timestamps.size() == 0 || - std::difftime(std::time(nullptr), _oldest_timestamp) <= _instance_timeout) - return; - - /* Update unresponsive instances which were responsive */ - for (std::unordered_map::iterator - it = _stored_timestamps.begin(), - end = _stored_timestamps.end(); - it != end; ++it) { - if (it->second.get_state() == stored_timestamp::responsive && - it->second.timestamp_outdated(_instance_timeout)) { - it->second.set_state(stored_timestamp::unresponsive); - _update_hosts_and_services_of_instance(it->second.get_id(), false); - } - } - - // Update new oldest timestamp - _oldest_timestamp = timestamp(std::numeric_limits::max()); - for (std::unordered_map::iterator - it = _stored_timestamps.begin(), - end = _stored_timestamps.end(); - it != end; ++it) { - if (it->second.get_state() == stored_timestamp::responsive && - _oldest_timestamp > it->second.get_timestamp()) - _oldest_timestamp = it->second.get_timestamp(); - } -} - -/** - * Update the hosts and services of one instance. - * - * @param[in] id The instance id. - * @param[in] responsive True if the instance is responsive, false otherwise. - */ -void stream::_update_hosts_and_services_of_instance(uint32_t id, - bool responsive) { - int32_t conn = _mysql.choose_connection_by_instance(id); - _finish_action(conn, actions::hosts); - _finish_action(-1, actions::acknowledgements | actions::modules | - actions::downtimes | actions::comments); - - std::string query; - if (responsive) { - query = fmt::format( - "UPDATE instances SET outdated=FALSE WHERE instance_id={}", id); - _mysql.run_query(query, database::mysql_error::restore_instances, false, - conn); - _add_action(conn, actions::instances); - query = fmt::format( - "UPDATE hosts AS h LEFT JOIN services AS s ON h.host_id=s.host_id " - "SET h.state=h.real_state,s.state=s.real_state WHERE h.instance_id={}", - id); - _mysql.run_query(query, database::mysql_error::restore_instances, false, - conn); - _add_action(conn, actions::hosts); - } else { - query = fmt::format( - "UPDATE instances SET outdated=TRUE WHERE instance_id={}", id); - _mysql.run_query(query, database::mysql_error::restore_instances, false, - conn); - _add_action(conn, actions::instances); - query = fmt::format( - "UPDATE hosts AS h LEFT JOIN services AS s ON h.host_id=s.host_id " - "SET h.real_state=h.state,s.real_state=s.state,h.state={},s.state={} " - "WHERE h.instance_id={}", - com::centreon::engine::host::state_unreachable, - com::centreon::engine::service::state_unknown, id); - _mysql.run_query(query, database::mysql_error::restore_instances, false, - conn); - _add_action(conn, actions::hosts); - } - std::shared_ptr ri = - std::make_shared(); - ri->poller_id = id; - ri->responsive = responsive; - multiplexing::publisher().write(ri); -} - -/** - * Update the store of living instance timestamps. - * - * @param instance_id The id of the instance to have its timestamp updated. - */ -void stream::_update_timestamp(uint32_t instance_id) { - stored_timestamp::state_type s{stored_timestamp::responsive}; - - // Find the state of an existing timestamp if it exists. - std::unordered_map::iterator found = - _stored_timestamps.find(instance_id); - if (found != _stored_timestamps.end()) { - s = found->second.get_state(); - - // Update a suddenly alive instance - if (s == stored_timestamp::unresponsive) { - _update_hosts_and_services_of_instance(instance_id, true); - s = stored_timestamp::responsive; - } - } - - // Insert the timestamp and its state in the store. - stored_timestamp& timestamp = _stored_timestamps[instance_id]; - timestamp = stored_timestamp(instance_id, s); - if (_oldest_timestamp > timestamp.get_timestamp()) - _oldest_timestamp = timestamp.get_timestamp(); -} - -bool stream::_is_valid_poller(uint32_t instance_id) { - /* Check if the poller of id instance_id is deleted. */ - bool deleted = false; - if (_cache_deleted_instance_id.find(instance_id) != - _cache_deleted_instance_id.end()) { - log_v2::sql()->info( - "unified sql: discarding some event related to a deleted poller " - "({})", - instance_id); - deleted = true; - } else - /* Update poller timestamp. */ - _update_timestamp(instance_id); - - return !deleted; -} - -void stream::_prepare_hg_insupdate_statement() { - if (!_host_group_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("hostgroup_id"); - query_preparator qp(neb::host_group::static_type(), unique); - _host_group_insupdate = qp.prepare_insert_or_update(_mysql); - } -} - -void stream::_prepare_sg_insupdate_statement() { - if (!_service_group_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("servicegroup_id"); - query_preparator qp(neb::service_group::static_type(), unique); - _service_group_insupdate = qp.prepare_insert_or_update(_mysql); - } -} - -/** - * Process an acknowledgement event. - * - * @param[in] e Uncasted acknowledgement. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_acknowledgement(const std::shared_ptr& d) { - // Cast object. - neb::acknowledgement const& ack = - *static_cast(d.get()); - - // Log message. - log_v2::sql()->info( - "processing acknowledgement event (poller: {}, host: {}, service: {}, " - "entry time: {}, deletion time: {})", - ack.poller_id, ack.host_id, ack.service_id, ack.entry_time, - ack.deletion_time); - - // Processing. - if (_is_valid_poller(ack.poller_id)) { - // Prepare queries. - if (!_acknowledgement_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("entry_time"); - unique.insert("host_id"); - unique.insert("service_id"); - query_preparator qp(neb::acknowledgement::static_type(), unique); - _acknowledgement_insupdate = qp.prepare_insert_or_update(_mysql); - } - - int32_t conn = _mysql.choose_connection_by_instance(ack.poller_id); - // Process object. - _acknowledgement_insupdate << ack; - _mysql.run_statement(_acknowledgement_insupdate, - database::mysql_error::store_acknowledgement, true, - conn); - } -} - -/** - * Process a comment event. - * - * @param[in] e Uncasted comment. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_comment(const std::shared_ptr& d) { - _finish_action(-1, actions::hosts | actions::instances | - actions::host_parents | actions::host_dependencies | - actions::service_dependencies | actions::comments); - - // Cast object. - neb::comment const& cmmnt{*static_cast(d.get())}; - - int32_t conn = _mysql.choose_connection_by_instance(cmmnt.poller_id); - - // Log message. - log_v2::sql()->info("SQL: processing comment of poller {} on ({}, {})", - cmmnt.poller_id, cmmnt.host_id, cmmnt.service_id); - - // Prepare queries. - if (!_comment_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - unique.insert("service_id"); - unique.insert("entry_time"); - unique.insert("instance_id"); - unique.insert("internal_id"); - query_preparator qp(neb::comment::static_type(), unique); - _comment_insupdate = qp.prepare_insert_or_update(_mysql); - } - - // Processing. - _comment_insupdate << cmmnt; - _mysql.run_statement(_comment_insupdate, database::mysql_error::store_comment, - true, conn); - _add_action(conn, actions::comments); -} - -/** - * Process a custom variable event. - * - * @param[in] e Uncasted custom variable. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_custom_variable(const std::shared_ptr& d) { - // Cast object. - neb::custom_variable const& cv{ - *static_cast(d.get())}; - - // Prepare queries. - if (!_custom_variable_delete.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - unique.insert("name"); - unique.insert("service_id"); - query_preparator qp(neb::custom_variable::static_type(), unique); - _custom_variable_delete = qp.prepare_delete(_mysql); - } - - // Processing. - if (cv.enabled) { - std::lock_guard lck(_queues_m); - _cv_queue.emplace_back(fmt::format( - "('{}',{},{},'{}',{},{},{},'{}')", - misc::string::escape( - cv.name, get_customvariables_col_size(customvariables_name)), - cv.host_id, cv.service_id, - misc::string::escape( - cv.default_value, - get_customvariables_col_size(customvariables_default_value)), - cv.modified ? 1 : 0, cv.var_type, cv.update_time, - misc::string::escape( - cv.value, get_customvariables_col_size(customvariables_value)))); - /* Here, we do not update the custom variable boolean ack flag, because - * it will be updated later when the bulk query will be done: - * stream::_update_customvariables() */ - } else { - int conn = special_conn::custom_variable % _mysql.connections_count(); - _finish_action(-1, actions::custom_variables); - - log_v2::sql()->info("SQL: disabling custom variable '{}' of ({}, {})", - cv.name, cv.host_id, cv.service_id); - _custom_variable_delete.bind_value_as_i32(":host_id", cv.host_id); - _custom_variable_delete.bind_value_as_i32(":service_id", cv.service_id); - _custom_variable_delete.bind_value_as_str(":name", cv.name); - - _mysql.run_statement(_custom_variable_delete, - database::mysql_error::remove_customvariable, true, - conn); - _add_action(conn, actions::custom_variables); - } -} - -/** - * Process a custom variable status event. - * - * @param[in] e Uncasted custom variable status. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_custom_variable_status( - const std::shared_ptr& d) { - // Cast object. - neb::custom_variable_status const& cv{ - *static_cast(d.get())}; - - { - std::lock_guard lck(_queues_m); - _cvs_queue.emplace_back(fmt::format( - "('{}',{},{},{},{},'{}')", - misc::string::escape( - cv.name, get_customvariables_col_size(customvariables_name)), - cv.host_id, cv.service_id, cv.modified ? 1 : 0, cv.update_time, - misc::string::escape( - cv.value, get_customvariables_col_size(customvariables_value)))); - } - - log_v2::sql()->info("SQL: updating custom variable '{}' of ({}, {})", cv.name, - cv.host_id, cv.service_id); -} - -/** - * Process a downtime event. - * - * @param[in] e Uncasted downtime. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_downtime(const std::shared_ptr& d) { - int conn = special_conn::downtime % _mysql.connections_count(); - _finish_action(-1, actions::hosts | actions::instances | actions::downtimes | - actions::host_parents | actions::host_dependencies | - actions::service_dependencies); - - // Cast object. - neb::downtime const& dd = *static_cast(d.get()); - - // Log message. - log_v2::sql()->info( - "SQL: processing downtime event (poller: {}" - ", host: {}, service: {}, start time: {}, end_time: {}" - ", actual start time: {}" - ", actual end time: {}" - ", duration: {}, entry time: {}" - ", deletion time: {})", - dd.poller_id, dd.host_id, dd.service_id, dd.start_time, dd.end_time, - dd.actual_start_time, dd.actual_end_time, dd.duration, dd.entry_time, - dd.deletion_time); - - // Check if poller is valid. - if (_is_valid_poller(dd.poller_id)) { - // Prepare queries. - if (!_downtime_insupdate.prepared()) { - _downtime_insupdate = mysql_stmt( - "INSERT INTO downtimes (actual_end_time,actual_start_time,author," - "type,deletion_time,duration,end_time,entry_time," - "fixed,host_id,instance_id,internal_id,service_id," - "start_time,triggered_by,cancelled,started,comment_data) " - "VALUES(:actual_end_time,:actual_start_time,:author,:type," - ":deletion_time,:duration,:end_time,:entry_time,:fixed,:host_id," - ":instance_id,:internal_id,:service_id,:start_time," - ":triggered_by,:cancelled,:started,:comment_data) " - "ON DUPLICATE KEY UPDATE " - "actual_end_time=GREATEST(COALESCE(actual_end_time,-1)," - ":actual_end_time),actual_start_time=COALESCE(actual_start_time," - ":actual_start_time),author=:author,cancelled=:cancelled," - "comment_data=:comment_data,deletion_time=:deletion_time,duration=" - ":duration,end_time=:end_time,fixed=:fixed,host_id=:host_id," - "service_id=:service_id,start_time=:start_time,started=:started," - "triggered_by=:triggered_by, type=:type", - true); - _mysql.prepare_statement(_downtime_insupdate); - } - - // Process object. - _downtime_insupdate << dd; - _mysql.run_statement(_downtime_insupdate, - database::mysql_error::store_downtime, true, conn); - _add_action(conn, actions::downtimes); - } -} - -/** - * Process an event handler event. - * - * @param[in] e Uncasted event handler. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_event_handler(const std::shared_ptr& d) { - // Cast object. - neb::event_handler const& eh = - *static_cast(d.get()); - - // Log message. - log_v2::sql()->info( - "SQL: processing event handler event (host: {}" - ", service: {}, start time {})", - eh.host_id, eh.service_id, eh.start_time); - - // Prepare queries. - if (!_event_handler_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - unique.insert("service_id"); - unique.insert("start_time"); - query_preparator qp(neb::event_handler::static_type(), unique); - _event_handler_insupdate = qp.prepare_insert_or_update(_mysql); - } - - // Processing. - _event_handler_insupdate << eh; - _mysql.run_statement( - _event_handler_insupdate, database::mysql_error::store_eventhandler, true, - _mysql.choose_connection_by_instance(_cache_host_instance[eh.host_id])); -} - -/** - * Process a flapping status event. - * - * @param[in] e Uncasted flapping status. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_flapping_status(const std::shared_ptr& d) { - // Cast object. - neb::flapping_status const& fs( - *static_cast(d.get())); - - // Log message. - log_v2::sql()->info( - "SQL: processing flapping status event (host: {}, service: {}, entry " - "time: {})", - fs.host_id, fs.service_id, fs.event_time); - - // Prepare queries. - if (!_flapping_status_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - unique.insert("service_id"); - unique.insert("event_time"); - query_preparator qp(neb::flapping_status::static_type(), unique); - _flapping_status_insupdate = qp.prepare_insert_or_update(_mysql); - } - - // Processing. - _flapping_status_insupdate << fs; - int32_t conn = - _mysql.choose_connection_by_instance(_cache_host_instance[fs.host_id]); - _mysql.run_statement(_flapping_status_insupdate, - database::mysql_error::store_flapping, true, conn); - _add_action(conn, actions::hosts); -} - -/** - * Process an host check event. - * - * @param[in] e Uncasted host check. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_host_check(const std::shared_ptr& d) { - _finish_action(-1, actions::instances | actions::downtimes | - actions::comments | actions::host_dependencies | - actions::host_parents | actions::service_dependencies); - - // Cast object. - neb::host_check const& hc = *static_cast(d.get()); - - time_t now = time(nullptr); - if (hc.check_type || // - passive result - !hc.active_checks_enabled || // - active checks are disabled, - // status might not be updated - hc.next_check >= now - 5 * 60 || // - normal case - !hc.next_check) { // - initial state - // Apply to DB. - log_v2::sql()->info( - "SQL: processing host check event (host: {}, command: {}", hc.host_id, - hc.command_line); - - // Prepare queries. - if (!_host_check_update.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - query_preparator qp(neb::host_check::static_type(), unique); - _host_check_update = qp.prepare_update(_mysql); - } - - // Processing. - bool store; - size_t str_hash = std::hash{}(hc.command_line); - // Did the command changed since last time? - if (_cache_hst_cmd[hc.host_id] != str_hash) { - store = true; - _cache_hst_cmd[hc.host_id] = str_hash; - } else - store = false; - - if (store) { - int32_t conn = _mysql.choose_connection_by_instance( - _cache_host_instance[hc.host_id]); - - _host_check_update << hc; - std::promise promise; - _mysql.run_statement(_host_check_update, - database::mysql_error::store_host_check, true, conn); - _add_action(conn, actions::hosts); - } - } else - // Do nothing. - log_v2::sql()->info( - "SQL: not processing host check event (host: {}, command: {}, check " - "type: {}, next check: {}, now: {})", - hc.host_id, hc.command_line, hc.check_type, hc.next_check, now); -} - -/** - * Process a host dependency event. - * - * @param[in] e Uncasted host dependency. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_host_dependency(const std::shared_ptr& d) { - int32_t conn = special_conn::host_dependency % _mysql.connections_count(); - _finish_action(-1, actions::hosts | actions::host_parents | - actions::comments | actions::downtimes | - actions::host_dependencies | - actions::service_dependencies); - - // Cast object. - neb::host_dependency const& hd = - *static_cast(d.get()); - - // Insert/Update. - if (hd.enabled) { - log_v2::sql()->info("SQL: enabling host dependency of {} on {}", - hd.dependent_host_id, hd.host_id); - - // Prepare queries. - if (!_host_dependency_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - unique.insert("dependent_host_id"); - query_preparator qp(neb::host_dependency::static_type(), unique); - _host_dependency_insupdate = qp.prepare_insert_or_update(_mysql); - } - - // Process object. - _host_dependency_insupdate << hd; - _mysql.run_statement(_host_dependency_insupdate, - database::mysql_error::store_host_dependency, true, - conn); - _add_action(conn, actions::host_dependencies); - } - // Delete. - else { - log_v2::sql()->info("SQL: removing host dependency of {} on {}", - hd.dependent_host_id, hd.host_id); - std::string query(fmt::format( - "DELETE FROM hosts_hosts_dependencies WHERE dependent_host_id={}" - " AND host_id={}", - hd.dependent_host_id, hd.host_id)); - _mysql.run_query(query, database::mysql_error::empty, true, conn); - _add_action(conn, actions::host_dependencies); - } -} - -/** - * Process a host group event. - * - * @param[in] e Uncasted host group. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_host_group(const std::shared_ptr& d) { - int32_t conn = special_conn::host_group % _mysql.connections_count(); - _finish_action(-1, actions::hosts); - - // Cast object. - neb::host_group const& hg{*static_cast(d.get())}; - - if (hg.enabled) { - log_v2::sql()->info("SQL: enabling host group {} ('{}' on instance {})", - hg.id, hg.name, hg.poller_id); - _prepare_hg_insupdate_statement(); - - _host_group_insupdate << hg; - _mysql.run_statement(_host_group_insupdate, - database::mysql_error::store_host_group, true, conn); - _add_action(conn, actions::hostgroups); - _hostgroup_cache.insert(hg.id); - } - // Delete group. - else { - log_v2::sql()->info("SQL: disabling host group {} ('{}' on instance {})", - hg.id, hg.name, hg.poller_id); - - // Delete group members. - { - std::string query(fmt::format( - "DELETE hosts_hostgroups FROM hosts_hostgroups LEFT JOIN hosts" - " ON hosts_hostgroups.host_id=hosts.host_id" - " WHERE hosts_hostgroups.hostgroup_id={} AND hosts.instance_id={}", - hg.id, hg.poller_id)); - _mysql.run_query(query, database::mysql_error::empty, false, conn); - _hostgroup_cache.erase(hg.id); - } - } -} - -/** - * Process a host group member event. - * - * @param[in] e Uncasted host group member. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_host_group_member(const std::shared_ptr& d) { - int32_t conn = special_conn::host_group % _mysql.connections_count(); - _finish_action(-1, actions::hostgroups | actions::hosts); - - // Cast object. - neb::host_group_member const& hgm( - *static_cast(d.get())); - - if (hgm.enabled) { - // Log message. - log_v2::sql()->info( - "SQL: enabling membership of host {} to host group {} on instance {}", - hgm.host_id, hgm.group_id, hgm.poller_id); - - // We only need to try to insert in this table as the - // host_id/hostgroup_id should be UNIQUE. - if (!_host_group_member_insert.prepared()) { - query_preparator::event_unique unique; - unique.insert("hostgroup_id"); - unique.insert("host_id"); - query_preparator qp(neb::host_group_member::static_type(), unique); - _host_group_member_insert = qp.prepare_insert(_mysql); - } - - /* If the group does not exist, we create it. */ - if (_cache_host_instance[hgm.host_id]) { - if (_hostgroup_cache.find(hgm.group_id) == _hostgroup_cache.end()) { - log_v2::sql()->error( - "SQL: host group {} does not exist - insertion before insertion of " - "members", - hgm.group_id); - _prepare_hg_insupdate_statement(); - - neb::host_group hg; - hg.id = hgm.group_id; - hg.name = hgm.group_name; - hg.enabled = true; - hg.poller_id = _cache_host_instance[hgm.host_id]; - - _host_group_insupdate << hg; - _mysql.run_statement(_host_group_insupdate, - database::mysql_error::store_host_group, false, - conn); - _add_action(conn, actions::hostgroups); - } - - _host_group_member_insert << hgm; - _mysql.run_statement(_host_group_member_insert, - database::mysql_error::store_host_group_member, - false, conn); - _add_action(conn, actions::hostgroups); - } else - log_v2::sql()->error( - "SQL: host with host_id = {} does not exist - unable to store " - "unexisting host in a hostgroup. You should restart centengine.", - hgm.host_id); - } - // Delete. - else { - // Log message. - log_v2::sql()->info( - "SQL: disabling membership of host {} to host group {} on instance {}", - hgm.host_id, hgm.group_id, hgm.poller_id); - - if (!_host_group_member_delete.prepared()) { - query_preparator::event_unique unique; - unique.insert("hostgroup_id"); - unique.insert("host_id"); - query_preparator qp(neb::host_group_member::static_type(), unique); - _host_group_member_delete = qp.prepare_delete(_mysql); - } - _host_group_member_delete << hgm; - _mysql.run_statement(_host_group_member_delete, - database::mysql_error::delete_host_group_member, true, - conn); - _add_action(conn, actions::hostgroups); - } -} - -/** - * Process an host event. - * - * @param[in] e Uncasted host. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_host(const std::shared_ptr& d) { - _finish_action(-1, actions::instances | actions::hostgroups | - actions::host_dependencies | actions::host_parents | - actions::custom_variables | actions::downtimes | - actions::comments | actions::service_dependencies); - neb::host& h = *static_cast(d.get()); - - // Log message. - log_v2::sql()->debug( - "SQL: processing host event (poller: {}, host: {}, name: {})", - h.poller_id, h.host_id, h.host_name); - - // Processing - if (_is_valid_poller(h.poller_id)) { - // FixMe BAM Generate fake host, this host - // does not contains a display_name - // We should not store them in db - if (h.host_id && !h.alias.empty()) { - int32_t conn = _mysql.choose_connection_by_instance(h.poller_id); - - // Prepare queries. - if (!_host_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - query_preparator qp(neb::host::static_type(), unique); - _host_insupdate = qp.prepare_insert_or_update(_mysql); - } - - // Process object. - _host_insupdate << h; - _mysql.run_statement(_host_insupdate, database::mysql_error::store_host, - true, conn); - _add_action(conn, actions::hosts); - - // Fill the cache... - if (h.enabled) - _cache_host_instance[h.host_id] = h.poller_id; - else - _cache_host_instance.erase(h.host_id); - } else - log_v2::sql()->trace( - "SQL: host '{}' of poller {} has no ID nor alias, probably bam " - "fake host", - h.host_name, h.poller_id); - } -} - -/** - * Process a host parent event. - * - * @param[in] e Uncasted host parent. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_host_parent(const std::shared_ptr& d) { - int32_t conn = special_conn::host_parent % _mysql.connections_count(); - _finish_action(-1, actions::hosts | actions::host_dependencies | - actions::comments | actions::downtimes); - - neb::host_parent const& hp(*static_cast(d.get())); - - // Enable parenting. - if (hp.enabled) { - // Log message. - log_v2::sql()->info("SQL: host {} is parent of host {}", hp.parent_id, - hp.host_id); - - // Prepare queries. - if (!_host_parent_insert.prepared()) { - query_preparator qp(neb::host_parent::static_type()); - _host_parent_insert = qp.prepare_insert(_mysql, true); - } - - // Insert. - _host_parent_insert << hp; - _mysql.run_statement(_host_parent_insert, - database::mysql_error::store_host_parentship, false, - conn); - _add_action(conn, actions::host_parents); - } - // Disable parenting. - else { - log_v2::sql()->info("SQL: host {} is not parent of host {} anymore", - hp.parent_id, hp.host_id); - - // Prepare queries. - if (!_host_parent_delete.prepared()) { - query_preparator::event_unique unique; - unique.insert("child_id"); - unique.insert("parent_id"); - query_preparator qp(neb::host_parent::static_type(), unique); - _host_parent_delete = qp.prepare_delete(_mysql); - } - - // Delete. - _host_parent_delete << hp; - _mysql.run_statement(_host_parent_delete, database::mysql_error::empty, - false, conn); - _add_action(conn, actions::host_parents); - } -} - -/** - * Process a host status event. - * - * @param[in] e Uncasted host status. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_host_status(const std::shared_ptr& d) { - _finish_action(-1, actions::instances | actions::downtimes | - actions::comments | actions::custom_variables | - actions::hostgroups | actions::host_dependencies | - actions::host_parents); - - // Processed object. - neb::host_status const& hs(*static_cast(d.get())); - - time_t now = time(nullptr); - if (hs.check_type || // - passive result - !hs.active_checks_enabled || // - active checks are disabled, - // status might not be updated - hs.next_check >= now - 5 * 60 || // - normal case - !hs.next_check) { // - initial state - // Apply to DB. - log_v2::sql()->info( - "processing host status event (host: {}, last check: {}, state ({}, " - "{}))", - hs.host_id, hs.last_check, hs.current_state, hs.state_type); - - // Prepare queries. - if (!_host_status_update.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - query_preparator qp(neb::host_status::static_type(), unique); - _host_status_update = qp.prepare_update(_mysql); - } - - // Processing. - _host_status_update << hs; - int32_t conn = - _mysql.choose_connection_by_instance(_cache_host_instance[hs.host_id]); - _mysql.run_statement(_host_status_update, - database::mysql_error::store_host_status, true, conn); - _add_action(conn, actions::hosts); - } else - // Do nothing. - log_v2::sql()->info( - "SQL: not processing host status event (id: {}, check type: {}, last " - "check: {}, next check: {}, now: {}, state: ({}, {}))", - hs.host_id, hs.check_type, hs.last_check, hs.next_check, now, - hs.current_state, hs.state_type); -} - -/** - * Process an instance event. The thread executing the command is controlled - * so that queries depending on this one will be made by the same thread. - * - * @param[in] e Uncasted instance. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_instance(const std::shared_ptr& d) { - neb::instance& i(*static_cast(d.get())); - int32_t conn = _mysql.choose_connection_by_instance(i.poller_id); - _finish_action(-1, actions::hosts | actions::acknowledgements | - actions::modules | actions::downtimes | - actions::comments | actions::servicegroups | - actions::hostgroups | actions::service_dependencies | - actions::host_dependencies); - - // Log message. - log_v2::sql()->info( - "SQL: processing poller event (id: {}, name: {}, running: {})", - i.poller_id, i.name, i.is_running ? "yes" : "no"); - - // Clean tables. - _clean_tables(i.poller_id); - - // Processing. - if (_is_valid_poller(i.poller_id)) { - // Prepare queries. - if (!_instance_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("instance_id"); - query_preparator qp(neb::instance::static_type(), unique); - _instance_insupdate = qp.prepare_insert_or_update(_mysql); - } - - // Process object. - _instance_insupdate << i; - _mysql.run_statement(_instance_insupdate, - database::mysql_error::store_poller, true, conn); - _add_action(conn, actions::instances); - } -} - -/** - * Process an instance status event. To work on an instance status, we must - * be sure the instance already exists in the database. So this query must - * be done by the same thread as the one that created the instance. - * - * @param[in] e Uncasted instance status. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_instance_status(const std::shared_ptr& d) { - neb::instance_status& is = *static_cast(d.get()); - int32_t conn = _mysql.choose_connection_by_instance(is.poller_id); - - _finish_action(-1, actions::hosts | actions::acknowledgements | - actions::modules | actions::downtimes | - actions::comments); - - // Log message. - log_v2::sql()->info( - "SQL: processing poller status event (id: {}, last alive: {})", - is.poller_id, is.last_alive); - - // Processing. - if (_is_valid_poller(is.poller_id)) { - // Prepare queries. - if (!_instance_status_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("instance_id"); - query_preparator qp(neb::instance_status::static_type(), unique); - _instance_status_insupdate = qp.prepare_insert_or_update(_mysql); - } - - // Process object. - _instance_status_insupdate << is; - _mysql.run_statement(_instance_status_insupdate, - database::mysql_error::update_poller, true, conn); - _add_action(conn, actions::instances); - } -} - -/** - * Process a log event. - * - * @param[in] e Uncasted log. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_log(const std::shared_ptr& d) { - // Fetch proper structure. - neb::log_entry const& le(*static_cast(d.get())); - - // Log message. - log_v2::sql()->info( - "SQL: processing log of poller '{}' generated at {} (type {})", - le.poller_name, le.c_time, le.msg_type); - - std::lock_guard lck(_queues_m); - // Run query. - _log_queue.emplace_back(fmt::format( - "({},{},{},'{}','{}',{},{},'{}','{}',{},'{}',{},'{}')", le.c_time, - le.host_id, le.service_id, - misc::string::escape(le.host_name, get_logs_col_size(logs_host_name)), - misc::string::escape(le.poller_name, - get_logs_col_size(logs_instance_name)), - le.log_type, le.msg_type, - misc::string::escape(le.notification_cmd, - get_logs_col_size(logs_notification_cmd)), - misc::string::escape(le.notification_contact, - get_logs_col_size(logs_notification_contact)), - le.retry, - misc::string::escape(le.service_description, - get_logs_col_size(logs_service_description)), - le.status, - misc::string::escape(le.output, get_logs_col_size(logs_output)))); -} - -/** - * Process a module event. We must take care of the thread id sending the - * query because the modules table has a constraint on instances.instance_id - * - * @param[in] e Uncasted module. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_module(const std::shared_ptr& d) { - // Cast object. - neb::module const& m = *static_cast(d.get()); - int32_t conn = _mysql.choose_connection_by_instance(m.poller_id); - - // Log message. - log_v2::sql()->info( - "SQL: processing module event (poller: {}, filename: {}, loaded: {})", - m.poller_id, m.filename, m.loaded ? "yes" : "no"); - - // Processing. - if (_is_valid_poller(m.poller_id)) { - // Prepare queries. - if (!_module_insert.prepared()) { - query_preparator qp(neb::module::static_type()); - _module_insert = qp.prepare_insert(_mysql); - } - - // Process object. - if (m.enabled) { - _module_insert << m; - _mysql.run_statement(_module_insert, database::mysql_error::store_module, - true, conn); - _add_action(conn, actions::modules); - } else { - const std::string* ptr_filename; - if (m.filename.size() > get_modules_col_size(modules_filename)) { - std::string trunc_filename = m.filename; - misc::string::truncate(trunc_filename, - get_modules_col_size(modules_filename)); - ptr_filename = &trunc_filename; - } else - ptr_filename = &m.filename; - - std::string query(fmt::format( - "DELETE FROM modules WHERE instance_id={} AND filename='{}'", - m.poller_id, *ptr_filename)); - _mysql.run_query(query, database::mysql_error::empty, false, conn); - _add_action(conn, actions::modules); - } - } -} - -/** - * Process a service check event. - * - * @param[in] e Uncasted service check. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_service_check(const std::shared_ptr& d) { - _finish_action(-1, actions::downtimes | actions::comments | - actions::host_dependencies | actions::host_parents | - actions::service_dependencies); - - // Cast object. - neb::service_check const& sc( - *static_cast(d.get())); - - time_t now{time(nullptr)}; - if (sc.check_type // - passive result - || !sc.active_checks_enabled // - active checks are disabled, - // status might not be updated - // - normal case - || (sc.next_check >= now - 5 * 60) || - !sc.next_check) { // - initial state - // Apply to DB. - log_v2::sql()->info( - "SQL: processing service check event (host: {}, service: {}, command: " - "{})", - sc.host_id, sc.service_id, sc.command_line); - - // Prepare queries. - if (!_service_check_update.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - unique.insert("service_id"); - query_preparator qp(neb::service_check::static_type(), unique); - _service_check_update = qp.prepare_update(_mysql); - } - - // Processing. - bool store = true; - size_t str_hash = std::hash{}(sc.command_line); - // Did the command changed since last time? - if (_cache_svc_cmd[{sc.host_id, sc.service_id}] != str_hash) - _cache_svc_cmd[std::make_pair(sc.host_id, sc.service_id)] = str_hash; - else - store = false; - - if (store) { - if (_cache_host_instance[sc.host_id]) { - _service_check_update << sc; - std::promise promise; - int32_t conn = _mysql.choose_connection_by_instance( - _cache_host_instance[sc.host_id]); - _mysql.run_statement(_service_check_update, - database::mysql_error::store_service_check_command, - false, conn); - } else - log_v2::sql()->error( - "SQL: host with host_id = {} does not exist - unable to store " - "service command check of that host. You should restart centengine", - sc.host_id); - } - } else - // Do nothing. - log_v2::sql()->info( - "SQL: not processing service check event (host: {}, service: {}, " - "command: {}, check_type: {}, next_check: {}, now: {})", - sc.host_id, sc.service_id, sc.command_line, sc.check_type, - sc.next_check, now); -} - -/** - * Process a service dependency event. - * - * @param[in] e Uncasted service dependency. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_service_dependency(const std::shared_ptr& d) { - int32_t conn = special_conn::service_dependency % _mysql.connections_count(); - _finish_action(-1, actions::hosts | actions::host_parents | - actions::downtimes | actions::comments | - actions::host_dependencies | - actions::service_dependencies); - - // Cast object. - neb::service_dependency const& sd( - *static_cast(d.get())); - - // Insert/Update. - if (sd.enabled) { - log_v2::sql()->info( - "SQL: enabling service dependency of ({}, {}) on ({}, {})", - sd.dependent_host_id, sd.dependent_service_id, sd.host_id, - sd.service_id); - - // Prepare queries. - if (!_service_dependency_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("dependent_host_id"); - unique.insert("dependent_service_id"); - unique.insert("host_id"); - unique.insert("service_id"); - query_preparator qp(neb::service_dependency::static_type(), unique); - _service_dependency_insupdate = qp.prepare_insert_or_update(_mysql); - } - - // Process object. - _service_dependency_insupdate << sd; - _mysql.run_statement(_service_dependency_insupdate, - database::mysql_error::store_service_dependency, true, - conn); - _add_action(conn, actions::service_dependencies); - } - // Delete. - else { - log_v2::sql()->info( - "SQL: removing service dependency of ({}, {}) on ({}, {})", - sd.dependent_host_id, sd.dependent_service_id, sd.host_id, - sd.service_id); - std::string query(fmt::format( - "DELETE FROM serivces_services_dependencies WHERE dependent_host_id={} " - "AND dependent_service_id={} AND host_id={} AND service_id={}", - sd.dependent_host_id, sd.dependent_service_id, sd.host_id, - sd.service_id)); - _mysql.run_query(query, database::mysql_error::empty, false, conn); - _add_action(conn, actions::service_dependencies); - } -} - -/** - * Process a service group event. - * - * @param[in] e Uncasted service group. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_service_group(const std::shared_ptr& d) { - int32_t conn = special_conn::service_group % _mysql.connections_count(); - _finish_action(-1, actions::hosts | actions::services); - - // Cast object. - neb::service_group const& sg( - *static_cast(d.get())); - - // Insert/update group. - if (sg.enabled) { - log_v2::sql()->info("SQL: enabling service group {} ('{}' on instance {})", - sg.id, sg.name, sg.poller_id); - _prepare_sg_insupdate_statement(); - - _service_group_insupdate << sg; - _mysql.run_statement(_service_group_insupdate, - database::mysql_error::store_service_group, true, - conn); - _add_action(conn, actions::servicegroups); - _servicegroup_cache.insert(sg.id); - } - // Delete group. - else { - log_v2::sql()->info("SQL: disabling service group {} ('{}' on instance {})", - sg.id, sg.name, sg.poller_id); - - // Delete group members. - { - std::string query(fmt::format( - "DELETE services_servicegroups FROM services_servicegroups LEFT " - "JOIN hosts ON services_servicegroups.host_id=hosts.host_id WHERE " - "services_servicegroups.servicegroup_id={} AND " - "hosts.instance_id={}", - sg.id, sg.poller_id)); - _mysql.run_query(query, database::mysql_error::empty, false, conn); - _add_action(conn, actions::servicegroups); - _servicegroup_cache.erase(sg.id); - } - } -} - -/** - * Process a service group member event. - * - * @param[in] e Uncasted service group member. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_service_group_member(const std::shared_ptr& d) { - int32_t conn = special_conn::service_group % _mysql.connections_count(); - _finish_action(-1, - actions::hosts | actions::servicegroups | actions::services); - - // Cast object. - neb::service_group_member const& sgm( - *static_cast(d.get())); - - if (sgm.enabled) { - // Log message. - log_v2::sql()->info( - "SQL: enabling membership of service ({}, {}) to service group {} on " - "instance {}", - sgm.host_id, sgm.service_id, sgm.group_id, sgm.poller_id); - - // We only need to try to insert in this table as the - // host_id/service_id/servicegroup_id combo should be UNIQUE. - if (!_service_group_member_insert.prepared()) { - query_preparator::event_unique unique; - unique.insert("servicegroup_id"); - unique.insert("host_id"); - unique.insert("service_id"); - query_preparator qp(neb::service_group_member::static_type(), unique); - _service_group_member_insert = qp.prepare_insert(_mysql); - } - - /* If the group does not exist, we create it. */ - if (_servicegroup_cache.find(sgm.group_id) == _servicegroup_cache.end()) { - log_v2::sql()->error( - "SQL: service group {} does not exist - insertion before insertion " - "of members", - sgm.group_id); - _prepare_sg_insupdate_statement(); - - neb::service_group sg; - sg.id = sgm.group_id; - sg.name = sgm.group_name; - sg.enabled = true; - sg.poller_id = sgm.poller_id; - - _service_group_insupdate << sg; - _mysql.run_statement(_service_group_insupdate, - database::mysql_error::store_service_group, false, - conn); - _add_action(conn, actions::servicegroups); - } - - _service_group_member_insert << sgm; - _mysql.run_statement(_service_group_member_insert, - database::mysql_error::store_service_group_member, - false, conn); - _add_action(conn, actions::servicegroups); - } - // Delete. - else { - // Log message. - log_v2::sql()->info( - "SQL: disabling membership of service ({}, {}) to service group {} on " - "instance {}", - sgm.host_id, sgm.service_id, sgm.group_id, sgm.poller_id); - - if (!_service_group_member_delete.prepared()) { - query_preparator::event_unique unique; - unique.insert("servicegroup_id"); - unique.insert("host_id"); - unique.insert("service_id"); - query_preparator qp(neb::service_group_member::static_type(), unique); - _service_group_member_delete = qp.prepare_delete(_mysql); - } - _service_group_member_delete << sgm; - _mysql.run_statement(_service_group_member_delete, - database::mysql_error::delete_service_group_member, - false, conn); - _add_action(conn, actions::servicegroups); - } -} - -/** - * Process a service event. - * - * @param[in] e Uncasted service. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_service(const std::shared_ptr& d) { - _finish_action(-1, actions::host_parents | actions::comments | - actions::downtimes | actions::host_dependencies | - actions::service_dependencies); - - // Processed object. - const neb::service& s(*static_cast(d.get())); - if (_cache_host_instance[s.host_id]) { - int32_t conn = - _mysql.choose_connection_by_instance(_cache_host_instance[s.host_id]); - - // Log message. - log_v2::sql()->info( - "SQL: processing service event (host: {}, service: {}, " - "description: {})", - s.host_id, s.service_id, s.service_description); - - if (s.host_id && s.service_id) { - // Prepare queries. - if (!_service_insupdate.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - unique.insert("service_id"); - query_preparator qp(neb::service::static_type(), unique); - _service_insupdate = qp.prepare_insert_or_update(_mysql); - } - - _service_insupdate << s; - _mysql.run_statement(_service_insupdate, - database::mysql_error::store_service, true, conn); - _add_action(conn, actions::services); - } else - log_v2::sql()->trace( - "SQL: service '{}' has no host ID, service ID nor hostname, probably " - "bam fake service", - s.service_description); - } else - log_v2::sql()->error( - "SQL: host with host_id = {} does not exist - unable to store service " - "of that host. You should restart centengine", - s.host_id); -} - -/** - * Process a service status event. - * - * @param[in] e Uncasted service status. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_service_status(const std::shared_ptr& d) { - _finish_action(-1, actions::host_parents | actions::comments | - actions::downtimes | actions::host_dependencies | - actions::service_dependencies); - // Processed object. - neb::service_status const& ss{ - *static_cast(d.get())}; - - log_v2::perfdata()->info("SQL: service status output: <<{}>>", ss.output); - log_v2::perfdata()->info("SQL: service status perfdata: <<{}>>", - ss.perf_data); - - time_t now = time(nullptr); - if (ss.check_type || // - passive result - !ss.active_checks_enabled // - active checks are disabled, - // status might not be updated - || // - normal case - ss.next_check >= now - 5 * 60 || !ss.next_check) { // - initial state - // Apply to DB. - log_v2::sql()->info( - "SQL: processing service status event (host: {}, service: {}, last " - "check: {}, state ({}, {}))", - ss.host_id, ss.service_id, ss.last_check, ss.current_state, - ss.state_type); - - // Prepare queries. - if (!_service_status_update.prepared()) { - query_preparator::event_unique unique; - unique.insert("host_id"); - unique.insert("service_id"); - query_preparator qp(neb::service_status::static_type(), unique); - _service_status_update = qp.prepare_update(_mysql); - } - - // Processing. - _service_status_update << ss; - int32_t conn = - _mysql.choose_connection_by_instance(_cache_host_instance[ss.host_id]); - _mysql.run_statement(_service_status_update, - database::mysql_error::store_service_status, false, - conn); - _add_action(conn, actions::hosts); - } else - // Do nothing. - log_v2::sql()->info( - "SQL: not processing service status event (host: {}, service: {}, " - "check type: {}, last check: {}, next check: {}, now: {}, state ({}, " - "{}))", - ss.host_id, ss.service_id, ss.check_type, ss.last_check, ss.next_check, - now, ss.current_state, ss.state_type); -} - -/** - * Process an instance configuration event. - * - * @param[in] e Uncasted instance configuration. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_instance_configuration(const std::shared_ptr& d - __attribute__((unused))) {} - -/** - * Process a responsive instance event. - * - * @return The number of events that can be acknowledged. - */ -void stream::_process_responsive_instance(const std::shared_ptr& d - __attribute__((unused))) {} - -/** - * @brief Send a big query to update/insert a bulk of custom variables. When - * the query is done, we set the corresponding boolean of each pair to true - * to ack each event. - * - * When we exit the function, the custom variables queue is empty. - */ -void stream::_update_customvariables() { - std::deque cv_queue; - std::deque cvs_queue; - { - std::lock_guard lck(_queues_m); - std::swap(cv_queue, _cv_queue); - std::swap(cvs_queue, _cvs_queue); - } - int32_t conn = special_conn::custom_variable % _mysql.connections_count(); - _finish_action(conn, actions::custom_variables); - if (!cv_queue.empty()) { - /* Building of the query */ - std::string query{fmt::format( - "INSERT INTO customvariables " - "(name,host_id,service_id,default_value,modified,type,update_time," - "value) VALUES {} " - " ON DUPLICATE KEY UPDATE " - "default_value=VALUES(default_VALUE),modified=VALUES(modified),type=" - "VALUES(type),update_time=VALUES(update_time),value=VALUES(value)", - fmt::join(cv_queue, ","))}; - _mysql.run_query(query, database::mysql_error::update_customvariables, true, - conn); - _add_action(conn, actions::custom_variables); - log_v2::sql()->debug("{} new custom variables inserted", cv_queue.size()); - log_v2::sql()->trace("sending query << {} >>", query); - } - if (!cvs_queue.empty()) { - /* Building of the query */ - std::string query{fmt::format( - "INSERT INTO customvariables " - "(name,host_id,service_id,modified,update_time,value) VALUES {} " - " ON DUPLICATE KEY UPDATE " - "modified=VALUES(modified),update_time=VALUES(update_time),value=" - "VALUES(value)", - fmt::join(cvs_queue, ","))}; - _mysql.run_query(query, database::mysql_error::update_customvariables, true, - conn); - _add_action(conn, actions::custom_variables); - log_v2::sql()->debug("{} new custom variable status inserted", - cvs_queue.size()); - log_v2::sql()->trace("sending query << {} >>", query); - } -} - -/** - * @brief Send a big query to insert a bulk of logs. When the query is done, - * we set the corresponding boolean of each pair to true to ack each event. - * - * When we exit the function, the logs queue is empty. - */ -void stream::_insert_logs() { - std::deque log_queue; - { - std::lock_guard lck(_queues_m); - if (_log_queue.empty()) - return; - std::swap(_log_queue, log_queue); - } - int32_t conn = special_conn::log % _mysql.connections_count(); - /* Building of the query */ - std::string query{fmt::format( - "INSERT INTO logs " - "(ctime,host_id,service_id,host_name,instance_name,type,msg_type," - "notification_cmd,notification_contact,retry,service_description," - "status,output) VALUES {}", - fmt::join(log_queue, ","))}; - - _mysql.run_query(query, database::mysql_error::update_logs, true, conn); - log_v2::sql()->debug("{} new logs inserted", log_queue.size()); - log_v2::sql()->trace("sending query << {} >>", query); -} diff --git a/centreon-broker/unified_sql/src/stream_storage.cc b/centreon-broker/unified_sql/src/stream_storage.cc deleted file mode 100644 index 104171810a7..00000000000 --- a/centreon-broker/unified_sql/src/stream_storage.cc +++ /dev/null @@ -1,654 +0,0 @@ -/* -** Copyright 2019-2021 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#include - -#include -#include -#include -#include - -#include "bbdo/storage/index_mapping.hh" -#include "bbdo/storage/metric.hh" -#include "bbdo/storage/metric_mapping.hh" -#include "bbdo/storage/remove_graph.hh" -#include "bbdo/storage/status.hh" -#include "com/centreon/broker/database/table_max_size.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/perfdata.hh" -#include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/neb/events.hh" -#include "com/centreon/broker/unified_sql/stream.hh" -#include "com/centreon/exceptions/msg_fmt.hh" - -using namespace com::centreon::exceptions; -using namespace com::centreon::broker; -using namespace com::centreon::broker::unified_sql; - -#define BAM_NAME "_Module_" - -/** - * Check that the floating point values are the same number or are NaN or are - * INFINITY at the same time. The idea is to check if a is changed into b, did - * it really change? - * - * @param[in] a Floating point value. - * @param[in] b Floating point value. - * - * @return true if they are equal, false otherwise. - */ -static inline bool check_equality(double a, double b) { - static const double eps = 0.000001; - if (a == b) - return true; - if (std::isnan(a) && std::isnan(b)) - return true; - if (fabs(a - b) < eps) - return true; - return false; -} -/** - * Process a service status event. - * - * @param[in] e Uncasted service status. - * - * @return the number of events sent to the database. - */ -void stream::_unified_sql_process_service_status( - const std::shared_ptr& d) { - neb::service_status const& ss{*static_cast(d.get())}; - uint64_t host_id = ss.host_id, service_id = ss.service_id; - - log_v2::perfdata()->debug( - "unified sql::_unified_sql_process_service_status(): host_id:{}, " - "service_id:{}", - host_id, service_id); - auto it_index_cache = _index_cache.find({host_id, service_id}); - uint64_t index_id; - uint32_t rrd_len; - int32_t conn = - _mysql.choose_connection_by_instance(_cache_host_instance[ss.host_id]); - bool index_locked{false}; - bool special{!strncmp(ss.host_name.c_str(), BAM_NAME, sizeof(BAM_NAME) - 1)}; - - auto add_metric_in_cache = - [this](uint64_t index_id, uint64_t host_id, uint64_t service_id, - neb::service_status const& ss, bool index_locked, bool special, - uint32_t& rrd_len) -> void { - if (index_id == 0) { - throw msg_fmt( - "unified_sql: could not fetch index_id of newly inserted index ({}" - ", {})", - host_id, service_id); - } - - /* Insert index in cache. */ - log_v2::perfdata()->info( - "unified sql: add_metric_in_cache: index {}, for host_id {} and " - "service_id {}", - index_id, host_id, service_id); - index_info info{.host_name = ss.host_name, - .index_id = index_id, - .locked = index_locked, - .rrd_retention = _rrd_len, - .service_description = ss.service_description, - .special = special}; - - _index_cache[{host_id, service_id}] = std::move(info); - rrd_len = _rrd_len; - log_v2::perfdata()->debug( - "add metric in cache: (host: {}, service: {}, index: {}, returned " - "rrd_len {}", - ss.host_name, ss.service_description, index_id, rrd_len); - - /* Create the metric mapping. */ - auto im{std::make_shared(index_id, host_id, - service_id)}; - multiplexing::publisher pblshr; - pblshr.write(im); - }; - - /* Index does not exist */ - if (it_index_cache == _index_cache.end()) { - _finish_action(-1, actions::index_data); - log_v2::perfdata()->debug( - "unified sql::_unified_sql_process_service_status(): host_id:{}, " - "service_id:{} - index not found in cache", - host_id, service_id); - - if (!_index_data_insert.prepared()) - _index_data_insert = _mysql.prepare_query( - "INSERT INTO index_data " - "(host_id,host_name,service_id,service_description,must_be_rebuild," - "special) VALUES (?,?,?,?,?,?)"); - - fmt::string_view hv(misc::string::truncate( - ss.host_name, get_index_data_col_size(index_data_host_name))); - fmt::string_view sv(misc::string::truncate( - ss.service_description, - get_index_data_col_size(index_data_service_description))); - _index_data_insert.bind_value_as_i32(0, host_id); - _index_data_insert.bind_value_as_str(1, hv); - _index_data_insert.bind_value_as_i32(2, service_id); - _index_data_insert.bind_value_as_str(3, sv); - _index_data_insert.bind_value_as_str(4, "0"); - _index_data_insert.bind_value_as_str(5, special ? "1" : "0"); - std::promise promise; - _mysql.run_statement_and_get_int( - _index_data_insert, &promise, database::mysql_task::LAST_INSERT_ID, - conn); - try { - index_id = promise.get_future().get(); - add_metric_in_cache(index_id, host_id, service_id, ss, index_locked, - special, rrd_len); - } catch (std::exception const& e) { - try { - if (!_index_data_query.prepared()) - _index_data_query = _mysql.prepare_query( - "SELECT id from index_data WHERE host_id=? AND service_id=?"); - - _index_data_query.bind_value_as_i32(0, host_id); - _index_data_query.bind_value_as_i32(1, service_id); - { - std::promise promise; - log_v2::sql()->debug( - "Query for index_data for host_id={} and service_id={}", host_id, - service_id); - _mysql.run_statement_and_get_result(_index_data_query, &promise, - conn); - - database::mysql_result res(promise.get_future().get()); - if (_mysql.fetch_row(res)) - index_id = res.value_as_u64(0); - else - index_id = 0; - } - - if (index_id == 0) - throw msg_fmt( - "unified_sql: could not fetch index_id of newly inserted index " - "({}, " - "{})", - host_id, service_id); - - if (!_index_data_update.prepared()) - _index_data_update = _mysql.prepare_query( - "UPDATE index_data " - "SET host_name=?, service_description=?, must_be_rebuild=?, " - "special=? " - "WHERE id=?"); - - log_v2::sql()->debug( - "Updating index_data for host_id={} and service_id={}", host_id, - service_id); - _index_data_update.bind_value_as_str(0, hv); - _index_data_update.bind_value_as_str(1, sv); - _index_data_update.bind_value_as_str(2, "0"); - _index_data_update.bind_value_as_str(3, special ? "1" : "0"); - _index_data_update.bind_value_as_u64(4, index_id); - { - std::promise promise; - _mysql.run_statement_and_get_result(_index_data_update, &promise, - conn); - promise.get_future().get(); - } - - add_metric_in_cache(index_id, host_id, service_id, ss, index_locked, - special, rrd_len); - log_v2::sql()->debug( - "Index {} stored in cache for host_id={} and service_id={}", - index_id, host_id, service_id); - } catch (std::exception const& e) { - throw msg_fmt( - "unified_sql: insertion of index ( {}, {}" - ") failed: {}", - host_id, service_id, e.what()); - } - } - } else { - index_id = it_index_cache->second.index_id; - rrd_len = it_index_cache->second.rrd_retention; - index_locked = it_index_cache->second.locked; - log_v2::perfdata()->debug( - "unified sql: host_id:{}, service_id:{} - index already in cache " - "- index_id {}, rrd_len {}", - host_id, service_id, index_id, rrd_len); - } - - if (index_id) { - /* Generate status event */ - log_v2::perfdata()->debug( - "unified sql: host_id:{}, service_id:{} - generating status event " - "with index_id {}, rrd_len: {}", - host_id, service_id, index_id, rrd_len); - if (ss.has_been_checked) { - auto status(std::make_shared( - ss.last_check, index_id, - static_cast(ss.check_interval * _interval_length), false, - rrd_len, ss.last_hard_state)); - multiplexing::publisher().write(status); - } - - if (!ss.perf_data.empty()) { - /* Statements preparations */ - if (!_metrics_insert.prepared()) { - _metrics_insert = _mysql.prepare_query( - "INSERT INTO metrics " - "(index_id,metric_name,unit_name,warn,warn_low," - "warn_threshold_mode,crit," - "crit_low,crit_threshold_mode,min,max,current_value," - "data_source_type) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); - } - - /* Parse perfdata. */ - _finish_action(-1, actions::metrics); - std::list pds{misc::parse_perfdata( - ss.host_id, ss.service_id, ss.perf_data.c_str())}; - - std::list> to_publish; - for (auto& pd : pds) { - auto it_index_cache = _metric_cache.find({index_id, pd.name()}); - - /* The cache does not contain this metric */ - uint32_t metric_id; - bool need_metric_mapping = true; - if (it_index_cache == _metric_cache.end()) { - log_v2::perfdata()->debug( - "unified sql: no metrics corresponding to index {} and " - "perfdata '{}' found in cache", - index_id, pd.name()); - /* Let's insert it */ - _metrics_insert.bind_value_as_u64(0, index_id); - _metrics_insert.bind_value_as_str(1, pd.name()); - _metrics_insert.bind_value_as_str(2, pd.unit()); - _metrics_insert.bind_value_as_f32(3, pd.warning()); - _metrics_insert.bind_value_as_f32(4, pd.warning_low()); - _metrics_insert.bind_value_as_tiny(5, pd.warning_mode()); - _metrics_insert.bind_value_as_f32(6, pd.critical()); - _metrics_insert.bind_value_as_f32(7, pd.critical_low()); - _metrics_insert.bind_value_as_tiny(8, pd.critical_mode()); - _metrics_insert.bind_value_as_f32(9, pd.min()); - _metrics_insert.bind_value_as_f32(10, pd.max()); - _metrics_insert.bind_value_as_f32(11, pd.value()); - - uint32_t type = pd.value_type(); - char t[2]; - t[0] = '0' + type; - t[1] = 0; - _metrics_insert.bind_value_as_str(12, t); - - // Execute query. - std::promise promise; - _mysql.run_statement_and_get_int( - _metrics_insert, &promise, database::mysql_task::LAST_INSERT_ID, - conn); - try { - metric_id = promise.get_future().get(); - - // Insert metric in cache. - log_v2::perfdata()->info( - "unified sql: new metric {} for index {} and perfdata " - "'{}'", - metric_id, index_id, pd.name()); - metric_info info{.locked = false, - .metric_id = metric_id, - .type = type, - .value = pd.value(), - .unit_name = pd.unit(), - .warn = pd.warning(), - .warn_low = pd.warning_low(), - .warn_mode = pd.warning_mode(), - .crit = pd.critical(), - .crit_low = pd.critical_low(), - .crit_mode = pd.critical_mode(), - .min = pd.min(), - .max = pd.max(), - .metric_mapping_sent = - true}; // It will be done after this block - - std::lock_guard lock(_metric_cache_m); - _metric_cache[{index_id, pd.name()}] = info; - } catch (std::exception const& e) { - log_v2::perfdata()->error( - "unified sql: failed to create metric {} with type {}, " - "value {}, unit_name {}, warn {}, warn_low {}, warn_mode {}, " - "crit {}, crit_low {}, crit_mode {}, min {} and max {}", - metric_id, type, pd.value(), pd.unit(), pd.warning(), - pd.warning_low(), pd.warning_mode(), pd.critical(), - pd.critical_low(), pd.critical_mode(), pd.min(), pd.max()); - throw msg_fmt( - "unified_sql: insertion of metric '{}" - "' of index {} failed: {}", - pd.name(), index_id, e.what()); - } - } else { - std::lock_guard lock(_metric_cache_m); - /* We have the metric in the cache */ - metric_id = it_index_cache->second.metric_id; - if (!it_index_cache->second.metric_mapping_sent) - it_index_cache->second.metric_mapping_sent = true; - else - need_metric_mapping = false; - - pd.value_type(static_cast( - it_index_cache->second.type)); - - log_v2::perfdata()->debug( - "unified sql: metric {} concerning index {}, perfdata " - "'{}' found in cache", - it_index_cache->second.metric_id, index_id, pd.name()); - // Should we update metrics ? - if (!check_equality(it_index_cache->second.value, pd.value()) || - it_index_cache->second.unit_name != pd.unit() || - !check_equality(it_index_cache->second.warn, pd.warning()) || - !check_equality(it_index_cache->second.warn_low, - pd.warning_low()) || - it_index_cache->second.warn_mode != pd.warning_mode() || - !check_equality(it_index_cache->second.crit, pd.critical()) || - !check_equality(it_index_cache->second.crit_low, - pd.critical_low()) || - it_index_cache->second.crit_mode != pd.critical_mode() || - !check_equality(it_index_cache->second.min, pd.min()) || - !check_equality(it_index_cache->second.max, pd.max())) { - log_v2::perfdata()->info( - "unified sql: updating metric {} of index {}, perfdata " - "'{}' with unit: {}, warning: {}:{}, critical: {}:{}, min: " - "{}, max: {}", - it_index_cache->second.metric_id, index_id, pd.name(), - pd.unit(), pd.warning_low(), pd.warning(), pd.critical_low(), - pd.critical(), pd.min(), pd.max()); - // Update metrics table. - it_index_cache->second.unit_name = pd.unit(); - it_index_cache->second.value = pd.value(); - it_index_cache->second.warn = pd.warning(); - it_index_cache->second.warn_low = pd.warning_low(); - it_index_cache->second.crit = pd.critical(); - it_index_cache->second.crit_low = pd.critical_low(); - it_index_cache->second.warn_mode = pd.warning_mode(); - it_index_cache->second.crit_mode = pd.critical_mode(); - it_index_cache->second.min = pd.min(); - it_index_cache->second.max = pd.max(); - { - std::lock_guard lck(_queues_m); - _metrics[it_index_cache->second.metric_id] = - &it_index_cache->second; - } - log_v2::perfdata()->debug("new metric with metric_id={}", - it_index_cache->second.metric_id); - } - } - if (need_metric_mapping) - to_publish.emplace_back( - std::make_shared(index_id, metric_id)); - - if (_store_in_db) { - // Append perfdata to queue. - metric_value val; - val.c_time = ss.last_check; - val.metric_id = metric_id; - val.status = ss.current_state; - val.value = pd.value(); - { - std::lock_guard lck(_queues_m); - _perfdata_queue.push_back(val); - } - } - - // Send perfdata event to processing. - if (!index_locked) { - auto perf{std::make_shared( - ss.host_id, ss.service_id, pd.name(), ss.last_check, - static_cast(ss.check_interval * _interval_length), - false, metric_id, rrd_len, pd.value(), - static_cast(pd.value_type()))}; - log_v2::perfdata()->debug( - "unified sql: generating perfdata event for metric {} " - "(name '{}', ctime {}, value {}, rrd_len {}, data_type {})", - perf->metric_id, perf->name, perf->ctime, perf->value, rrd_len, - perf->value_type); - multiplexing::publisher().write(perf); - } - } - multiplexing::publisher pblshr; - pblshr.write(to_publish); - } - } -} - -void stream::_update_metrics() { - std::unordered_map metrics; - { - std::lock_guard lck(_queues_m); - std::swap(_metrics, metrics); - } - - std::deque m; - for (auto it = metrics.begin(); it != metrics.end(); ++it) { - metric_info* metric = it->second; - m.emplace_back(fmt::format( - "({},'{}',{},{},'{}',{},{},'{}',{},{},{})", metric->metric_id, - misc::string::escape(metric->unit_name, - get_metrics_col_size(metrics_unit_name)), - std::isnan(metric->warn) || std::isinf(metric->warn) - ? "NULL" - : fmt::format("{}", metric->warn), - std::isnan(metric->warn_low) || std::isinf(metric->warn_low) - ? "NULL" - : fmt::format("{}", metric->warn_low), - metric->warn_mode ? "1" : "0", - std::isnan(metric->crit) || std::isinf(metric->crit) - ? "NULL" - : fmt::format("{}", metric->crit), - std::isnan(metric->crit_low) || std::isinf(metric->crit_low) - ? "NULL" - : fmt::format("{}", metric->crit_low), - metric->crit_mode ? "1" : "0", - std::isnan(metric->min) || std::isinf(metric->min) - ? "NULL" - : fmt::format("{}", metric->min), - std::isnan(metric->max) || std::isinf(metric->max) - ? "NULL" - : fmt::format("{}", metric->max), - std::isnan(metric->value) || std::isinf(metric->value) - ? "NULL" - : fmt::format("{}", metric->value))); - } - if (!m.empty()) { - std::string query(fmt::format( - "INSERT INTO metrics (metric_id, unit_name, warn, warn_low, " - "warn_threshold_mode, crit, crit_low, crit_threshold_mode, min, max, " - "current_value) VALUES {} ON DUPLICATE KEY UPDATE " - "unit_name=VALUES(unit_name), warn=VALUES(warn), " - "warn_low=VALUES(warn_low), " - "warn_threshold_mode=VALUES(warn_threshold_mode), crit=VALUES(crit), " - "crit_low=VALUES(crit_low), " - "crit_threshold_mode=VALUES(crit_threshold_mode), min=VALUES(min), " - "max=VALUES(max), current_value=VALUES(current_value)", - fmt::join(m, ","))); - int32_t conn = _mysql.choose_best_connection(-1); - _finish_action(-1, actions::metrics); - log_v2::sql()->trace("Send query: {}", query); - _mysql.run_query(query, database::mysql_error::update_metrics, false, conn); - _add_action(conn, actions::metrics); - } -} - -/** - * Insert performance data entries in the data_bin table. - */ -void stream::_insert_perfdatas() { - std::deque pd_queue; - { - std::lock_guard lck(_queues_m); - std::swap(_perfdata_queue, pd_queue); - } - - auto it = pd_queue.begin(); - if (it != pd_queue.end()) { - // Status. - //_update_status("status=inserting performance data\n"); - - uint32_t count = 0; - - // Insert first entry. - std::ostringstream query; - { - const metric_value& mv = *it; - if (std::isinf(mv.value)) - query << fmt::format( - "INSERT INTO data_bin (id_metric,ctime,status,value) VALUES " - "({},{},'{}',{})", - mv.metric_id, mv.c_time, mv.status, - (mv.value < 0.0) ? -FLT_MAX : FLT_MAX); - else if (std::isnan(mv.value)) - query << fmt::format( - "INSERT INTO data_bin (id_metric,ctime,status,value) VALUES " - "({},{},'{}',NULL)", - mv.metric_id, mv.c_time, mv.status); - else - query << fmt::format( - "INSERT INTO data_bin (id_metric,ctime,status,value) VALUES " - "({},{},'{}',{})", - mv.metric_id, mv.c_time, mv.status, mv.value); - ++it; - count++; - } - - // Insert perfdata in data_bin. - for (; it != pd_queue.end(); ++it) { - const metric_value& mv = *it; - if (std::isinf(mv.value)) - query << fmt::format(",({},{},'{}',{})", mv.metric_id, mv.c_time, - mv.status, (mv.value < 0.0) ? -FLT_MAX : FLT_MAX); - else if (std::isnan(mv.value)) - query << fmt::format(",({},{},'{}',NULL)", mv.metric_id, mv.c_time, - mv.status); - else - query << fmt::format(",({},{},'{}',{})", mv.metric_id, mv.c_time, - mv.status, mv.value); - count++; - } - - // Execute query. - _mysql.run_query(query.str(), database::mysql_error::insert_data); - - //_update_status(""); - log_v2::sql()->info("unified_sql: {} perfdata inserted in data_bin", count); - } -} - -/** - * Check for deleted index. - */ -void stream::_check_deleted_index(asio::error_code ec) { - if (ec) - log_v2::sql()->info( - "unified_sql: the check for deleted indices encountered an error: {}", - ec.message()); - else { - // Info. - log_v2::sql()->info("unified_sql: starting DB cleanup"); - uint32_t deleted_index(0); - uint32_t deleted_metrics(0); - - // Fetch next index to delete. - { - std::promise promise; - int32_t conn = _mysql.choose_best_connection(-1); - std::set index_to_delete; - std::set metrics_to_delete; - try { - _mysql.run_query_and_get_result( - "SELECT m.index_id,m.metric_id, m.metric_name, i.host_id, " - "i.service_id FROM metrics m LEFT JOIN index_data i ON " - "i.id=m.index_id WHERE i.to_delete=1", - &promise, conn); - database::mysql_result res(promise.get_future().get()); - - std::lock_guard lock(_metric_cache_m); - while (_mysql.fetch_row(res)) { - index_to_delete.insert(res.value_as_u64(0)); - metrics_to_delete.insert(res.value_as_u64(1)); - _metric_cache.erase({res.value_as_u64(0), res.value_as_str(2)}); - _index_cache.erase({res.value_as_u32(3), res.value_as_u32(4)}); - } - promise = std::promise(); - _mysql.run_query_and_get_result( - "SELECT metric_id, metric_name FROM metrics WHERE to_delete=1", - &promise, conn); - res = promise.get_future().get(); - - while (_mysql.fetch_row(res)) { - metrics_to_delete.insert(res.value_as_u64(0)); - _metric_cache.erase({res.value_as_u64(0), res.value_as_str(1)}); - } - } catch (const std::exception& e) { - log_v2::sql()->error( - "could not query index / metrics table(s) to get index to delete: " - "{} ", - e.what()); - } - - // Delete metrics. - - std::string query; - std::string err_msg; - for (int64_t i : metrics_to_delete) { - query = fmt::format("DELETE FROM metrics WHERE metric_id={}", i); - _mysql.run_query(query, database::mysql_error::delete_metric, false, - conn); - _add_action(conn, actions::metrics); - - // Remove associated graph. - std::shared_ptr rg{ - std::make_shared(i, false)}; - multiplexing::publisher().write(rg); - - { - std::lock_guard lck(_queues_m); - _metrics.erase(i); - } - log_v2::perfdata()->debug("metrics erasing metric_id = {}", i); - deleted_metrics++; - } - - // Delete index from DB. - for (int64_t i : index_to_delete) { - query = fmt::format("DELETE FROM index_data WHERE id={}", i); - _mysql.run_query(query, database::mysql_error::delete_index, false, - conn); - _add_action(conn, actions::index_data); - - // Remove associated graph. - std::shared_ptr rg{ - std::make_shared(i, true)}; - multiplexing::publisher().write(rg); - deleted_index++; - } - } - - // End. - log_v2::perfdata()->info( - "unified_sql: end of DB cleanup: {} metrics and {} indices removed", - deleted_metrics, deleted_index); - _timer.expires_after(std::chrono::minutes(5)); - _timer.async_wait( - std::bind(&stream::_check_deleted_index, this, std::placeholders::_1)); - } -} diff --git a/centreon-broker/unified_sql/test/conflict_manager.cc b/centreon-broker/unified_sql/test/conflict_manager.cc deleted file mode 100644 index 3b625a588bf..00000000000 --- a/centreon-broker/unified_sql/test/conflict_manager.cc +++ /dev/null @@ -1,134 +0,0 @@ -/* -** Copyright 2018 Centreon -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -** -** For more information : contact@centreon.com -*/ - -#include "com/centreon/broker/unified_sql/conflict_manager.hh" - -#include - -#include -#include - -#include "../../core/test/test_server.hh" -#include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/modules/loader.hh" -#include "com/centreon/broker/neb/custom_variable.hh" -#include "com/centreon/broker/neb/host.hh" -#include "com/centreon/broker/neb/instance.hh" -#include "com/centreon/broker/neb/module.hh" -#include "com/centreon/broker/neb/service.hh" - -using namespace com::centreon::broker; -using namespace com::centreon::broker::sql; - -class USConflictManagerTest : public ::testing::Test { - public: - void SetUp() override { - try { - config::applier::init(0, "test_broker"); - } catch (std::exception const& e) { - (void)e; - } - } - void TearDown() override { config::applier::deinit(); } -}; - -TEST_F(USConflictManagerTest, OpenClose) { - database_config dbcfg("MySQL", "127.0.0.1", 3306, "centreon", "centreon", - "centreon_unified_sql", 5, true, 5); - uint32_t loop_timeout = 5; - uint32_t instance_timeout = 5; - - ASSERT_FALSE(conflict_manager::init_unified_sql(true, 100000, 18)); - ASSERT_NO_THROW( - conflict_manager::init_sql(dbcfg, loop_timeout, instance_timeout)); - ASSERT_TRUE(conflict_manager::init_unified_sql(true, 100000, 18)); - conflict_manager::close(); -} - -TEST_F(USConflictManagerTest, InstCVConflict) { - modules::loader l; - l.load_file("./neb/10-neb.so"); - uint32_t loop_timeout = 5; - uint32_t instance_timeout = 5; - database_config dbcfg("MySQL", "127.0.0.1", 3306, "centreon", "centreon", - "centreon_unified_sql", 5, true, 5); - ASSERT_NO_THROW( - conflict_manager::init_sql(dbcfg, loop_timeout, instance_timeout)); - - std::shared_ptr inst{std::make_shared()}; - inst->poller_id = 1; - inst->name = "Central"; - inst->program_start = time(nullptr) - 100; - inst->program_end = time(nullptr) - 1; - inst->version = "1.8.1"; - inst->is_running = true; - conflict_manager::instance().send_event(conflict_manager::sql, inst); - - std::shared_ptr h{std::make_shared()}; - h->address = "10.0.2.15"; - h->alias = "central"; - h->flap_detection_on_down = true; - h->flap_detection_on_unreachable = true; - h->flap_detection_on_up = true; - h->host_id = 31; - h->host_name = "central_9"; - h->notify_on_down = true; - h->notify_on_unreachable = true; - h->poller_id = 1; - h->stalk_on_down = false; - h->stalk_on_unreachable = false; - h->stalk_on_up = false; - h->statusmap_image = ""; - h->timezone = "Europe/Paris"; - conflict_manager::instance().send_event(conflict_manager::sql, h); - - std::shared_ptr s{std::make_shared()}; - s->host_id = 31; - s->service_id = 498; - s->default_active_checks_enabled = true; - s->default_event_handler_enabled = true; - s->default_flap_detection_enabled = true; - s->default_notifications_enabled = true; - s->default_passive_checks_enabled = true; - s->display_name = "test-dbr"; - s->icon_image = ""; - s->icon_image_alt = ""; - s->notification_interval = 30; - s->notification_period = ""; - s->notify_on_downtime = true; - s->notify_on_flapping = true; - s->notify_on_recovery = true; - s->retain_nonstatus_information = true; - s->retain_status_information = true; - - conflict_manager::instance().send_event(conflict_manager::sql, s); - - std::shared_ptr cv{ - std::make_shared()}; - cv->service_id = 498; - cv->update_time = time(nullptr); - cv->modified = false; - cv->host_id = 31; - cv->name = "PROCESSNAME"; - cv->value = "centengine"; - cv->default_value = "centengine"; - - conflict_manager::instance().send_event(conflict_manager::sql, cv); - - conflict_manager::close(); -} diff --git a/centreon-broker/unified_sql/test/connector.cc b/centreon-broker/unified_sql/test/connector.cc deleted file mode 100644 index 66e1d89fb9c..00000000000 --- a/centreon-broker/unified_sql/test/connector.cc +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - * - */ - -#include "com/centreon/broker/unified_sql/connector.hh" - -#include - -#include "com/centreon/broker/exceptions/config.hh" -#include "com/centreon/broker/unified_sql/factory.hh" - -using namespace com::centreon::exceptions; -using namespace com::centreon::broker; - -TEST(UnifiedSqlFactory, Factory) { - database_config dbcfg("MySQL", "127.0.0.1", "/var/lib/mysql/mysql.sock", 3306, - "centreon", "centreon", "centreon_unified_sql", 5, true, - 5); - std::shared_ptr cache; - config::endpoint cfg(config::endpoint::io_type::output); - bool is_acceptor; - - unified_sql::factory factory; - - ASSERT_THROW(factory.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - cfg.params["length"] = "42"; - ASSERT_THROW(factory.new_endpoint(cfg, is_acceptor, cache), - exceptions::config); - cfg.params["db_type"] = "mysql"; - cfg.params["db_name"] = "centreon"; - ASSERT_FALSE(factory.has_endpoint(cfg, nullptr)); - cfg.type = "unified_sql"; - unified_sql::connector* endp = static_cast( - factory.new_endpoint(cfg, is_acceptor, cache)); - - unified_sql::connector con; - con.connect_to(dbcfg, 42, 60, 300, 80, 250, true); - - ASSERT_TRUE(factory.has_endpoint(cfg, nullptr)); - ASSERT_EQ(cfg.read_timeout, -1); - ASSERT_EQ(cfg.params["read_timeout"], ""); - - delete endp; -} - - -TEST(UnifiedSqlFactory, FactoryWithFullConf) { - database_config dbcfg("MySQL", "", "/var/lib/mysql/mysql.sock", 3306, - "centreon", "centreon", "centreon_unified_sql", 5, true, - 5); - std::shared_ptr cache; - config::endpoint cfg(config::endpoint::io_type::output); - bool is_acceptor; - - unified_sql::factory factory; - - ASSERT_THROW(factory.new_endpoint(cfg, is_acceptor, cache), msg_fmt); - cfg.params["length"] = "42"; - ASSERT_THROW(factory.new_endpoint(cfg, is_acceptor, cache), - exceptions::config); - cfg.params["db_type"] = "mysql"; - cfg.params["db_name"] = "centreon"; - cfg.params["interval"] = "43"; - cfg.params["rebuild_check_interval"] = "44"; - cfg.params["store_in_data_bin"] = "0"; - ASSERT_FALSE(factory.has_endpoint(cfg, nullptr)); - cfg.type = "unified_sql"; - unified_sql::connector* endp = static_cast( - factory.new_endpoint(cfg, is_acceptor, cache)); - - unified_sql::connector con; - con.connect_to(dbcfg, 42, 43, 44, 45, 46, false); - - ASSERT_TRUE(factory.has_endpoint(cfg, nullptr)); - ASSERT_EQ(cfg.read_timeout, -1); - ASSERT_EQ(cfg.params["read_timeout"], ""); - - delete endp; -} diff --git a/centreon-broker/unified_sql/test/metric.cc b/centreon-broker/unified_sql/test/metric.cc deleted file mode 100644 index 978d65aa834..00000000000 --- a/centreon-broker/unified_sql/test/metric.cc +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - * - */ - -#include "bbdo/storage/metric.hh" -#include -#include -#include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/misc/perfdata.hh" -#include "com/centreon/broker/unified_sql/internal.hh" - -using namespace com::centreon::broker; - -/** - * Check that the metric assignment operator works properly. - */ -TEST(UnifiedSqlMetric, SpecificConstructor) { - // First object. - storage::metric m1(1, 14, "foo", 123456789, 42, true, 24, 180, 4242.0, 1); - - // Check objects properties values. - ASSERT_FALSE(m1.ctime != 123456789); - ASSERT_FALSE(m1.interval != 42); - ASSERT_FALSE(m1.is_for_rebuild != true); - ASSERT_FALSE(m1.metric_id != 24); - ASSERT_FALSE(m1.name != "foo"); - ASSERT_FALSE(m1.rrd_len != 180); - ASSERT_FALSE(fabs(m1.value - 4242.0) > 0.00001); - ASSERT_FALSE(m1.value_type != 1); -} - -/** - * Check that the metric object properly default constructs. - */ -TEST(UnifiedSqlMetric, DefaultCtor) { - // Build object. - storage::metric m; - - auto val(io::events::data_type::value); - - // Check properties values. - ASSERT_FALSE(m.ctime != 0); - ASSERT_FALSE(m.interval != 0); - ASSERT_FALSE(m.is_for_rebuild != false); - ASSERT_FALSE(m.metric_id != 0); - ASSERT_FALSE(!m.name.empty()); - ASSERT_FALSE(m.rrd_len != 0); - ASSERT_FALSE(!std::isnan(m.value)); - ASSERT_FALSE(m.value_type != misc::perfdata::gauge); - ASSERT_FALSE(m.type() != val); -} diff --git a/centreon-broker/unified_sql/test/perfdata.cc b/centreon-broker/unified_sql/test/perfdata.cc deleted file mode 100644 index 49248d99805..00000000000 --- a/centreon-broker/unified_sql/test/perfdata.cc +++ /dev/null @@ -1,558 +0,0 @@ -/* - * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - * - */ - -#include -#include - -#include -#include - -#include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/misc/misc.hh" -#include "com/centreon/broker/misc/perfdata.hh" - -using namespace com::centreon::broker; - -/** - * Check that the perfdata assignment operator works properly. - */ -TEST(UnifiedSqlPerfdata, Assign) { - // First object. - misc::perfdata p1; - p1.critical(42.0); - p1.critical_low(-456.032); - p1.critical_mode(false); - p1.max(76.3); - p1.min(567.2); - p1.name("foo"); - p1.unit("bar"); - p1.value(52189.912); - p1.value_type(misc::perfdata::counter); - p1.warning(4548.0); - p1.warning_low(42.42); - p1.warning_mode(true); - - // Second object. - misc::perfdata p2; - p2.critical(2345678.9672374); - p2.critical_low(-3284523786.8923); - p2.critical_mode(true); - p2.max(834857.9023); - p2.min(348.239479); - p2.name("merethis"); - p2.unit("centreon"); - p2.value(8374598345.234); - p2.value_type(misc::perfdata::absolute); - p2.warning(0.823745784); - p2.warning_low(NAN); - p2.warning_mode(false); - - // Assignment. - p2 = p1; - - // Change first object. - p1.critical(9432.5); - p1.critical_low(1000.0001); - p1.critical_mode(true); - p1.max(123.0); - p1.min(843.876); - p1.name("baz"); - p1.unit("qux"); - p1.value(3485.9); - p1.value_type(misc::perfdata::derive); - p1.warning(3612.0); - p1.warning_low(-987579.0); - p1.warning_mode(false); - - // Check objects properties values. - ASSERT_FALSE(fabs(p1.critical() - 9432.5) > 0.00001); - ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001) > 0.00001); - ASSERT_FALSE(!p1.critical_mode()); - ASSERT_FALSE(fabs(p1.max() - 123.0) > 0.00001); - ASSERT_FALSE(fabs(p1.min() - 843.876) > 0.00001); - ASSERT_FALSE(p1.name() != "baz"); - ASSERT_FALSE(p1.unit() != "qux"); - ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); - ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); - ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); - ASSERT_FALSE(p1.warning_mode()); - ASSERT_FALSE(fabs(p2.critical() - 42.0) > 0.00001); - ASSERT_FALSE(fabs(p2.critical_low() + 456.032) > 0.00001); - ASSERT_FALSE(p2.critical_mode()); - ASSERT_FALSE(fabs(p2.max() - 76.3) > 0.00001); - ASSERT_FALSE(fabs(p2.min() - 567.2) > 0.00001); - ASSERT_FALSE(p2.name() != "foo"); - ASSERT_FALSE(p2.unit() != "bar"); - ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); - ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); - ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); - ASSERT_FALSE(!p2.warning_mode()); -} - -/** - * Check that the perfdata copy constructor works properly. - */ -TEST(UnifiedSqlPerfdata, CopyCtor) { - // First object. - misc::perfdata p1; - p1.critical(42.0); - p1.critical_low(-456.032); - p1.critical_mode(false); - p1.max(76.3); - p1.min(567.2); - p1.name("foo"); - p1.unit("bar"); - p1.value(52189.912); - p1.value_type(misc::perfdata::counter); - p1.warning(4548.0); - p1.warning_low(42.42); - p1.warning_mode(true); - - // Second object. - misc::perfdata p2(p1); - - // Change first object. - p1.critical(9432.5); - p1.critical_low(1000.0001); - p1.critical_mode(true); - p1.max(123.0); - p1.min(843.876); - p1.name("baz"); - p1.unit("qux"); - p1.value(3485.9); - p1.value_type(misc::perfdata::derive); - p1.warning(3612.0); - p1.warning_low(-987579.0); - p1.warning_mode(false); - - // Check objects properties values. - ASSERT_FALSE(fabs(p1.critical() - 9432.5) > 0.00001); - ASSERT_FALSE(fabs(p1.critical_low() - 1000.0001) > 0.00001); - ASSERT_FALSE(!p1.critical_mode()); - ASSERT_FALSE(fabs(p1.max() - 123.0) > 0.00001); - ASSERT_FALSE(fabs(p1.min() - 843.876) > 0.00001); - ASSERT_FALSE(p1.name() != "baz"); - ASSERT_FALSE(p1.unit() != "qux"); - ASSERT_FALSE(fabs(p1.value() - 3485.9) > 0.00001); - ASSERT_FALSE(p1.value_type() != misc::perfdata::derive); - ASSERT_FALSE(fabs(p1.warning() - 3612.0) > 0.00001); - ASSERT_FALSE(fabs(p1.warning_low() + 987579.0) > 0.01); - ASSERT_FALSE(p1.warning_mode()); - ASSERT_FALSE(fabs(p2.critical() - 42.0) > 0.00001); - ASSERT_FALSE(fabs(p2.critical_low() + 456.032) > 0.00001); - ASSERT_FALSE(p2.critical_mode()); - ASSERT_FALSE(fabs(p2.max() - 76.3) > 0.00001); - ASSERT_FALSE(fabs(p2.min() - 567.2) > 0.00001); - ASSERT_FALSE(p2.name() != "foo"); - ASSERT_FALSE(p2.unit() != "bar"); - ASSERT_FALSE(fabs(p2.value() - 52189.912) > 0.00001); - ASSERT_FALSE(p2.value_type() != misc::perfdata::counter); - ASSERT_FALSE(fabs(p2.warning() - 4548.0) > 0.00001); - ASSERT_FALSE(fabs(p2.warning_low() - 42.42) > 0.00001); - ASSERT_FALSE(!p2.warning_mode()); -} - -/** - * Check that the perfdata object properly default constructs. - * - * @return 0 on success. - */ -TEST(UnifiedSqlPerfdata, DefaultCtor) { - // Build object. - misc::perfdata p; - - // Check properties values. - ASSERT_FALSE(!std::isnan(p.critical())); - ASSERT_FALSE(!std::isnan(p.critical_low())); - ASSERT_FALSE(p.critical_mode()); - ASSERT_FALSE(!std::isnan(p.max())); - ASSERT_FALSE(!std::isnan(p.min())); - ASSERT_FALSE(!p.name().empty()); - ASSERT_FALSE(!p.unit().empty()); - ASSERT_FALSE(!std::isnan(p.value())); - ASSERT_FALSE(p.value_type() != misc::perfdata::gauge); - ASSERT_FALSE(!std::isnan(p.warning())); - ASSERT_FALSE(!std::isnan(p.warning_low())); - ASSERT_FALSE(p.warning_mode()); -} - -class UnifiedSqlParserParsePerfdata : public testing::Test { - public: - void SetUp() override { config::applier::init(0, "test_broker"); } - void TearDown() override { config::applier::deinit(); }; -}; - -// Given a misc::parser object -// When parse_perfdata() is called with a valid perfdata string -// Then perfdata are returned in a list -TEST_F(UnifiedSqlParserParsePerfdata, Simple1) { - auto lst{misc::parse_perfdata(0, 0, "time=2.45698s;2.000000;5.000000;0.000000;10.000000")}; - - // Assertions. - ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; - expected.name("time"); - expected.value_type(misc::perfdata::gauge); - expected.value(2.45698); - expected.unit("s"); - expected.warning(2.0); - expected.warning_low(0.0); - expected.critical(5.0); - expected.critical_low(0.0); - expected.min(0.0); - expected.max(10.0); - ASSERT_TRUE(expected == *it); -} - -TEST_F(UnifiedSqlParserParsePerfdata, Simple2) { - auto list{misc::parse_perfdata(0, 0, "'ABCD12E'=18.00%;15:;10:;0;100")}; - - // Assertions. - ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; - expected.name("ABCD12E"); - expected.value_type(misc::perfdata::gauge); - expected.value(18.0); - expected.unit("%"); - expected.warning(std::numeric_limits::infinity()); - expected.warning_low(15.0); - expected.critical(std::numeric_limits::infinity()); - expected.critical_low(10.0); - expected.min(0.0); - expected.max(100.0); - ASSERT_TRUE(expected == *it); -} - -TEST_F(UnifiedSqlParserParsePerfdata, Complex1) { - auto list{misc::parse_perfdata( - 0, 0, - "time=2.45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " - "infotraffic=18x;;;; a[foo]=1234;10;11: c[bar]=1234;~:10;20:30 " - "baz=1234;@10:20; 'q u x'=9queries_per_second;@10:;@5:;0;100")}; - - // Assertions. - ASSERT_EQ(list.size(), 7u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; - - // #1. - expected.name("time"); - expected.value_type(misc::perfdata::gauge); - expected.value(2.45698); - expected.unit("s"); - expected.max(std::numeric_limits::infinity()); - ASSERT_TRUE(expected == *it); - ++it; - - // #2. - expected = misc::perfdata(); - expected.name("metric"); - expected.value_type(misc::perfdata::derive); - expected.value(239765); - expected.unit("B/s"); - expected.warning(5.0); - expected.warning_low(0.0); - expected.min(-std::numeric_limits::infinity()); - ASSERT_TRUE(expected == *it); - ++it; - - // #3. - expected = misc::perfdata(); - expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); - expected.value(18.0); - expected.unit("x"); - ASSERT_TRUE(expected == *it); - ++it; - - // #4. - expected = misc::perfdata(); - expected.name("foo"); - expected.value_type(misc::perfdata::absolute); - expected.value(1234.0); - expected.warning(10.0); - expected.warning_low(0.0); - expected.critical(std::numeric_limits::infinity()); - expected.critical_low(11.0); - ASSERT_TRUE(expected == *it); - ++it; - - // #5. - expected = misc::perfdata(); - expected.name("bar"); - expected.value_type(misc::perfdata::counter); - expected.value(1234.0); - expected.warning(10.0); - expected.warning_low(-std::numeric_limits::infinity()); - expected.critical(30.0); - expected.critical_low(20.0); - ASSERT_TRUE(expected == *it); - ++it; - - // #6. - expected = misc::perfdata(); - expected.name("baz"); - expected.value_type(misc::perfdata::gauge); - expected.value(1234.0); - expected.warning(20.0); - expected.warning_low(10.0); - expected.warning_mode(true); - ASSERT_TRUE(expected == *it); - ++it; - - // #7. - expected = misc::perfdata(); - expected.name("q u x"); - expected.value_type(misc::perfdata::gauge); - expected.value(9.0); - expected.unit("queries_per_second"); - expected.warning(std::numeric_limits::infinity()); - expected.warning_low(10.0); - expected.warning_mode(true); - expected.critical(std::numeric_limits::infinity()); - expected.critical_low(5.0); - expected.critical_mode(true); - expected.min(0.0); - expected.max(100.0); - ASSERT_TRUE(expected == *it); -} - -// Given a misc::parser object -// When parse_perfdata() is called multiple time with valid strings -// Then the corresponding perfdata list is returned -TEST_F(UnifiedSqlParserParsePerfdata, Loop) { - std::list list; - - // Loop. - for (uint32_t i(0); i < 10000; ++i) { - // Parse perfdata string. - list = misc::parse_perfdata( - 0, 0, "c[time]=2.45698s;2.000000;5.000000;0.000000;10.000000"); - - // Assertions. - ASSERT_EQ(list.size(), 1u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; - expected.name("time"); - expected.value_type(misc::perfdata::counter); - expected.value(2.45698); - expected.unit("s"); - expected.warning(2.0); - expected.warning_low(0.0); - expected.critical(5.0); - expected.critical_low(0.0); - expected.min(0.0); - expected.max(10.0); - ASSERT_TRUE(expected == *it); - ++it; - } -} - -// Given a misc::parser object -// When parse_perfdata() is called with an invalid string -// Then it throws a unified_sql::exceptions::perfdata -TEST_F(UnifiedSqlParserParsePerfdata, Incorrect1) { - // Attempt to parse perfdata. - auto list{misc::parse_perfdata(0, 0, "metric1= 10 metric2=42")}; - ASSERT_EQ(list.size(), 1u); - ASSERT_EQ(list.back().name(), "metric2"); - ASSERT_EQ(list.back().value(), 42); -} - -// Given a misc::parser object -// When parse_perfdata() is called with a metric without value but with unit -// Then it throws a unified_sql::exceptions::perfdata -TEST_F(UnifiedSqlParserParsePerfdata, Incorrect2) { - auto list{misc::parse_perfdata(0, 0, "metric=kb/s")}; - ASSERT_TRUE(list.empty()); -} - -TEST_F(UnifiedSqlParserParsePerfdata, LabelWithSpaces) { - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; - - // Assertions. - ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; - expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); - expected.value(2); - expected.unit("s"); - expected.warning(2.0); - expected.warning_low(0.0); - expected.critical(5.0); - expected.critical_low(0.0); - ASSERT_TRUE(expected == *it); -} - -TEST_F(UnifiedSqlParserParsePerfdata, LabelWithSpacesMultiline) { - auto lst{misc::parse_perfdata(0, 0, " 'foo bar '=2s;2;5;;")}; - - // Assertions. - ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; - expected.name("foo bar"); - expected.value_type(misc::perfdata::gauge); - expected.value(2); - expected.unit("s"); - expected.warning(2.0); - expected.warning_low(0.0); - expected.critical(5.0); - expected.critical_low(0.0); - ASSERT_TRUE(expected == *it); -} - -TEST_F(UnifiedSqlParserParsePerfdata, Complex2) { - auto list{misc::parse_perfdata( - 0, 0, - "' \n time'=2,45698s;;nan;;inf d[metric]=239765B/s;5;;-inf; " - "g[test]=8x;;;;" - " infotraffic=18,6x;;;; a[foo]=1234,17;10;11: c[bar]=1234,147;~:10;20:30")}; - - // Assertions. - ASSERT_EQ(list.size(), 6u); - std::list::const_iterator it(list.begin()); - misc::perfdata expected; - - // #1. - expected.name("time"); - expected.value_type(misc::perfdata::gauge); - expected.value(2.45698); - expected.unit("s"); - expected.max(std::numeric_limits::infinity()); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; - - // #2. - expected = misc::perfdata(); - expected.name("metric"); - expected.value_type(misc::perfdata::derive); - expected.value(239765); - expected.unit("B/s"); - expected.warning(5.0); - expected.warning_low(0.0); - expected.min(-std::numeric_limits::infinity()); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; - - // #3. - expected = misc::perfdata(); - expected.name("test"); - expected.value_type(misc::perfdata::gauge); - expected.value(8); - expected.unit("x"); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; - - // #4. - expected = misc::perfdata(); - expected.name("infotraffic"); - expected.value_type(misc::perfdata::gauge); - expected.value(18.6); - expected.unit("x"); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; - - // #5. - expected = misc::perfdata(); - expected.name("foo"); - expected.value_type(misc::perfdata::absolute); - expected.value(1234.17); - expected.warning(10.0); - expected.warning_low(0.0); - expected.critical(std::numeric_limits::infinity()); - expected.critical_low(11.0); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; - - // #6. - expected = misc::perfdata(); - expected.name("bar"); - expected.value_type(misc::perfdata::counter); - expected.value(1234.147); - expected.warning(10.0); - expected.warning_low(-std::numeric_limits::infinity()); - expected.critical(30.0); - expected.critical_low(20.0); - ASSERT_TRUE(expected == *it); - ASSERT_FALSE(expected != *it); - ++it; -} - -// Given a misc::parser object -// When parse_perfdata() is called with a valid perfdata string -// Then perfdata are returned in a list -TEST_F(UnifiedSqlParserParsePerfdata, SimpleWithR) { - auto lst{misc::parse_perfdata(0, 0, "'total'=5;;;0;\r")}; - - // Assertions. - ASSERT_EQ(lst.size(), 1u); - std::list::const_iterator it(lst.begin()); - misc::perfdata expected; - expected.name("total"); - expected.value_type(misc::perfdata::gauge); - expected.value(5); - expected.unit(""); - expected.warning(NAN); - expected.warning_low(NAN); - expected.critical(NAN); - expected.critical_low(NAN); - expected.min(0.0); - expected.max(NAN); - ASSERT_TRUE(expected == *it); -} - -// Given a misc::parser object -// When parse_perfdata() is called with a valid perfdata string -// Then perfdata are returned in a list -TEST_F(UnifiedSqlParserParsePerfdata, BadMetric) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 =1 user3=3")}; - - // Assertions. - ASSERT_EQ(lst.size(), 3u); - int i = 1; - for (auto& p : lst) { - ASSERT_EQ(p.name(), fmt::format("user{}", i)); - ASSERT_EQ(p.value(), static_cast(i)); - ++i; - } -} - -TEST_F(UnifiedSqlParserParsePerfdata, BadMetric1) { - auto lst{misc::parse_perfdata(0, 0, "user1=1 user2=2 user4= user3=3")}; - - // Assertions. - ASSERT_EQ(lst.size(), 3u); - int i = 1; - for (auto& p : lst) { - ASSERT_EQ(p.name(), fmt::format("user{}", i)); - ASSERT_EQ(p.value(), static_cast(i)); - ++i; - } -} diff --git a/centreon-broker/unified_sql/test/rebuild.cc b/centreon-broker/unified_sql/test/rebuild.cc deleted file mode 100644 index 7af0498245d..00000000000 --- a/centreon-broker/unified_sql/test/rebuild.cc +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - * - */ - -#include "bbdo/storage/rebuild.hh" -#include -#include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/unified_sql/internal.hh" - -using namespace com::centreon::broker; - -/** - * Check that the rebuild object properly default constructs. - */ -TEST(UnifiedSqlRebuild, DefaultCtor) { - // Build object. - storage::rebuild r; - - // Check properties values. - ASSERT_FALSE(!r.end); - ASSERT_FALSE(r.id != 0); - ASSERT_FALSE(r.is_index); -} - -/** - * Check that the remove_graph object properly return is type - */ -TEST(UnifiedSqlRebuild, ReturnType) { - storage::rebuild r; - auto val = io::events::data_type::value; - - ASSERT_TRUE(r.static_type() == val); - ASSERT_TRUE(r.type() == val); -} diff --git a/centreon-broker/unified_sql/test/rebuild2.cc b/centreon-broker/unified_sql/test/rebuild2.cc deleted file mode 100644 index d49caa38b81..00000000000 --- a/centreon-broker/unified_sql/test/rebuild2.cc +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright 2021 Centreon (https://www.centreon.com/) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - * - */ - -#include -#include - -#include -#include -#include -#include - -#include "com/centreon/broker/bbdo/stream.hh" -#include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/config/applier/modules.hh" -#include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/lua/macro_cache.hh" -#include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/misc/variant.hh" -#include "com/centreon/broker/neb/instance.hh" -#include "com/centreon/broker/persistent_file.hh" -#include "com/centreon/broker/unified_sql/internal.hh" - -using namespace com::centreon::broker; -using namespace com::centreon::broker::misc; -using namespace google::protobuf::util; - -class into_memory : public io::stream { - public: - into_memory() : io::stream("into_memory"), _memory() {} - ~into_memory() override {} - - bool read(std::shared_ptr& d, - time_t deadline = (time_t)-1) override { - (void)deadline; - if (_memory.empty()) - return false; - std::shared_ptr raw(new io::raw); - raw->get_buffer() = std::move(_memory); - _memory.clear(); - d = raw; - return true; - } - - int write(std::shared_ptr const& d) override { - _memory = std::static_pointer_cast(d)->get_buffer(); - return 1; - } - - int32_t stop() override { return 0; } - - std::vector const& get_memory() const { return _memory; } - std::vector& get_mutable_memory() { return _memory; } - - private: - std::vector _memory; -}; - -class UnifiedSqlRebuild2Test : public ::testing::Test { - public: - void SetUp() override { - io::data::broker_id = 0; - try { - config::applier::init(0, "broker_test"); - } catch (std::exception const& e) { - (void)e; - } - std::shared_ptr pcache( - std::make_shared("/tmp/broker_test_cache")); - } - - void TearDown() override { - // The cache must be destroyed before the applier deinit() call. - config::applier::deinit(); - ::remove("/tmp/broker_test_cache"); - ::remove(log_v2::instance().log_name().c_str()); - } -}; - -// When a script is correctly loaded and a neb event has to be sent -// Then this event is translated into a Lua table and sent to the lua write() -// function. -TEST_F(UnifiedSqlRebuild2Test, WriteReadRebuild2) { - config::applier::modules modules; - modules.load_file("./unified_sql/20-unified_sql.so"); - - std::shared_ptr r( - std::make_shared()); - r->obj.mutable_metric()->set_metric_id(1234); - r->obj.mutable_metric()->set_value_type(0); - for (int i = 0; i < 20; i++) { - Point* p = r->obj.add_data(); - p->set_ctime(i); - p->set_value(i * i); - } - - std::shared_ptr memory_stream(std::make_shared()); - bbdo::stream stm(true); - stm.set_substream(memory_stream); - stm.set_coarse(false); - stm.set_negotiate(false); - stm.negotiate(bbdo::stream::negotiate_first); - stm.write(r); - std::vector const& mem1 = memory_stream->get_memory(); - - constexpr size_t size = 270u; - ASSERT_EQ(mem1.size(), size); - // The size is size - 16: 16 is the header size. - for (uint32_t i = 0; i < size; i++) { - printf("%02x ", static_cast(0xff & mem1[i])); - if ((i & 0x1f) == 0) - puts(""); - } - puts(""); - - ASSERT_EQ(htons(*reinterpret_cast(&mem1[0] + 2)), size - 16); - - std::shared_ptr e; - stm.read(e, time(nullptr) + 1000); - std::shared_ptr new_r = - std::static_pointer_cast(e); - ASSERT_TRUE(MessageDifferencer::Equals(r->obj, new_r->obj)); -} - -// When a script is correctly loaded and a neb event has to be sent -// Then this event is translated into a Lua table and sent to the lua write() -// function. -TEST_F(UnifiedSqlRebuild2Test, LongWriteReadRebuild2) { - config::applier::modules modules; - modules.load_file("./unified_sql/20-unified_sql.so"); - - std::shared_ptr r( - std::make_shared()); - r->obj.mutable_metric()->set_metric_id(1234); - r->obj.mutable_metric()->set_value_type(0); - for (int i = 0; i < 20000; i++) { - Point* p = r->obj.add_data(); - p->set_ctime(i); - p->set_value(i * i); - } - - std::shared_ptr memory_stream(std::make_shared()); - bbdo::stream stm(true); - stm.set_substream(memory_stream); - stm.set_coarse(false); - stm.set_negotiate(false); - stm.negotiate(bbdo::stream::negotiate_first); - stm.write(r); - std::vector const& mem1 = memory_stream->get_memory(); - - constexpr size_t size = 283562; - ASSERT_EQ(mem1.size(), size); - - const char* tmp = &mem1[0]; - - for (int i = 0; i < 4; i++) { - std::cout << "test " << i << std::endl; - ASSERT_EQ(htons(*reinterpret_cast(tmp + 2)), 0xffff); - tmp += 16 + 0xffff; - } - ASSERT_EQ(htons(*reinterpret_cast(tmp + 2)), 21342); - - std::shared_ptr e; - stm.read(e, time(nullptr) + 1000); - std::shared_ptr new_r = - std::static_pointer_cast(e); - ASSERT_TRUE(MessageDifferencer::Equals(r->obj, new_r->obj)); -} diff --git a/centreon-broker/unified_sql/test/remove_graph.cc b/centreon-broker/unified_sql/test/remove_graph.cc deleted file mode 100644 index 14a7c552cd4..00000000000 --- a/centreon-broker/unified_sql/test/remove_graph.cc +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - * - */ - -#include "bbdo/storage/remove_graph.hh" -#include -#include -#include - -using namespace com::centreon::broker; - -/** - * Check that remove_graph's assignment operator. - */ -TEST(UnifiedSqlRemoveGraph, Constructor) { - // Base object. - storage::remove_graph r1(42, false); - ASSERT_TRUE(r1.id == 42); - ASSERT_FALSE(r1.is_index); -} - -/** - * Check that the remove_graph object properly return is type - */ -TEST(UnifiedSqlRemoveGraph, ReturnType) { - storage::remove_graph r; - auto val = - io::events::data_type::value; - - ASSERT_TRUE(r.static_type() == val); - ASSERT_TRUE(r.type() == val); -} diff --git a/centreon-broker/unified_sql/test/status-entry.cc b/centreon-broker/unified_sql/test/status-entry.cc deleted file mode 100644 index 14dcea73fea..00000000000 --- a/centreon-broker/unified_sql/test/status-entry.cc +++ /dev/null @@ -1,131 +0,0 @@ -/* - * * Copyright 2021 Centreon (https://www.centreon.com/) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information : contact@centreon.com - * * - * */ - -#include -#include - -#include -#include -#include - -#include "com/centreon/broker/bbdo/stream.hh" -#include "com/centreon/broker/config/applier/init.hh" -#include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/io/protocols.hh" -#include "com/centreon/broker/io/raw.hh" -#include "com/centreon/broker/log_v2.hh" -#include "com/centreon/broker/lua/macro_cache.hh" -#include "com/centreon/broker/misc/string.hh" -#include "com/centreon/broker/misc/variant.hh" -#include "com/centreon/broker/modules/handle.hh" -#include "com/centreon/broker/neb/instance.hh" -#include "com/centreon/broker/unified_sql/factory.hh" -#include "bbdo/storage/status.hh" - -using namespace com::centreon::broker; -using namespace com::centreon::broker::misc; - -class into_memory : public io::stream { - std::vector _memory; - - public: - into_memory() : io::stream("into_memory"), _memory() {} - ~into_memory() override {} - bool read(std::shared_ptr& d, - time_t deadline = (time_t)-1) override { - (void)deadline; - if (_memory.empty()) - return false; - std::shared_ptr raw(new io::raw); - raw->get_buffer() = std::move(_memory); - _memory.clear(); - d = raw; - return true; - } - - int32_t write(std::shared_ptr const& d) override { - _memory = std::static_pointer_cast(d)->get_buffer(); - return 1; - } - - int32_t stop() override { return 0; } - - std::vector const& get_memory() const { return _memory; } - std::vector& get_mutable_memory() { return _memory; } -}; - -class UnifiedSqlEntryTest : public ::testing::Test { - public: - void SetUp() override { - io::data::broker_id = 0; - try { - config::applier::init(0, "test_broker"); - } catch (std::exception const& e) { - (void)e; - } - std::shared_ptr pcache( - std::make_shared("/tmp/broker_test_cache")); - } - - void TearDown() override { - // The cache must be destroyed before the applier deinit() call. - config::applier::deinit(); - ::remove("/tmp/broker_test_cache"); - ::remove(log_v2::instance().log_name().c_str()); - } -}; - -// When a script is correctly loaded and a neb event has to be sent -// Then this event is translated into a Lua table and sent to the lua write() -// function. - -TEST_F(UnifiedSqlEntryTest, WriteStatus) { - io::events& e(io::events::instance()); - - // Register event status. - e.register_event(make_type(io::storage, storage::de_status), "status", - &storage::status::operations, - storage::status::entries); - - // Register unified_sql layer. - io::protocols::instance().reg("unified_sql", - std::make_shared(), 1, 7); - - std::shared_ptr st{std::make_shared( - 12345, 123456789123456789, 34567, false, 789789, 2)}; - - std::shared_ptr memory_stream(std::make_shared()); - bbdo::stream stm(true); - stm.set_substream(memory_stream); - stm.set_coarse(false); - stm.set_negotiate(false); - stm.negotiate(bbdo::stream::negotiate_first); - stm.write(st); - - std::shared_ptr ev; - stm.read(ev, time(nullptr) + 1000); - std::shared_ptr new_st = - std::static_pointer_cast(ev); - ASSERT_EQ(st->ctime, new_st->ctime); - ASSERT_EQ(st->index_id, new_st->index_id); - ASSERT_EQ(st->state, new_st->state); - - io::events::instance().unregister_category(io::storage); - io::protocols::instance().unreg("storage"); -} diff --git a/centreon-broker/unified_sql/test/status.cc b/centreon-broker/unified_sql/test/status.cc deleted file mode 100644 index 7a8c281731e..00000000000 --- a/centreon-broker/unified_sql/test/status.cc +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For more information : contact@centreon.com - * - */ - -#include "bbdo/storage/status.hh" -#include -#include "com/centreon/broker/io/events.hh" -#include "com/centreon/broker/unified_sql/internal.hh" - -using namespace com::centreon::broker; - -/** - * Check that the status assignment operator works properly. - */ -TEST(UnifiedSqlStatus, Assign) { - // First object. - storage::status s1; - s1.ctime = 123456789; - s1.index_id = 6774; - s1.interval = 42; - s1.is_for_rebuild = true; - s1.rrd_len = 180; - s1.state = 3; - - // Second object. - storage::status s2; - s2.ctime = 654123; - s2.index_id = 33; - s2.interval = 78; - s2.is_for_rebuild = false; - s2.rrd_len = 666; - s2.state = 1; - - // Assignment. - s2 = s1; - - // Change first object. - s1.ctime = 741258; - s1.index_id = 12; - s1.interval = 36; - s1.is_for_rebuild = false; - s1.rrd_len = 900; - s1.state = 2; - - // Check objects properties values. - ASSERT_FALSE(s1.ctime != 741258); - ASSERT_FALSE(s1.index_id != 12); - ASSERT_FALSE(s1.interval != 36); - ASSERT_FALSE(s1.is_for_rebuild != false); - ASSERT_FALSE(s1.rrd_len != 900); - ASSERT_FALSE(s1.state != 2); - ASSERT_FALSE(s2.ctime != 123456789); - ASSERT_FALSE(s2.index_id != 6774); - ASSERT_FALSE(s2.interval != 42); - ASSERT_FALSE(s2.is_for_rebuild != true); - ASSERT_FALSE(s2.rrd_len != 180); - ASSERT_FALSE(s2.state != 3); -} - -/** - * Check that the status copy constructor works properly. - */ -TEST(UnifiedSqlStatus, CopyCtor) { - // First object. - storage::status s1; - s1.ctime = 123456789; - s1.index_id = 42; - s1.interval = 24; - s1.is_for_rebuild = true; - s1.rrd_len = 180; - s1.state = 1; - - // Second object. - storage::status s2(s1); - - // Change first object. - s1.ctime = 741258; - s1.index_id = 3612; - s1.interval = 36; - s1.is_for_rebuild = false; - s1.rrd_len = 900; - s1.state = 2; - - // Check objects properties values. - ASSERT_FALSE(s1.ctime != 741258); - ASSERT_FALSE(s1.index_id != 3612); - ASSERT_FALSE(s1.interval != 36); - ASSERT_FALSE(s1.is_for_rebuild != false); - ASSERT_FALSE(s1.rrd_len != 900); - ASSERT_FALSE(s1.state != 2); - ASSERT_FALSE(s2.ctime != 123456789); - ASSERT_FALSE(s2.index_id != 42); - ASSERT_FALSE(s2.interval != 24); - ASSERT_FALSE(s2.is_for_rebuild != true); - ASSERT_FALSE(s2.rrd_len != 180); - ASSERT_FALSE(s2.state != 1); - ; -} - -/** - * Check that the status object properly default constructs. - */ -TEST(UnifiedSqlStatus, DefaultCtor) { - // Build object. - storage::status s; - - auto val(io::events::data_type::value); - - // Check properties values. - ASSERT_FALSE(s.ctime != 0); - ASSERT_FALSE(s.index_id != 0); - ASSERT_FALSE(s.interval != 0); - ASSERT_FALSE(s.is_for_rebuild != false); - ASSERT_FALSE(s.rrd_len != 0); - ASSERT_FALSE(s.state != 0); - ASSERT_FALSE(s.type() != val); - ; -} diff --git a/centreon-broker/watchdog/CMakeLists.txt b/centreon-broker/watchdog/CMakeLists.txt index be091cec3d7..ee237ce9ef7 100644 --- a/centreon-broker/watchdog/CMakeLists.txt +++ b/centreon-broker/watchdog/CMakeLists.txt @@ -27,7 +27,6 @@ include_directories(${PROJECT_SOURCE_DIR}/watchdog/inc/ # Watchdog binary. set(WATCHDOG "cbwd") set(WATCHDOG "${WATCHDOG}" PARENT_SCOPE) -add_definitions(-DPREFIX_SBIN_CBD="${CMAKE_INSTALL_FULL_SBINDIR}") add_executable("${WATCHDOG}" # Sources. ${SRC_DIR}/main.cc @@ -62,5 +61,5 @@ endif (WITH_WATCHDOG_TESTS) # Install rule. install(TARGETS "${WATCHDOG}" - RUNTIME DESTINATION "${CMAKE_INSTALL_FULL_SBINDIR}" + RUNTIME DESTINATION "${PREFIX_BIN}" ) diff --git a/centreon-broker/watchdog/src/configuration_parser.cc b/centreon-broker/watchdog/src/configuration_parser.cc index bbc1bf53b82..ea7ce940f50 100644 --- a/centreon-broker/watchdog/src/configuration_parser.cc +++ b/centreon-broker/watchdog/src/configuration_parser.cc @@ -166,7 +166,7 @@ void configuration_parser::_parse_centreon_broker_element(const json& element) { throw msg_fmt("missing instance name"); if (executable.empty()) - executable = std::string(PREFIX_SBIN_CBD "/cbd"); + executable = std::string(PREFIX_BIN "/cbd"); if (!_instances_configuration .insert({instance_name.get(), diff --git a/centreon-clib/CMakeLists.txt b/centreon-clib/CMakeLists.txt index 8e66b79f0fc..c1a67437869 100644 --- a/centreon-clib/CMakeLists.txt +++ b/centreon-clib/CMakeLists.txt @@ -1,5 +1,5 @@ ## -## Copyright 2011-2014,2018-2021 Centreon +## Copyright 2011-2014,2018-2019 Centreon ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. @@ -19,6 +19,10 @@ # Global options. cmake_minimum_required(VERSION 2.8) project("Centreon Clib" C CXX) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") +#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -stdlib=libc++") +#set(CMAKE_CXX_COMPILER "clang++") +add_definitions("-D_GLIBCXX_USE_CXX11_ABI=1") # Set directories. set(INCLUDE_DIR "${PROJECT_SOURCE_DIR}/inc") @@ -28,7 +32,11 @@ set(SCRIPT_DIR "${PROJECT_SOURCE_DIR}/script") # Version. -set(CLIB_VERSION "${COLLECT_MAJOR}.${COLLECT_MINOR}.${COLLECT_PATCH}") +set(CLIB_MAJOR 21) +set(CLIB_MINOR 10) +set(CLIB_PATCH 0) +set(CLIB_VERSION "${CLIB_MAJOR}.${CLIB_MINOR}.${CLIB_PATCH}") + # Include module to check existing libraries. include(CheckLibraryExists) @@ -99,11 +107,50 @@ endif () # Set path. +if (WITH_PREFIX) + set(PREFIX "${WITH_PREFIX}") + set(CMAKE_INSTALL_PREFIX "${PREFIX}") +else () + set(PREFIX "${CMAKE_INSTALL_PREFIX}") +endif () if (WITH_PREFIX_LIB_CLIB) set(PREFIX_LIB "${WITH_PREFIX_LIB_CLIB}") else () set(PREFIX_LIB "${CMAKE_INSTALL_PREFIX}/lib") endif () +if (WITH_PREFIX_INC) + set(PREFIX_INC "${WITH_PREFIX_INC}") +else () + set(PREFIX_INC "${CMAKE_INSTALL_PREFIX}/include") +endif () + + +# Set pkg-config options. +option(WITH_PKGCONFIG_SCRIPT "Generate and install pkg-config script." ON) +if (WITH_PKGCONFIG_SCRIPT) + # Generate pkg-config file. + message(STATUS "Generating pkg-config file.") + configure_file( + "${SCRIPT_DIR}/centreon-clib.pc.in" + "${SCRIPT_DIR}/centreon-clib.pc" + @ONLY + ) + + # pkg-config file install directory. + if (WITH_PKGCONFIG_DIR) + set(PKGCONFIG_DIR "${WITH_PKGCONFIG_DIR}") + else () + set(PKGCONFIG_DIR "${PREFIX_LIB}pkgconfig") + endif () + + # Install rule. + install( + FILES "${SCRIPT_DIR}/centreon-clib.pc" + DESTINATION "${PKGCONFIG_DIR}" + COMPONENT "runtime" + ) +endif () + # Set options. option(WITH_ASAN "Add the libasan to check memory leaks and other memory issues." OFF) @@ -135,6 +182,29 @@ if (CPACK_BINARY_RPM) set(RPM_PACKAGE "Yes") endif () + +# Set libraries. +if (NOT WITH_SHARED_LIB AND NOT WITH_STATIC_LIB) + set(WITH_SHARED_LIB 1) +endif () + +set(SHARED_LIB "No") +if (WITH_SHARED_LIB) + set(SHARED_LIB "Yes") +endif() + +set(STATIC_LIB "No") +if (WITH_STATIC_LIB) + set(STATIC_LIB "Yes") +endif () + +if (WITH_SHARED_LIB) + set(DEFAULT_LINK_NAME "centreon_clib_shared") +else () + set(DEFAULT_LINK_NAME "centreon_clib_static") +endif () + + # Find headers. include(CheckIncludeFileCXX) check_include_file_cxx("spawn.h" HAVE_SPAWN_H) @@ -194,38 +264,73 @@ if (WITH_TESTING) add_subdirectory(test) endif () -# Create shared library. -add_library( - centreon_clib - SHARED - ${SOURCES} - ${HEADERS} -) -# Link target with required libraries. -target_link_libraries( - centreon_clib - ${LIB_THREAD} - ${LIB_RT} - ${LIB_DL} -) -# Set output name for the shared library. -set_target_properties( - centreon_clib - PROPERTIES - OUTPUT_NAME - centreon_clib -) -# Install shared library. -install( - TARGETS centreon_clib - DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}" - COMPONENT "runtime" -) + +if (WITH_SHARED_LIB) + # Create shared library. + add_library( + "centreon_clib_shared" + SHARED + ${SOURCES} + ${HEADERS} + ) + # Link target with required libraries. + target_link_libraries( + "centreon_clib_shared" + ${LIB_THREAD} + ${LIB_RT} + ${LIB_DL} + ) + # Set output name for the shared library. + set_target_properties( + "centreon_clib_shared" + PROPERTIES + OUTPUT_NAME + "centreon_clib" + ) + # Install shared library. + install( + TARGETS "centreon_clib_shared" + DESTINATION "${PREFIX_LIB}" + COMPONENT "runtime" + ) +endif () + + +if (WITH_STATIC_LIB) + # Create static library. + add_library( + "centreon_clib_static" + STATIC + ${SOURCES} + ${HEADERS} + ) + # Link target with required libraries. + target_link_libraries( + "centreon_clib_static" + ${LIB_THREAD} + ${LIB_RT} + ${LIB_DL} + ) + # Set output name for the static library. + set_target_properties( + "centreon_clib_static" + PROPERTIES + OUTPUT_NAME + "centreon_clib" + ) + # Install static library. + install( + TARGETS "centreon_clib_static" + DESTINATION "${PREFIX_LIB}" + COMPONENT "runtime" + ) +endif () + # Install header files for devel. install( DIRECTORY "${INCLUDE_DIR}/" - DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/centreon-clib" + DESTINATION "${PREFIX_INC}" COMPONENT "development" FILES_MATCHING PATTERN "*.hh" ) @@ -242,6 +347,8 @@ message(STATUS "") message(STATUS " Project") message(STATUS " - Name ${PROJECT_NAME}") message(STATUS " - Version ${CLIB_VERSION}") +message(STATUS " - With shared library ${SHARED_LIB}") +message(STATUS " - With static library ${STATIC_LIB}") message(STATUS "") message(STATUS " System") message(STATUS " - Name ${CMAKE_SYSTEM_NAME}") @@ -255,7 +362,11 @@ message(STATUS " - Extra compilation flags ${CMAKE_CXX_FLAGS}") message(STATUS " - Build unit tests ${UNIT_TEST}") message(STATUS "") message(STATUS " Installation") -message(STATUS " - Prefix ${CMAKE_INSTALL_PREFIX}") +message(STATUS " - Prefix ${PREFIX}") message(STATUS " - Library directory ${PREFIX_LIB}") +message(STATUS " - Include directory ${PREFIX_INC}") message(STATUS " - Package ${PACKAGE_LIST}") +if (WITH_PKGCONFIG_SCRIPT) + message(STATUS " - pkg-config directory ${PKGCONFIG_DIR}") +endif () message(STATUS "") diff --git a/centreon-clib/cmake/package.cmake b/centreon-clib/cmake/package.cmake index 6dd1be2607d..8c61d979bb6 100644 --- a/centreon-clib/cmake/package.cmake +++ b/centreon-clib/cmake/package.cmake @@ -32,9 +32,9 @@ if (WITH_PACKAGE_SH # Default settings. set(CPACK_PACKAGE_NAME "centreon-clib") set(CPACK_PACKAGE_VENDOR "Centreon") - set(CPACK_PACKAGE_VERSION_MAJOR "${COLLECT_MAJOR}") - set(CPACK_PACKAGE_VERSION_MINOR "${COLLECT_MINOR}") - set(CPACK_PACKAGE_VERSION_PATCH "${COLLECT_PATCH}") + set(CPACK_PACKAGE_VERSION_MAJOR "${CLIB_MAJOR}") + set(CPACK_PACKAGE_VERSION_MINOR "${CLIB_MINOR}") + set(CPACK_PACKAGE_VERSION_PATCH "${CLIB_PATCH}") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Centreon C/C++ library used in multiple monitoring-related projects.") set(CPACK_PACKAGE_FILE_NAME diff --git a/centreon-clib/inc/com/centreon/clib/version.hh.in b/centreon-clib/inc/com/centreon/clib/version.hh.in index dea870844df..74e410192dc 100644 --- a/centreon-clib/inc/com/centreon/clib/version.hh.in +++ b/centreon-clib/inc/com/centreon/clib/version.hh.in @@ -20,9 +20,9 @@ # define CC_CLIB_VERSION_HH // Compile-time values. -# define CENTREON_CLIB_VERSION_MAJOR @COLLECT_MAJOR@ -# define CENTREON_CLIB_VERSION_MINOR @COLLECT_MINOR@ -# define CENTREON_CLIB_VERSION_PATCH @COLLECT_PATCH@ +# define CENTREON_CLIB_VERSION_MAJOR @CLIB_MAJOR@ +# define CENTREON_CLIB_VERSION_MINOR @CLIB_MINOR@ +# define CENTREON_CLIB_VERSION_PATCH @CLIB_PATCH@ # define CENTREON_CLIB_VERSION_STRING "@CLIB_VERSION@" # include "com/centreon/namespace.hh" @@ -32,16 +32,16 @@ CC_BEGIN() namespace clib { namespace version { // Compile-time values. - unsigned int const major = @COLLECT_MAJOR@; - unsigned int const minor = @COLLECT_MINOR@; - unsigned int const patch = @COLLECT_PATCH@; + unsigned int const major = @CLIB_MAJOR@; + unsigned int const minor = @CLIB_MINOR@; + unsigned int const patch = @CLIB_PATCH@; char const* const string = "@CLIB_VERSION@"; // Run-time values. - unsigned int get_major() noexcept; - unsigned int get_minor() noexcept; - unsigned int get_patch() noexcept; - char const* get_string() noexcept; + unsigned int get_major() throw (); + unsigned int get_minor() throw (); + unsigned int get_patch() throw (); + char const* get_string() throw (); } } diff --git a/centreon-clib/packaging/rpm/centreon-clib.spectemplate b/centreon-clib/packaging/rpm/centreon-clib.spectemplate new file mode 100644 index 00000000000..c4d2b8baf82 --- /dev/null +++ b/centreon-clib/packaging/rpm/centreon-clib.spectemplate @@ -0,0 +1,136 @@ +## +## Copyright 2011-2019 Centreon +## + +%if 0%{?suse_version} +%define group "Development/Languages/C and C++" +%else +%define group "Development/Libraries" +%endif + +Name: centreon-clib +Version: %{VERSION} +Release: %{RELEASE}%{?dist} +Summary: Centreon core library. + +Group: %{group} +License: ASL 2.0 +URL: https://github.com/centreon/centreon-clib +Packager: Matthieu Kermagoret +Vendor: Centreon Entreprise Server (CES) Repository, http://yum.centreon.com/standard/ + +Source0: %{name}-%{version}.tar.gz +BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root + +BuildRequires: cmake3 >= 3.15 + +BuildRequires: gcc +BuildRequires: gcc-c++ +BuildRequires: make +Conflicts: centreon-engine < 1.3.3 + +%description +Centreon Clib is a common library for all Centreon +products written in C/C++. + +%package devel +Summary: Provide include files for Centreon Clib. +Group: %{group} +Requires: centreon-clib = %{version}-%{release} +Requires: pkgconfig + +%description devel +Centreon Clib devel provide include files to build +Centreon products written in C/C++. + +%prep +%setup + +%build +pip3 install conan --upgrade +cpp11=$(gcc --version | awk "/gcc/ && ($3+0)>5.0{print 1}") +if [ $cpp11 -eq 1 ] ; then + conan install . -s compiler.libcxx=libstdc++11 --build=missing +else + conan install . -s compiler.libcxx=libstdc++ +fi + +CXXFLAGS="-DNDEBUG -g -O2 -Wno-long-long" cmake3 \ + -DWITH_PKGCONFIG_DIR=%{_libdir}/pkgconfig \ + -DWITH_PREFIX=%{_prefix} \ + -DWITH_PREFIX_LIB_CLIB=%{_libdir} \ + -DWITH_PREFIX_INC=%{_includedir}/centreon-clib \ + -DWITH_SHARED_LIB=1 \ + -DWITH_STATIC_LIB=0 \ + -DWITH_TESTING=0 . +%{__make} %{?jobs:-j%jobs} %{?_smp_mflags} VERBOSE="1" + +%install +%{__rm} -rf $RPM_BUILD_ROOT +%{__make} install DESTDIR="$RPM_BUILD_ROOT" + +%clean +%{__rm} -rf $RPM_BUILD_ROOT + +%pre + +%files +%defattr(-,root,root,-) +%{_libdir}/libcentreon_clib.so +%doc LICENSE + +%files devel +%defattr(-,root,root,-) +%{_libdir}/pkgconfig/centreon-clib.pc +%{_includedir}/centreon-clib +%doc LICENSE + +%changelog +* Tue Sep 29 2015 Matthieu Kermagoret 1.4.2-3 +- Do not install files that are not ours. + +* Mon Sep 28 2015 Matthieu Kermagoret 1.4.2-2 +- Update Centreon Clib license to Apache Software License 2 (ASL 2.0). + +* Thu Oct 16 2014 Alexandre Fouille 1.4.2-1 +- Fix a random memory corruption when a stringifier is realloc'd. + +* Wed Sep 10 2014 Alexandre Fouille 1.4.1-1 +- Fix a segfault when a stringifier is copied. + +* Tue May 27 2014 Matthieu Kermagoret 1.4.0-1 +- Introduce maximum log file size. + +* Thu May 22 2014 Matthieu Kermagoret 1.3.0-2 +- devel package must require the exact same version of the base package. + +* Thu Apr 10 2014 Matthieu Kermagoret 1.3.0-1 +- Handle interruptions of syscalls in process. + +* Thu Oct 17 2013 Dorian Guillois 1.2.1-2 +- Change centreon-clib spec to use the new cmake package. + +* Tue Oct 15 2013 Matthieu Kermagoret 1.2.1-1 +- Fix concurrent accesses to the task manager task list. + +* Tue Oct 01 2013 Matthieu Kermagoret 1.2.0-3 +- Clib conflicts with Centreon Engine < 1.3.3 (packaging bug) + +* Thu Aug 29 2013 Matthieu Kermagoret 1.2.0-2 +- Reworked spec file. + +* Fri Aug 16 2013 Dorian Guillois 1.2.0-1 +- Add feature on shared_ptr. +- Add hash function. + +* Fri May 3 2013 Dorian Guillois 1.1.0-1 +- Fix command line parser. +- Fix thread sleep. +- Improve performances. +- Update documentation. + +* Tue Mar 05 2013 Maximilien Bersoult 1.0.0-13 +- Use macro for cmake dependancies in CES 2.2 and CES 3.0, prepare for OpenSuSE + +* Mon Aug 20 2012 Dorian Guillois 1.0.0-1 +- Initial build. diff --git a/centreon-clib/packaging/rpm/debian/centreon-clib.triggers b/centreon-clib/packaging/rpm/debian/centreon-clib.triggers new file mode 100644 index 00000000000..dd866036784 --- /dev/null +++ b/centreon-clib/packaging/rpm/debian/centreon-clib.triggers @@ -0,0 +1 @@ +activate-noawait ldconfig diff --git a/centreon-clib/packaging/rpm/debian/changelog.in b/centreon-clib/packaging/rpm/debian/changelog.in new file mode 100644 index 00000000000..a37d2dc1a0a --- /dev/null +++ b/centreon-clib/packaging/rpm/debian/changelog.in @@ -0,0 +1,5 @@ +centreon-clib (@VERSION@-@RELEASE@) UNRELEASED; urgency=medium + + * Release. + + -- Matthieu Kermagoret Thu, 13 Jul 2017 10:40:36 +0200 diff --git a/centreon-clib/packaging/rpm/debian/compat b/centreon-clib/packaging/rpm/debian/compat new file mode 100644 index 00000000000..f599e28b8ab --- /dev/null +++ b/centreon-clib/packaging/rpm/debian/compat @@ -0,0 +1 @@ +10 diff --git a/centreon-clib/packaging/rpm/debian/control b/centreon-clib/packaging/rpm/debian/control new file mode 100644 index 00000000000..2bf13586aa7 --- /dev/null +++ b/centreon-clib/packaging/rpm/debian/control @@ -0,0 +1,13 @@ +Source: centreon-clib +Section: net +Priority: optional +Maintainer: Matthieu Kermagoret +Build-Depends: debhelper (>=10), cmake, lsb-base, make (>=3) +Standards-Version: 3.9.8 +Homepage: https://github.com/centreon/centreon-clib + +Package: centreon-clib +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends} +Description: Common C++ library + for the Centreon software suite. diff --git a/centreon-clib/packaging/rpm/debian/copyright b/centreon-clib/packaging/rpm/debian/copyright new file mode 100644 index 00000000000..50dba506d4e --- /dev/null +++ b/centreon-clib/packaging/rpm/debian/copyright @@ -0,0 +1 @@ +See /usr/share/common-licenses/Apache-2.0 diff --git a/centreon-clib/packaging/rpm/debian/rules b/centreon-clib/packaging/rpm/debian/rules new file mode 100755 index 00000000000..07c961754d5 --- /dev/null +++ b/centreon-clib/packaging/rpm/debian/rules @@ -0,0 +1,16 @@ +#!/usr/bin/make -f + +export DH_VERBOSE=1 +USE_CXX11=$(shell grep -q "ABI=1" CMakeLists.txt && echo -n 1 || echo -n 0) + +%: + dh $@ + +override_dh_auto_configure: + cmake -DWITH_PREFIX=/usr -DUSE_CXX11_ABI=$(USE_CXX11) . + +override_dh_auto_build: + make + +override_dh_auto_install: + make install DESTDIR=debian/centreon-clib diff --git a/centreon-clib/packaging/rpm/debian/source/format b/centreon-clib/packaging/rpm/debian/source/format new file mode 100644 index 00000000000..163aaf8d82b --- /dev/null +++ b/centreon-clib/packaging/rpm/debian/source/format @@ -0,0 +1 @@ +3.0 (quilt) diff --git a/centreon-clib/packaging/script/rpmbuild.sh b/centreon-clib/packaging/script/rpmbuild.sh new file mode 100755 index 00000000000..2dbad78acf9 --- /dev/null +++ b/centreon-clib/packaging/script/rpmbuild.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +show_help() { +cat << EOF +Usage: ${0##*/} -n=[yes|no] -v + +This program build Centreon-clib + + -v : major version + -r : release number + -h : help +EOF +exit 2 +} + +VERSION=$1 +RELEASE=$2 + +if [ -z $VERSION ] || [ -z $RELEASE ] ; then + echo "Some or all of the parameters are empty"; + echo $VERSION; + echo $RELEASE; + show_help +fi + +ln -s /usr/bin/cmake3 /usr/bin/cmake + +# dossier racine du nouveau centreon collect +if [ ! -d /root/rpmbuild/SOURCES ] ; then + mkdir -p /root/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} +fi + +cd "../../../" + +mkdir centreon-clib-$VERSION +cp -r centreon-clib/* centreon-clib-$VERSION +tar -czf centreon-clib-$VERSION.tar.gz centreon-clib-$VERSION cmake.sh +mv centreon-clib-$VERSION.tar.gz /root/rpmbuild/SOURCES/ +rm -rf centreon-clib-$VERSION + +rpmbuild -ba centreon-clib/packaging/rpm/centreon-clib.spectemplate -D "VERSION $VERSION" -D "RELEASE $RELEASE" + diff --git a/centreon-clib/test/CMakeLists.txt b/centreon-clib/test/CMakeLists.txt index 9162d43e522..3d08192f8e4 100644 --- a/centreon-clib/test/CMakeLists.txt +++ b/centreon-clib/test/CMakeLists.txt @@ -1,3 +1,4 @@ +find_package(GTest REQUIRED) include_directories(${GTest_INCLUDE_DIRS}) link_directories(${GTest_LIB_DIRS}) add_executable(bin_test_process_output ${PROJECT_SOURCE_DIR}/test/bin_test_process_output.cc) @@ -33,4 +34,4 @@ if (WITH_COVERAGE) set(GCOV gcov) endif () add_test(NAME tests COMMAND ut-clib) -target_link_libraries(ut-clib ${GTest_LIBS} pthread centreon_clib) +target_link_libraries(ut-clib ${GTest_LIBS} pthread centreon_clib_shared) diff --git a/centreon-clib/test/handle_manager.cc b/centreon-clib/test/handle_manager.cc index 9501adc33a6..75380fd6bf4 100644 --- a/centreon-clib/test/handle_manager.cc +++ b/centreon-clib/test/handle_manager.cc @@ -215,7 +215,7 @@ TEST(ClibHandleManager, RemoveByHandleListener) { io::file_stream fs1(stdin); hm.add(&fs1, &l); - ASSERT_EQ(hm.remove(&l), 1u); + ASSERT_EQ(hm.remove(&l), 1); hm.add(&fs1, &l); io::file_stream fs2(stdout); @@ -223,5 +223,5 @@ TEST(ClibHandleManager, RemoveByHandleListener) { io::file_stream fs3(stderr); hm.add(&fs3, &l); - ASSERT_EQ(hm.remove(&l), 3u); + ASSERT_EQ(hm.remove(&l), 3); } diff --git a/centreon-clib/test/logging.cc b/centreon-clib/test/logging.cc index 8560e6632d9..3d04f9092bf 100644 --- a/centreon-clib/test/logging.cc +++ b/centreon-clib/test/logging.cc @@ -288,9 +288,9 @@ TEST(ClibLogging, EngineRemoveByBackend) { std::unique_ptr obj(new backend_test); e.add(obj.get(), 1, 0); - ASSERT_EQ(e.remove(obj.get()), 1u); + ASSERT_EQ(e.remove(obj.get()), 1); - constexpr uint32_t nb_backend{1000}; + static unsigned int const nb_backend(1000); for (unsigned int i(1); i < nb_backend; ++i) e.add(obj.get(), i, 0); diff --git a/centreon-clib/test/task_manager.cc b/centreon-clib/test/task_manager.cc index b987bba4679..11a7045235f 100644 --- a/centreon-clib/test/task_manager.cc +++ b/centreon-clib/test/task_manager.cc @@ -73,7 +73,7 @@ TEST(ClibTaskManager, Execute) { tm.add(t1, timestamp::now(), true, true); ASSERT_TRUE(tm.next_execution_time().to_useconds()); - ASSERT_EQ(tm.execute(timestamp::now()), 1u); + ASSERT_EQ(tm.execute(timestamp::now()), 1); task_test* t2(new task_test); tm.add(t2, timestamp(), false, false); @@ -81,7 +81,7 @@ TEST(ClibTaskManager, Execute) { tm.add(t2, timestamp(), false, false); tm.add(t2, timestamp(), false, false); - ASSERT_EQ(tm.execute(timestamp::now()), 4u); + ASSERT_EQ(tm.execute(timestamp::now()), 4); timestamp future(timestamp::now()); future.add_seconds(42); @@ -97,9 +97,9 @@ TEST(ClibTaskManager, ExecuteRecurring) { task_test* t1(new task_test); tm.add(t1, timestamp(), 1, true, true); - ASSERT_EQ(tm.execute(timestamp::now()), 1u); - ASSERT_EQ(tm.execute(timestamp::now()), 1u); - ASSERT_EQ(tm.execute(timestamp::now()), 1u); + ASSERT_EQ(tm.execute(timestamp::now()), 1); + ASSERT_EQ(tm.execute(timestamp::now()), 1); + ASSERT_EQ(tm.execute(timestamp::now()), 1); } { @@ -111,9 +111,9 @@ TEST(ClibTaskManager, ExecuteRecurring) { tm.add(t2, timestamp(), 1, false, false); tm.add(t2, timestamp(), 1, false, false); - ASSERT_EQ(tm.execute(timestamp::now()), 4u); - ASSERT_EQ(tm.execute(timestamp::now()), 4u); - ASSERT_EQ(tm.execute(timestamp::now()), 4u); + ASSERT_EQ(tm.execute(timestamp::now()), 4); + ASSERT_EQ(tm.execute(timestamp::now()), 4); + ASSERT_EQ(tm.execute(timestamp::now()), 4); delete t2; } @@ -171,14 +171,14 @@ TEST(ClibTaskManager, RemoveByTask) { task_test none; ASSERT_FALSE(tm.remove(&none)); - ASSERT_EQ(tm.remove(t1), 1u); + ASSERT_EQ(tm.remove(t1), 1); task_test* t2(new task_test); tm.add(t2, timestamp::now(), false, false); tm.add(t2, timestamp::now(), false, false); tm.add(t2, timestamp::now(), false, false); tm.add(t2, timestamp::now(), false, false); - ASSERT_EQ(tm.remove(t2), 4u); + ASSERT_EQ(tm.remove(t2), 4); delete t2; ASSERT_FALSE(tm.remove(reinterpret_cast(0x4242))); diff --git a/centreon-connector/CMakeLists.txt b/centreon-connector/CMakeLists.txt index e07772aa1f3..f1901c0a4e6 100644 --- a/centreon-connector/CMakeLists.txt +++ b/centreon-connector/CMakeLists.txt @@ -1,15 +1,28 @@ # Global options. +cmake_minimum_required(VERSION 2.8.12) project(connectors CXX) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") +add_definitions("-D_GLIBCXX_USE_CXX11_ABI=1") -set(CONNECTOR_VERSION "${COLLECT_MAJOR}.${COLLECT_MINOR}.${COLLECT_PATCH}") +set(CONNECTOR_MAJOR 21) +set(CONNECTOR_MINOR 10) +set(CONNECTOR_PATCH 0) +set(CONNECTOR_VERSION "${CONNECTOR_MAJOR}.${CONNECTOR_MINOR}.${CONNECTOR_PATCH}") add_definitions(-DCENTREON_CONNECTOR_VERSION=\"${CONNECTOR_VERSION}\") +include(${PROJECT_SOURCE_DIR}/cmake/Findclib.cmake) include(${PROJECT_SOURCE_DIR}/cmake/FindSSH.cmake) include(${PROJECT_SOURCE_DIR}/cmake/Findperl.cmake) include(${CMAKE_BINARY_DIR}/conan_paths.cmake) +find_package(fmt REQUIRED) +find_package(spdlog REQUIRED) + +add_definitions(${spdlog_DEFINITIONS}) + +include_directories(${fmt_INCLUDE_DIRS}) +include_directories(${spdlog_INCLUDE_DIRS}) -set(PREFIX_CONNECTORS "${CMAKE_INSTALL_PREFIX}/lib64/centreon-connector/") # Generate code to dynamically load modules. # Disable some warnings generated by Embedded Perl. @@ -24,14 +37,16 @@ endif () # We will use pkg-config if available. include_directories(${PROJECT_SOURCE_DIR}/common/inc) -include_directories(${CMAKE_SOURCE_DIR}/centreon-clib/inc) add_subdirectory(perl) add_subdirectory(ssh) link_directories(${CMAKE_SOURCE_DIR}/build/centreon-clib/) # Testing. +option(WITH_TESTING "Build unit tests." OFF) if (WITH_TESTING) + find_package(GTest REQUIRED) + set_source_files_properties(${PROJECT_SOURCE_DIR}/perl/src/xs_init.cc PROPERTIES GENERATED TRUE) include_directories(${GTest_INCLUDE_DIRS}) include_directories(/usr/lib64/perl5/CORE) @@ -72,7 +87,7 @@ if (WITH_TESTING) ${PROJECT_SOURCE_DIR}/ssh/test/sessions.cc ) add_dependencies(ut_connector centreon_connector_perl) - add_dependencies(ut_connector centreon_clib) + add_dependencies(ut_connector centreon_clib_shared) target_link_libraries(ut_connector ${GTest_LIBS} centreon_clib ${PERL_LIBRARIES} ${fmt_LIBS} ${spdlog_LIBS} ${LIBSSH2_LIBRARIES}) endif (WITH_TESTING) diff --git a/centreon-connector/cmake/Findclib.cmake b/centreon-connector/cmake/Findclib.cmake new file mode 100644 index 00000000000..cdb084073c2 --- /dev/null +++ b/centreon-connector/cmake/Findclib.cmake @@ -0,0 +1,51 @@ +# Find Centreon Clib's headers. +include(FindPkgConfig) +if (PKG_CONFIG_FOUND) + pkg_check_modules(CLIB QUIET "centreon-clib") # Will be used below. +endif (PKG_CONFIG_FOUND) + +if (WITH_CENTREON_CLIB_INCLUDE_DIR) + find_file( + CLIB_HEADER_FOUND + "com/centreon/clib/version.hh" + PATHS "${WITH_CENTREON_CLIB_INCLUDE_DIR}" + NO_DEFAULT_PATH) + if (NOT CLIB_HEADER_FOUND) + message(FATAL_ERROR "Could not find Centreon Clib's headers in ${WITH_CENTREON_CLIB_INCLUDE_DIR}.") + endif () + include_directories("${WITH_CENTREON_CLIB_INCLUDE_DIR}") + set(CLIB_INCLUDE_DIR "${WITH_CENTREON_CLIB_INCLUDE_DIR}") +elseif (CLIB_FOUND) # Was Centreon Clib detected with pkg-config ? + if (CMAKE_CXX_FLAGS) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CLIB_CFLAGS}") + else () + set(CMAKE_CXX_FLAGS "${CLIB_CFLAGS}") + endif () +else () + find_path(CLIB_INCLUDE_DIR "com/centreon/clib/version.hh" PATH_SUFFIXES "centreon-clib") + if (NOT CLIB_INCLUDE_DIR) + message(FATAL_ERROR "Could not find Centreon Clib's headers (try WITH_CENTREON_CLIB_INCLUDE_DIR).") + endif () + include_directories("${CLIB_INCLUDE_DIR}") +endif () + +# Find Centreon Clib's library. +if (WITH_CENTREON_CLIB_LIBRARIES) + set(CLIB_LIBRARIES "${WITH_CENTREON_CLIB_LIBRARIES}") +elseif (WITH_CENTREON_CLIB_LIBRARY_DIR) + find_library( + CLIB_LIBRARIES + "centreon_clib" + PATHS "${WITH_CENTREON_CLIB_LIBRARY_DIR}" + NO_DEFAULT_PATH) + if (NOT CLIB_LIBRARIES) + message(FATAL_ERROR "Could not find Centreon Clib's library in ${WITH_CENTREON_CLIB_LIBRARY_DIR}.") + endif () +elseif (CLIB_FOUND) # Was Centreon Clib detected with pkg-config ? + set(CLIB_LIBRARIES "${CLIB_LDFLAGS}") +else () + find_library(CLIB_LIBRARIES "centreon_clib") + if (NOT CLIB_LIBRARIES) + message(FATAL_ERROR "Could not find Centreon Clib's library (try WITH_CENTREON_CLIB_LIBRARY_DIR or WITH_CENTREON_CLIB_LIBRARIES).") + endif () +endif () \ No newline at end of file diff --git a/centreon-connector/common/inc/com/centreon/connector/namespace.hh b/centreon-connector/common/inc/com/centreon/connector/namespace.hh index c2846ab6b74..e130f6c94a4 100644 --- a/centreon-connector/common/inc/com/centreon/connector/namespace.hh +++ b/centreon-connector/common/inc/com/centreon/connector/namespace.hh @@ -23,16 +23,16 @@ #undef CCC_BEGIN #endif // CCC_BEGIN #define CCC_BEGIN() \ - namespace com { \ - namespace centreon { \ - namespace connector { + namespace com { \ + namespace centreon { \ + namespace connector { \ #ifdef CCC_END #undef CCC_END #endif // CCC_END #define CCC_END() \ - } \ - } \ + } \ + } \ } #endif // !CCC_NAMESPACE_HH diff --git a/centreon-connector/common/src/log.cc b/centreon-connector/common/src/log.cc index 0347ea998f8..c80214797c1 100644 --- a/centreon-connector/common/src/log.cc +++ b/centreon-connector/common/src/log.cc @@ -32,7 +32,8 @@ log::log() { _core_log->flush_on(spdlog::level::trace); } -log::~log() {} +log::~log() { +} com::centreon::connector::log& log::instance() { static log instance; diff --git a/centreon-connector/packaging/rpm/centreon-connector.spectemplate b/centreon-connector/packaging/rpm/centreon-connector.spectemplate new file mode 100644 index 00000000000..0f8d33b5d4e --- /dev/null +++ b/centreon-connector/packaging/rpm/centreon-connector.spectemplate @@ -0,0 +1,153 @@ +## +## Copyright 2011-2015,2017-2020 Centreon +## + +%if 0%{?suse_version} +%define group "System/Monitoring" +%else +%define group "Applications/System" +%endif +%define user centreon-engine + +Name: centreon-connector +Version: %{VERSION} +Release: %{RELEASE}%{?dist} +Summary: Centreon Connector provide some tools for Centreon Engine to monitoring and management system. +%define thismajor 22.04.0 +%define nextmajor 22.05.0 + +Group: %{group} +License: ASL 2.0 +URL: https://github.com/centreon/centreon-connectors +Packager: Matthieu Kermagoret +Vendor: Centreon Entreprise Server (CES) Repository, http://yum.centreon.com/standard/ + +Source0: %{name}-%{version}.tar.gz +BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root + +BuildRequires: cmake3 >= 3.15 + +BuildRequires: gcc +BuildRequires: gcc-c++ +BuildRequires: make +BuildRequires: centreon-clib-devel >= %{thismajor} +BuildRequires: centreon-clib-devel < %{nextmajor} +BuildRequires: libssh2-devel >= 1.4 +BuildRequires: libgcrypt-devel +BuildRequires: perl +BuildRequires: perl-devel +BuildRequires: perl-ExtUtils-Embed +Requires: %{name}-perl = %{version}-%{release} +Requires: %{name}-ssh = %{version}-%{release} + +%description +Centreon Connector provide a monitoring tools, compatible with +Centreon-Engine configuration, designed to monitor and manage system. + +%package perl +Summary: Centreon Connector Perl provide embedded perl for Centreon-Engine. +Group: %{group} +Requires: centreon-clib >= %{thismajor} +Requires: centreon-clib < %{nextmajor} +Requires: perl + +%description perl +Centreon Connector Perl provide embedded perl for Centreon Engine +a monitoring engine. + +%package ssh +Summary: Centreon Connector SSH provide persistante connection between checks. +Group: %{group} +Requires: centreon-clib >= %{thismajor} +Requires: centreon-clib < %{nextmajor} +Requires: libssh2 >= 1.4 +Requires: libgcrypt + +%description ssh +Centreon Connector SSH provide persistante connection between checks. + +%prep +%setup + +%build +pip3 install conan --upgrade +cpp11=$(gcc --version | awk '/gcc/ && ($3+0)>5.0{print 1}') +if [ $cpp11 -eq 1 ] ; then + conan install . -s compiler.libcxx=libstdc++11 --build=missing +else + conan install . -s compiler.libcxx=libstdc++ +fi + +CXXFLAGS="-DNDEBUG -g -O2 -std=c++11 -Wno-long-long" cmake3 \ + -DWITH_PREFIX=%{_prefix} \ + -DWITH_PREFIX_BINARY=%{_libdir}/centreon-connector \ + -DWITH_TESTING=0 . +%{__make} %{?jobs:-j%jobs} %{?_smp_mflags} VERBOSE="1" + +%install +%{__make} install DESTDIR="$RPM_BUILD_ROOT" + +%clean +%{__rm} -rf %{buildroot} + +%pre + +%files + +%files perl +%attr(0775,root,root) %{_libdir}/centreon-connector/centreon_connector_perl + +%files ssh +%attr(0775,root,root) %{_libdir}/centreon-connector/centreon_connector_ssh + +%changelog +* Tue Sep 29 2015 Matthieu Kermagoret 1.1.2-3 +- Connector Perl requires perl-devel to build on CentOS 7. + +* Tue Sep 29 2015 Matthieu Kermagoret 1.1.2-2 +- Connector Perl requires perl-libs to build. + +* Thu Sep 10 2015 Matthieu Kermagoret 1.1.2-1 +- Discard SSH sessions when host is not responding. + +* Thu Oct 02 2014 Matthieu Kermagoret 1.1.1-2 +- Do not add invalid FD to the list of FD to close. + +* Thu Sep 04 2014 Matthieu Kermagoret 1.1.1-1 +- Do not leak file descriptors to children. + +* Mon Aug 11 2014 Matthieu Kermagoret 1.1.0-1 +- Ability to run some Perl code from command-line. + +* Thu Jul 10 2014 Matthieu Kermagoret 1.0.3-2 +- Compatibility with Centreon Clib 1.4 (simultaneous release of Clib 1.4.0 and Engine 1.3.9). + +* Mon Jul 07 2014 Matthieu Kermagoret 1.0.3-1 +- Restored compatibility with Centreon Clib 1.2. +- Print Connector SSH errors in proper output. +- Handle check_by_ssh timeout argument properly. + +* Thu Jun 26 2014 Matthieu Kermagoret 1.0.2-5 +- Compatibility with Centreon Clib 1.4. + +* Thu May 22 2014 Matthieu Kermagoret 1.0.2-4 +- Compatibility with Centreon Clib 1.3. + +* Fri Nov 29 2013 Dorian Guillois 1.0.2-2 +- Fix centreon ssh connector segfault. + +* Fri Nov 29 2013 Dorian Guillois 1.0.2-1 +- Fix centreon ssh connector segfault. + +* Thu Oct 17 2013 Dorian Guillois 1.0.1-2 +- Change centreon-connector spec to use the new cmake package. + +* Mon Sep 30 2013 Dorian Guillois 1.0.1-1 +- Update to the 1.2 branch of Centreon Clib. +- Fix some compilation issues. + +* Tue Mar 05 2013 Maximilien Bersoult 1.0.0-7 +- Use macro for cmake dependancies in CES 2.2 and CES 3.0, prepare for OpenSuSE + +* Mon Aug 20 2012 Dorian Guillois 1.0.0-1 +- Initial build. diff --git a/centreon-connector/packaging/script/rpmbuild.sh b/centreon-connector/packaging/script/rpmbuild.sh new file mode 100755 index 00000000000..00da07080bb --- /dev/null +++ b/centreon-connector/packaging/script/rpmbuild.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +show_help() { +cat << EOF +Usage: ${0##*/} -n=[yes|no] -v + +This program build Centreon-connector + + -v : major version + -r : release number + -h : help +EOF +exit 2 +} + +VERSION=$1 +RELEASE=$2 + +if [ -z $VERSION ] || [ -z $RELEASE ] ; then + echo "Some or all of the parameters are empty"; + echo $VERSION; + echo $RELEASE; + show_help +fi + +ln -s /usr/bin/cmake3 /usr/bin/cmake + +# dossier racine du nouveau centreon collect +if [ ! -d /root/rpmbuild/SOURCES ] ; then + mkdir -p /root/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} +fi + +cd "../../../" + +mkdir centreon-connector-$VERSION +cp -r centreon-connector/* centreon-connector-$VERSION +tar -czf centreon-connector-$VERSION.tar.gz centreon-connector-$VERSION cmake.sh +mv centreon-connector-$VERSION.tar.gz /root/rpmbuild/SOURCES/ +rm -rf centreon-connector-$VERSION + +rpmbuild -ba centreon-connector/packaging/rpm/centreon-connector.spectemplate -D "VERSION $VERSION" -D "RELEASE $RELEASE" + diff --git a/centreon-connector/perl/CMakeLists.txt b/centreon-connector/perl/CMakeLists.txt index d78ec54d8cb..e3df077406b 100644 --- a/centreon-connector/perl/CMakeLists.txt +++ b/centreon-connector/perl/CMakeLists.txt @@ -54,11 +54,22 @@ add_executable(centreon_connector_perl ${PROJECT_SOURCE_DIR}/perl/inc/com/centreon/connector/perl/policy.hh ${PROJECT_SOURCE_DIR}/perl/inc/com/centreon/connector/perl/reporter.hh ) -add_dependencies(centreon_connector_perl centreon_clib) +add_dependencies(centreon_connector_perl centreon_clib_shared) target_link_libraries(centreon_connector_perl centreon_clib ${PERL_LIBRARIES} ${spdlog_LIBS} ${fmt_LIBS} pthread) + +# Installation path. +if (WITH_PREFIX) + set(CMAKE_INSTALL_PREFIX "${WITH_PREFIX}") +endif () +if (WITH_PREFIX_BINARY) + set(PREFIX_BINARY "${WITH_PREFIX_BINARY}") +else () + set(PREFIX_BINARY "${CMAKE_INSTALL_PREFIX}/bin") +endif () + # Install rules. -install(TARGETS centreon_connector_perl RUNTIME DESTINATION ${PREFIX_CONNECTORS}) +install(TARGETS centreon_connector_perl RUNTIME DESTINATION ${PREFIX_BINARY}) # Code coverage on unit tests option(WITH_COVERAGE "Add code coverage on unit tests." OFF) diff --git a/centreon-connector/perl/inc/com/centreon/connector/perl/checks/check.hh b/centreon-connector/perl/inc/com/centreon/connector/perl/checks/check.hh index 1a458640f49..16e32896937 100644 --- a/centreon-connector/perl/inc/com/centreon/connector/perl/checks/check.hh +++ b/centreon-connector/perl/inc/com/centreon/connector/perl/checks/check.hh @@ -46,7 +46,9 @@ class check : public handle_listener { check(check const& c) = delete; check& operator=(check const& c) = delete; void error(handle& h) override; - pid_t execute(uint64_t cmd_id, std::string const& cmd, const timestamp& tmt); + pid_t execute(uint64_t cmd_id, + std::string const& cmd, + const timestamp& tmt); void listen(listener* listnr); void on_timeout(bool final = true); void read(handle& h) override; @@ -56,6 +58,7 @@ class check : public handle_listener { void write(handle& h) override; private: + void _send_result_and_unregister(result const& r); pid_t _child; diff --git a/centreon-connector/perl/inc/com/centreon/connector/perl/options.hh b/centreon-connector/perl/inc/com/centreon/connector/perl/options.hh index 16e46d71306..6d4be97442c 100644 --- a/centreon-connector/perl/inc/com/centreon/connector/perl/options.hh +++ b/centreon-connector/perl/inc/com/centreon/connector/perl/options.hh @@ -31,8 +31,8 @@ CCCP_BEGIN() * Parse and expose command line arguments. */ class options : public com::centreon::misc::get_options { - void _init(); + void _init(); public: options(); ~options() noexcept override; diff --git a/centreon-connector/perl/inc/com/centreon/connector/perl/orders/parser.hh b/centreon-connector/perl/inc/com/centreon/connector/perl/orders/parser.hh index 33fcc599362..2fa1abf6ef6 100644 --- a/centreon-connector/perl/inc/com/centreon/connector/perl/orders/parser.hh +++ b/centreon-connector/perl/inc/com/centreon/connector/perl/orders/parser.hh @@ -38,7 +38,7 @@ namespace orders { class parser : public handle_listener { public: parser(); - ~parser() override = default; + ~parser() override = default ; parser(parser const& p) = delete; parser& operator=(parser const& p) = delete; void error(handle& h) override; diff --git a/centreon-connector/perl/src/checks/check.cc b/centreon-connector/perl/src/checks/check.cc index 16db96aa977..066bfb3c3ea 100644 --- a/centreon-connector/perl/src/checks/check.cc +++ b/centreon-connector/perl/src/checks/check.cc @@ -89,7 +89,8 @@ pid_t check::execute(uint64_t cmd_id, _err.set_fd(fds[2]); // Store command ID. - log::core()->debug("check {0} has ID {1}", static_cast(this), cmd_id); + log::core()->debug("check {0} has ID {1}", static_cast(this), + cmd_id); _cmd_id = cmd_id; // Register with multiplexer. @@ -111,8 +112,8 @@ pid_t check::execute(uint64_t cmd_id, * @param[in] listnr New listener. */ void check::listen(listener* listnr) { - log::core()->debug("check {0} is listened by {1}", static_cast(this), - static_cast(listnr)); + log::core()->debug("check {0} is listened by {1}", + static_cast(this), static_cast(listnr)); _listnr = listnr; } @@ -211,7 +212,7 @@ void check::terminated(int exit_code) { */ void check::unlisten(listener* listnr) { log::core()->debug("listener {0} stops listening check {1}", - static_cast(_listnr), static_cast(this)); + static_cast(_listnr), static_cast(this)); _listnr = nullptr; } diff --git a/centreon-connector/perl/src/embedded_perl.cc b/centreon-connector/perl/src/embedded_perl.cc index 46d2c7a3f37..6c14e79540a 100644 --- a/centreon-connector/perl/src/embedded_perl.cc +++ b/centreon-connector/perl/src/embedded_perl.cc @@ -16,10 +16,11 @@ ** For more information : contact@centreon.com */ -#include "com/centreon/connector/perl/embedded_perl.hh" -#include "com/centreon/connector/log.hh" + #include "com/centreon/connector/perl/pipe_handle.hh" #include "com/centreon/exceptions/basic.hh" +#include "com/centreon/connector/log.hh" +#include "com/centreon/connector/perl/embedded_perl.hh" #include #include diff --git a/centreon-connector/perl/src/main.cc b/centreon-connector/perl/src/main.cc index 6db06f61cca..43432275d51 100644 --- a/centreon-connector/perl/src/main.cc +++ b/centreon-connector/perl/src/main.cc @@ -100,7 +100,7 @@ int main(int argc, char** argv, char** env) { log::instance().set_level(spdlog::level::info); } log::core()->info("Centreon Perl Connector {} starting", - CENTREON_CONNECTOR_VERSION); + CENTREON_CONNECTOR_VERSION); // Set termination handler. log::core()->debug("installing termination handler"); diff --git a/centreon-connector/perl/src/multiplexer.cc b/centreon-connector/perl/src/multiplexer.cc index 30db92017ea..d63b9a9050a 100644 --- a/centreon-connector/perl/src/multiplexer.cc +++ b/centreon-connector/perl/src/multiplexer.cc @@ -34,9 +34,7 @@ static multiplexer* _instance = nullptr; * * @return multiplexer instance. */ -multiplexer& multiplexer::instance() noexcept { - return *_instance; -} +multiplexer& multiplexer::instance() noexcept { return *_instance; } /** * Load singleton. diff --git a/centreon-connector/perl/src/policy.cc b/centreon-connector/perl/src/policy.cc index 3c6a9f5da5c..663d8c8818d 100644 --- a/centreon-connector/perl/src/policy.cc +++ b/centreon-connector/perl/src/policy.cc @@ -73,8 +73,7 @@ policy::~policy() throw() { for (auto it = _checks.begin(), end = _checks.end(); it != end; ++it) { try { it->second->unlisten(this); - } catch (...) { - } + } catch (...) { } delete it->second; } _checks.clear(); @@ -149,8 +148,7 @@ void policy::on_result(checks::result const& r) { */ void policy::on_version() { // Report version 1.0. - log::core()->info( - "monitoring engine requested protocol version, sending 1.0"); + log::core()->info("monitoring engine requested protocol version, sending 1.0"); _reporter.send_version(1, 0); } @@ -179,8 +177,7 @@ bool policy::run() { std::unique_ptr chk(it->second); _checks.erase(it); if (WIFSIGNALED(status)) { - log::core()->error("process {0} exited because of a signal {1}", - child, WTERMSIG(status)); + log::core()->error("process {0} exited because of a signal {1}", child, WTERMSIG(status)); } chk->terminated(WIFEXITED(status) ? WEXITSTATUS(status) : -1); diff --git a/centreon-connector/perl/src/reporter.cc b/centreon-connector/perl/src/reporter.cc index e1c37e98d96..4daec1bb10d 100644 --- a/centreon-connector/perl/src/reporter.cc +++ b/centreon-connector/perl/src/reporter.cc @@ -42,8 +42,8 @@ reporter::reporter() : _can_report(true), _reported(0) {} * Destructor. */ reporter::~reporter() noexcept { - log::core()->info("connector reporter {} check results to monitoring engine", - _reported); + log::core()->info( + "connector reporter {} check results to monitoring engine", _reported); } /** @@ -75,7 +75,7 @@ void reporter::send_result(checks::result const& r) { // Update statistics. ++_reported; log::core()->debug("reporting check result #{0} (check {1})", _reported, - r.get_command_id()); + r.get_command_id()); // Build packet. std::ostringstream oss; @@ -117,8 +117,7 @@ void reporter::send_result(checks::result const& r) { */ void reporter::send_version(unsigned int major, unsigned int minor) { // Build packet. - log::core()->debug("sending protocol version {0}.{1} to monitoring engine", - major, minor); + log::core()->debug("sending protocol version {0}.{1} to monitoring engine", major, minor); std::ostringstream oss; oss << "1"; oss.put('\0'); diff --git a/centreon-connector/perl/test/connector.cc b/centreon-connector/perl/test/connector.cc index c6d83fc2aef..8035a5c7afb 100644 --- a/centreon-connector/perl/test/connector.cc +++ b/centreon-connector/perl/test/connector.cc @@ -26,8 +26,7 @@ #include "com/centreon/process.hh" using namespace com::centreon; -static std::string perl_connector = - BUILD_PATH "/centreon-connector/perl/centreon_connector_perl"; +static std::string perl_connector = BUILD_PATH "/centreon-connector/perl/centreon_connector_perl"; static constexpr const char cmd1[] = "2\x00" @@ -70,12 +69,11 @@ static constexpr const char scripts[] = " \0" \ " \0\0\0\0" -#define TimeoutKillCMD \ - "2\0" \ - "4242\0" \ - "3\0" \ - "123456789\0" BUILD_PATH \ - "/../centreon-connector/perl/test/timeout_kill.pl\0\0\0\0" +#define TimeoutKillCMD \ + "2\0" \ + "4242\0" \ + "3\0" \ + "123456789\0" BUILD_PATH "/../centreon-connector/perl/test/timeout_kill.pl\0\0\0\0" #define TimeoutKillRESULT \ "3\0" \ "4242\0" \ @@ -84,12 +82,11 @@ static constexpr const char scripts[] = " \0" \ " \0\0\0\0" -#define TimeoutTermCMD \ - "2\0" \ - "4242\0" \ - "3\0" \ - "123456789\0" BUILD_PATH \ - "/../centreon-connector/perl/test/timeout_term.pl\0\0\0\0" +#define TimeoutTermCMD \ + "2\0" \ + "4242\0" \ + "3\0" \ + "123456789\0" BUILD_PATH "/../centreon-connector/perl/test/timeout_term.pl\0\0\0\0" class TestConnector : public testing::Test { public: @@ -135,8 +132,8 @@ class TestConnector : public testing::Test { } static void _write_file(char const* filename, - char const* content, - unsigned int size = 0) { + char const* content, + unsigned int size = 0) { // Check size. if (!size) size = strlen(content); @@ -212,7 +209,7 @@ TEST_F(TestConnector, ExecuteModuleLoading) { TEST_F(TestConnector, ExecuteMultipleScripts) { // Write Perl scripts. std::string script_paths[10]; - for (auto& script_path : script_paths) { + for (auto & script_path : script_paths) { script_path = io::file_stream::temp_path(); _write_file(script_path.c_str(), scripts, sizeof(scripts) - 1); } @@ -241,7 +238,7 @@ TEST_F(TestConnector, ExecuteMultipleScripts) { int retval{wait_for_termination()}; // Remove temporary files. - for (auto& script_path : script_paths) + for (auto & script_path : script_paths) remove(script_path.c_str()); unsigned int nb_right_output(0); @@ -325,10 +322,11 @@ TEST_F(TestConnector, ExecuteSingleScriptLogFile) { std::ifstream file("/tmp/log_file"); ASSERT_TRUE(file.is_open()); std::string line((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + std::istreambuf_iterator()); ASSERT_NE( - line.find("[info] Centreon Perl Connector " CENTREON_CONNECTOR_VERSION - " starting"), + line.find( + "[info] Centreon Perl Connector " CENTREON_CONNECTOR_VERSION + " starting"), std::string::npos); file.close(); } @@ -344,9 +342,10 @@ TEST_F(TestConnector, ExecuteWithAdditionalCode) { "exit 0;\n"); // Process. - p.exec(perl_connector + - " --code 'package Centreon::Test; our $company=\"Centreon\"; our " - "$attribute=\"wonderful\";'"); + p.exec( + perl_connector + + " --code 'package Centreon::Test; our $company=\"Centreon\"; our " + "$attribute=\"wonderful\";'"); // Write command. std::ostringstream oss; diff --git a/centreon-connector/perl/test/embedded_perl.cc b/centreon-connector/perl/test/embedded_perl.cc index 36036425afc..90ecb0a082e 100644 --- a/centreon-connector/perl/test/embedded_perl.cc +++ b/centreon-connector/perl/test/embedded_perl.cc @@ -17,7 +17,6 @@ * */ -/* Be careful! gtest.h must be included before embedded_perl.hh */ #include #include "com/centreon/connector/perl/embedded_perl.hh" diff --git a/centreon-connector/perl/test/main.cc b/centreon-connector/perl/test/main.cc index 39ce2c7d029..30b109926d6 100644 --- a/centreon-connector/perl/test/main.cc +++ b/centreon-connector/perl/test/main.cc @@ -16,8 +16,8 @@ * For more information : contact@centreon.com * */ -#include #include +#include #include #include "com/centreon/connector/perl/embedded_perl.hh" @@ -33,7 +33,7 @@ using namespace com::centreon::connector::perl; * * @return 0 on success, any other value on failure. */ -int main(int argc, char* argv[], char** env) { +int main(int argc, char* argv[], char **env) { // GTest initialization. testing::InitGoogleTest(&argc, argv); PERL_SYS_INIT3(&argc, &argv, &env); diff --git a/centreon-connector/ssh/CMakeLists.txt b/centreon-connector/ssh/CMakeLists.txt index 28f1941422a..3f99a7099b4 100644 --- a/centreon-connector/ssh/CMakeLists.txt +++ b/centreon-connector/ssh/CMakeLists.txt @@ -59,12 +59,23 @@ add_executable(centreon_connector_ssh ${PROJECT_SOURCE_DIR}/ssh/inc/com/centreon/connector/ssh/sessions/session.hh ${PROJECT_SOURCE_DIR}/ssh/inc/com/centreon/connector/ssh/sessions/socket_handle.hh ) -add_dependencies(centreon_connector_ssh centreon_clib) +add_dependencies(centreon_connector_ssh centreon_clib_shared) target_link_libraries(centreon_connector_ssh ${LIBSSH2_LIBRARIES} centreon_clib ${LIBGCRYPT_LIBRARIES} ${spdlog_LIBS} ${fmt_LIBS} pthread) + +# Installation path. +if (WITH_PREFIX) + set(CMAKE_INSTALL_PREFIX "${WITH_PREFIX}") +endif () +if (WITH_PREFIX_BINARY) + set(PREFIX_BINARY "${WITH_PREFIX_BINARY}") +else () + set(PREFIX_BINARY "${CMAKE_INSTALL_PREFIX}/bin") +endif () + # Install rules. -install(TARGETS centreon_connector_ssh RUNTIME DESTINATION ${PREFIX_CONNECTORS}) +install(TARGETS centreon_connector_ssh RUNTIME DESTINATION ${PREFIX_BINARY}) # Code coverage on unit tests option(WITH_COVERAGE "Add code coverage on unit tests." OFF) @@ -73,4 +84,4 @@ if (WITH_COVERAGE) set(CMAKE_BUILD_TYPE "Debug") include(CodeCoverage.cmake) APPEND_COVERAGE_COMPILER_FLAGS() -endif () +endif () \ No newline at end of file diff --git a/centreon-connector/ssh/src/checks/check.cc b/centreon-connector/ssh/src/checks/check.cc index 8340c04141f..d2bea7646f7 100644 --- a/centreon-connector/ssh/src/checks/check.cc +++ b/centreon-connector/ssh/src/checks/check.cc @@ -157,11 +157,13 @@ void check::on_available(sessions::session& sess) { on_available(sess); } break; - case chan_close: + case chan_close: { + unsigned long long cmd_id(_cmd_id); log::core()->info("attempting to close check {} channel", _cmd_id); - if (!_close()) + if (!_close()) { log::core()->info("channel of check {} successfully closed", _cmd_id); - break; + } + } break; default: throw basic_error() << "channel requested to run at invalid step"; } diff --git a/centreon-connector/ssh/src/main.cc b/centreon-connector/ssh/src/main.cc index b9eb69d8150..af85bf76d2e 100644 --- a/centreon-connector/ssh/src/main.cc +++ b/centreon-connector/ssh/src/main.cc @@ -16,11 +16,11 @@ ** For more information : contact@centreon.com */ -#include #include #include #include #include +#include #ifdef LIBSSH2_WITH_LIBGCRYPT #include #endif // LIBSSH2_WITH_LIBGCRYPT @@ -126,15 +126,14 @@ int main(int argc, char* argv[]) { { char const* version(libssh2_version(LIBSSH2_VERSION_NUM)); if (!version) - throw basic_error() - << "libssh2 version is too old (>= " << LIBSSH2_VERSION - << " required)"; - log::core()->info("libssh2 version {} successfully loaded", version); + throw basic_error() << "libssh2 version is too old (>= " + << LIBSSH2_VERSION << " required)"; + log::core()->info( "libssh2 version {} successfully loaded", version); } #endif /* libssh2 version >= 1.2.5 */ // Set termination handler. - log::core()->debug("installing termination handler"); + log::core()->debug( "installing termination handler"); signal(SIGTERM, term_handler); // Program policy. @@ -142,7 +141,7 @@ int main(int argc, char* argv[]) { retval = (p.run() ? EXIT_SUCCESS : EXIT_FAILURE); } } catch (std::exception const& e) { - log::core()->error("installing termination handler"); + log::core()->error( "installing termination handler"); } #if LIBSSH2_VERSION_NUM >= 0x010205 diff --git a/centreon-connector/ssh/src/multiplexer.cc b/centreon-connector/ssh/src/multiplexer.cc index 0053b342aa7..864f1f36ab0 100644 --- a/centreon-connector/ssh/src/multiplexer.cc +++ b/centreon-connector/ssh/src/multiplexer.cc @@ -16,8 +16,8 @@ ** For more information : contact@centreon.com */ -#include "com/centreon/connector/ssh/multiplexer.hh" #include +#include "com/centreon/connector/ssh/multiplexer.hh" using namespace com::centreon::connector::ssh; diff --git a/centreon-connector/ssh/src/orders/parser.cc b/centreon-connector/ssh/src/orders/parser.cc index b0bd917e572..f2cbf8bde49 100644 --- a/centreon-connector/ssh/src/orders/parser.cc +++ b/centreon-connector/ssh/src/orders/parser.cc @@ -42,7 +42,7 @@ parser::parser() : _listnr(nullptr) {} * * @param[in] h Handle. */ -void parser::error([[maybe_unused]] handle& h) { +void parser::error([[maybe_unused]]handle& h) { if (_listnr) _listnr->on_error(0, "error on handle"); } @@ -97,7 +97,7 @@ void parser::read(handle& h) { _buffer.append(buffer, rb); // Find a command boundary. - char boundary[4]{0, 0, 0, 0}; + char boundary[4] { 0, 0, 0, 0 }; size_t bound(_buffer.find(boundary, 0, sizeof(boundary))); // Parse command. @@ -132,7 +132,7 @@ void parser::read(handle& h) { * * @return Always true. */ -bool parser::want_read([[maybe_unused]] handle& h) { +bool parser::want_read([[maybe_unused]]handle& h) { (void)h; return true; } @@ -142,7 +142,7 @@ bool parser::want_read([[maybe_unused]] handle& h) { * * @return Always false (class just parse). */ -bool parser::want_write([[maybe_unused]] handle& h) { +bool parser::want_write([[maybe_unused]]handle& h) { (void)h; return false; } @@ -228,8 +228,8 @@ void parser::_parse(std::string const& cmd) { ts_timeout = timestamp::now() + opt.get_timeout(); else if (opt.get_timeout() > static_cast(timeout)) throw basic_error() - << "invalid execution request " - "received: timeout > to monitoring engine timeout"; + << "invalid execution request " + "received: timeout > to monitoring engine timeout"; } catch (std::exception const& e) { if (_listnr) _listnr->on_error(cmd_id, e.what()); diff --git a/centreon-connector/ssh/src/sessions/socket_handle.cc b/centreon-connector/ssh/src/sessions/socket_handle.cc index 0086e2ca4dd..651562932d3 100644 --- a/centreon-connector/ssh/src/sessions/socket_handle.cc +++ b/centreon-connector/ssh/src/sessions/socket_handle.cc @@ -16,12 +16,12 @@ ** For more information : contact@centreon.com */ -#include "com/centreon/connector/ssh/sessions/socket_handle.hh" -#include -#include -#include #include #include +#include +#include +#include +#include "com/centreon/connector/ssh/sessions/socket_handle.hh" #include "com/centreon/exceptions/basic.hh" using namespace com::centreon; @@ -43,9 +43,7 @@ socket_handle::socket_handle(native_handle handl) : _handl(handl) {} /** * Destructor. */ -socket_handle::~socket_handle() noexcept { - this->close(); -} +socket_handle::~socket_handle() noexcept { this->close(); } /** * Close socket descriptor. diff --git a/centreon-connector/ssh/test/buffer_handle.cc b/centreon-connector/ssh/test/buffer_handle.cc index 30ed4c43a4a..27863c903fa 100644 --- a/centreon-connector/ssh/test/buffer_handle.cc +++ b/centreon-connector/ssh/test/buffer_handle.cc @@ -16,8 +16,8 @@ ** For more information : contact@centreon.com */ -#include "buffer_handle.hh" #include +#include "buffer_handle.hh" using namespace com::centreon; @@ -33,9 +33,7 @@ void buffer_handle::close() { * * @return true if buffer is empty. */ -bool buffer_handle::empty() const { - return _buffer.empty(); -} +bool buffer_handle::empty() const { return _buffer.empty(); } /** * Get the native handle. diff --git a/centreon-connector/ssh/test/checks.cc b/centreon-connector/ssh/test/checks.cc index 6f3e2dff32c..1a12f83b02e 100644 --- a/centreon-connector/ssh/test/checks.cc +++ b/centreon-connector/ssh/test/checks.cc @@ -66,9 +66,9 @@ TEST(SSHChecks, CommandId) { // Checks. r.set_command_id(71184); for (unsigned int i = 0; i < 100; ++i) - ASSERT_EQ(r.get_command_id(), 71184ull); + ASSERT_EQ(r.get_command_id(), 71184); r.set_command_id(15); - ASSERT_EQ(r.get_command_id(), 15ull); + ASSERT_EQ(r.get_command_id(), 15); r.set_command_id(741258963148368872ull); for (unsigned int i = 0; i < 10000; ++i) ASSERT_EQ(r.get_command_id(), 741258963148368872ull); @@ -94,7 +94,7 @@ TEST(SSHChecks, CtorCopy) { r1.set_output("baz qux"); // Check content. - ASSERT_EQ(r1.get_command_id(), 42ull); + ASSERT_EQ(r1.get_command_id(), 42); ASSERT_EQ(r1.get_error(), "foo bar"); ASSERT_EQ(r1.get_executed(), false); ASSERT_EQ(r1.get_exit_code(), 7536); @@ -112,7 +112,7 @@ TEST(SSHChecks, CtorDefault) { com::centreon::connector::ssh::checks::result r; // Check. - ASSERT_EQ(r.get_command_id(), 0ull); + ASSERT_EQ(r.get_command_id(), 0); ASSERT_EQ(r.get_error().empty(), true); ASSERT_EQ(r.get_executed(), false); ASSERT_EQ(r.get_exit_code(), -1); @@ -194,4 +194,5 @@ TEST(SSHChecks, TimeoutCtor) { checks::check c1; checks::timeout t2(&c1); ASSERT_EQ(t2.get_check(), &c1); + } diff --git a/centreon-connector/ssh/test/connector/command_execute_log_file.cc b/centreon-connector/ssh/test/connector/command_execute_log_file.cc index 389a72af529..bc1d779f940 100644 --- a/centreon-connector/ssh/test/connector/command_execute_log_file.cc +++ b/centreon-connector/ssh/test/connector/command_execute_log_file.cc @@ -120,8 +120,9 @@ int main() { std::ifstream file(LOG_FILE); if (file.is_open()) { getline(file, line); - if (line.find("[info] Centreon SSH Connector " CENTREON_CONNECTOR_VERSION - " starting") == std::string::npos) + if (line.find( + "[info] Centreon SSH Connector " CENTREON_CONNECTOR_VERSION + " starting") == std::string::npos) throw(basic_error() << "bad content: the first line does not start with 'Centreon " "SSH Connector " CENTREON_CONNECTOR_VERSION " starting'"); diff --git a/centreon-connector/ssh/test/fake_listener.cc b/centreon-connector/ssh/test/fake_listener.cc index 04ba3e88bc5..98fa951b856 100644 --- a/centreon-connector/ssh/test/fake_listener.cc +++ b/centreon-connector/ssh/test/fake_listener.cc @@ -22,6 +22,12 @@ using namespace com::centreon::connector::ssh::orders; +/************************************** + * * + * Public Methods * + * * + **************************************/ + /** * Get the callbacks information. * diff --git a/centreon-connector/ssh/test/fake_listener.hh b/centreon-connector/ssh/test/fake_listener.hh index 123b8a4aa25..f7daaaae51b 100644 --- a/centreon-connector/ssh/test/fake_listener.hh +++ b/centreon-connector/ssh/test/fake_listener.hh @@ -33,7 +33,13 @@ using namespace com::centreon; */ class fake_listener : public com::centreon::connector::ssh::orders::listener { public: - enum e_callback { cb_eof = 0, cb_error, cb_execute, cb_quit, cb_version }; + enum e_callback { + cb_eof, + cb_error, + cb_execute, + cb_quit, + cb_version + }; struct callback_info { e_callback callback; uint64_t cmd_id; diff --git a/centreon-connector/ssh/test/orders.cc b/centreon-connector/ssh/test/orders.cc index d0623482b83..1acfedf6f22 100644 --- a/centreon-connector/ssh/test/orders.cc +++ b/centreon-connector/ssh/test/orders.cc @@ -243,6 +243,9 @@ TEST(SSHOrders, ExecuteInvalidTimeout) { p.read(bh); p.read(bh); + // Checks. + int retval(0); + // Listener must have received errors and eof. ASSERT_EQ(listnr.get_callbacks().size(), 2u); fake_listener::callback_info info1, info2; diff --git a/centreon-connector/test/centreon-benchmark/connector/build/CMakeLists.txt b/centreon-connector/test/centreon-benchmark/connector/build/CMakeLists.txt index 099dd653678..a1ca7355259 100644 --- a/centreon-connector/test/centreon-benchmark/connector/build/CMakeLists.txt +++ b/centreon-connector/test/centreon-benchmark/connector/build/CMakeLists.txt @@ -42,8 +42,15 @@ set(SRC_DIR "${PROJECT_SOURCE_DIR}/src") # Set path. set(PREFIX "${CMAKE_INSTALL_PREFIX}/centreon-benchmark") +if (WITH_PREFIX) + set(PREFIX "${WITH_PREFIX}") + set(CMAKE_INSTALL_PREFIX "${PREFIX}") +endif () set(PREFIX_BIN "${PREFIX}/centreon_benchmark_connector") +if (WITH_PREFIX_BIN) + set(bindir "${WITH_PREFIX_BIN}") +endif () # Set options. set(UNIT_TEST "No") diff --git a/centreon-connector/test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/connector.hh b/centreon-connector/test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/connector.hh index 2f961378890..4cf4173e9c5 100644 --- a/centreon-connector/test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/connector.hh +++ b/centreon-connector/test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/connector.hh @@ -19,10 +19,10 @@ #ifndef CCB_CONNECTOR_CONNECTOR #define CCB_CONNECTOR_CONNECTOR -#include -#include #include +#include #include +#include #include #include "com/centreon/benchmark/connector/benchmark.hh" #include "com/centreon/benchmark/connector/namespace.hh" diff --git a/centreon-connector/test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/plugin.hh b/centreon-connector/test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/plugin.hh index 8ebb6f38125..6129455e861 100644 --- a/centreon-connector/test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/plugin.hh +++ b/centreon-connector/test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/plugin.hh @@ -19,10 +19,10 @@ #ifndef CCB_CONNECTOR_PLUGIN #define CCB_CONNECTOR_PLUGIN -#include #include #include #include +#include #include #include "com/centreon/benchmark/connector/benchmark.hh" #include "com/centreon/benchmark/connector/namespace.hh" diff --git a/centreon-connector/test/centreon-benchmark/connector/src/basic_exception.cc b/centreon-connector/test/centreon-benchmark/connector/src/basic_exception.cc index 261f983bce2..7e1e6ee3ee4 100644 --- a/centreon-connector/test/centreon-benchmark/connector/src/basic_exception.cc +++ b/centreon-connector/test/centreon-benchmark/connector/src/basic_exception.cc @@ -55,9 +55,7 @@ basic_exception& basic_exception::operator=(basic_exception const& right) { * * @return The message. */ -char const* basic_exception::what() const throw() { - return (_message); -} +char const* basic_exception::what() const throw() { return (_message); } /** * Internal copy. diff --git a/centreon-connector/test/centreon-benchmark/connector/src/benchmark.cc b/centreon-connector/test/centreon-benchmark/connector/src/benchmark.cc index 3773a9c47f0..0af0644ae75 100644 --- a/centreon-connector/test/centreon-benchmark/connector/src/benchmark.cc +++ b/centreon-connector/test/centreon-benchmark/connector/src/benchmark.cc @@ -16,9 +16,9 @@ ** For more information : contact@centreon.com */ -#include "com/centreon/benchmark/connector/benchmark.hh" #include #include "com/centreon/benchmark/connector/basic_exception.hh" +#include "com/centreon/benchmark/connector/benchmark.hh" using namespace com::centreon::benchmark::connector; @@ -36,9 +36,7 @@ benchmark::benchmark() * * @param[in] right The object to copy. */ -benchmark::benchmark(benchmark const& right) { - _internal_copy(right); -} +benchmark::benchmark(benchmark const& right) { _internal_copy(right); } /** * Default destructor. diff --git a/centreon-connector/test/centreon-benchmark/connector/src/connector.cc b/centreon-connector/test/centreon-benchmark/connector/src/connector.cc index 516dfd4e517..3d47207987e 100644 --- a/centreon-connector/test/centreon-benchmark/connector/src/connector.cc +++ b/centreon-connector/test/centreon-benchmark/connector/src/connector.cc @@ -16,18 +16,18 @@ ** For more information : contact@centreon.com */ -#include "com/centreon/benchmark/connector/connector.hh" #include #include +#include +#include #include #include #include #include #include -#include -#include #include "com/centreon/benchmark/connector/basic_exception.hh" #include "com/centreon/benchmark/connector/misc.hh" +#include "com/centreon/benchmark/connector/connector.hh" using namespace com::centreon::benchmark::connector; @@ -61,9 +61,7 @@ connector::connector(connector const& right) : benchmark() { /** * Default destructor. */ -connector::~connector() throw() { - _cleanup(); -} +connector::~connector() throw() { _cleanup(); } /** * Default copy constructor. @@ -111,9 +109,7 @@ void connector::_check_execution() { /** * Send and check quit request. */ -void connector::_check_quit() { - _send_data(_request_quit()); -} +void connector::_check_quit() { _send_data(_request_quit()); } /** * Send and check version request. @@ -189,9 +185,9 @@ void connector::_recv_data(int timeout) { throw(basic_exception(strerror(errno))); else if (ret && (_pfd.revents & (POLLNVAL | POLLHUP)) && !(_pfd.revents & (POLLIN | POLLPRI))) - throw( - basic_exception("connector communication fd " - "terminated prematurely")); + throw(basic_exception( + "connector communication fd " + "terminated prematurely")); else if (!ret || !(_pfd.revents & (POLLIN | POLLPRI))) return; char buffer[4096]; diff --git a/centreon-connector/test/centreon-benchmark/connector/src/main.cc b/centreon-connector/test/centreon-benchmark/connector/src/main.cc index f31b4dd19ad..29771d06626 100644 --- a/centreon-connector/test/centreon-benchmark/connector/src/main.cc +++ b/centreon-connector/test/centreon-benchmark/connector/src/main.cc @@ -16,13 +16,13 @@ ** For more information : contact@centreon.com */ +#include #include #include +#include #include #include #include -#include -#include #include "com/centreon/benchmark/connector/basic_exception.hh" #include "com/centreon/benchmark/connector/connector.hh" #include "com/centreon/benchmark/connector/plugin.hh" @@ -47,8 +47,7 @@ struct options { static void usage(char* appname) { std::cout << "usage: " << basename(appname) << " -c commands_file [-t connector|plugin] [-m 1024] [-n 100] [-l " - "1024] args..." - << std::endl; + "1024] args..." << std::endl; } static void help() { @@ -60,8 +59,7 @@ static void help() { << " -n, --total-request: Number of total request\n" << " -o, --output: The file path to write request output\n" << " -t, --type: Type of running command (connector or " - "plugin)" - << std::endl; + "plugin)" << std::endl; } static options parse_options(int ac, char** av) { @@ -149,7 +147,8 @@ int main(int argc, char** argv) { bench->set_output_file(opt.output_file); bench->run(); - } catch (std::exception const& e) { + } + catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; ret = EXIT_FAILURE; } diff --git a/centreon-connector/test/centreon-benchmark/connector/src/misc.cc b/centreon-connector/test/centreon-benchmark/connector/src/misc.cc index fc937a94f78..8ca438c6052 100644 --- a/centreon-connector/test/centreon-benchmark/connector/src/misc.cc +++ b/centreon-connector/test/centreon-benchmark/connector/src/misc.cc @@ -16,9 +16,9 @@ ** For more information : contact@centreon.com */ -#include "com/centreon/benchmark/connector/misc.hh" #include #include "com/centreon/benchmark/connector/basic_exception.hh" +#include "com/centreon/benchmark/connector/misc.hh" /** * Load the commands configuration file. @@ -57,10 +57,11 @@ char** com::centreon::benchmark::connector::list_to_tab( unsigned int size) { if (!size) size = v.size() + 1; - char** tab(new char*[size]); + char** tab(new char* [size]); unsigned int i(0); for (std::list::const_iterator it(v.begin()), end(v.end()); - it != end; ++it) + it != end; + ++it) tab[i++] = const_cast(it->c_str()); tab[i] = NULL; return (tab); diff --git a/centreon-connector/test/centreon-benchmark/connector/src/plugin.cc b/centreon-connector/test/centreon-benchmark/connector/src/plugin.cc index 0ca9bb9f61a..c35409746ea 100644 --- a/centreon-connector/test/centreon-benchmark/connector/src/plugin.cc +++ b/centreon-connector/test/centreon-benchmark/connector/src/plugin.cc @@ -16,9 +16,10 @@ ** For more information : contact@centreon.com */ -#include "com/centreon/benchmark/connector/plugin.hh" #include #include +#include +#include #include #include #include @@ -26,10 +27,9 @@ #include #include #include -#include -#include #include "com/centreon/benchmark/connector/basic_exception.hh" #include "com/centreon/benchmark/connector/misc.hh" +#include "com/centreon/benchmark/connector/plugin.hh" using namespace com::centreon::benchmark::connector; @@ -51,16 +51,12 @@ plugin::plugin(std::string const& commands_file, * * @param[in] right The object to copy. */ -plugin::plugin(plugin const& right) : benchmark() { - _internal_copy(right); -} +plugin::plugin(plugin const& right) : benchmark() { _internal_copy(right); } /** * Default destructor. */ -plugin::~plugin() throw() { - _cleanup(); -} +plugin::~plugin() throw() { _cleanup(); } /** * Default copy constructor. @@ -96,7 +92,8 @@ void plugin::run() { while (_current_running > 0) { _wait_plugin(true); } - } catch (std::exception const& e) { + } + catch (std::exception const& e) { wordfree(&p); throw; } diff --git a/centreon-engine/CMakeLists.txt b/centreon-engine/CMakeLists.txt index 4cbbaa356b7..23bf5d6498c 100644 --- a/centreon-engine/CMakeLists.txt +++ b/centreon-engine/CMakeLists.txt @@ -22,7 +22,9 @@ # # Set necessary settings. +cmake_minimum_required(VERSION 2.8) project("Centreon Engine" C CXX) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") # set -latomic if OS is Raspbian. if (CMAKE_SYSTEM_PROCESSOR MATCHES "arm") @@ -38,24 +40,46 @@ if (WITH_ASAN) "${CMAKE_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address") endif () +add_definitions("-D_GLIBCXX_USE_CXX11_ABI=1") set(INC_DIR "${PROJECT_SOURCE_DIR}/inc") set(SCRIPT_DIR "${PROJECT_SOURCE_DIR}/scripts") set(SRC_DIR "${PROJECT_SOURCE_DIR}/src") - -set(ENGINE_MODULES_DIR "${CMAKE_INSTALL_PREFIX}/lib64/centreon-engine/") - include_directories("${INC_DIR}") include_directories("${INC_DIR}/compatibility") include(${CMAKE_BINARY_DIR}/conan_paths.cmake) +set(protobuf_MODULE_COMPATIBLE True) +find_package(Protobuf REQUIRED) +find_package(gRPC REQUIRED) +find_package(c-ares REQUIRED) +find_package(ZLIB REQUIRED) +find_package(nlohmann_json REQUIRED) +find_package(fmt REQUIRED) +find_package(spdlog REQUIRED) + +include_directories(${gRPC_INCLUDE_DIRS}) +include_directories(${absl_INCLUDE_DIRS}) +include_directories(${protobuf_INCLUDE_DIRS}) +include_directories(${nlohmann_json_INCLUDE_DIRS}) +include_directories(${fmt_INCLUDE_DIRS}) + +link_directories(${protobuf_LIB_DIRS}) +link_directories(${gRPC_LIB_DIRS}) +link_directories(${OpenSSL_LIB_DIRS}) +link_directories(${c-ares_LIB_DIRS}) +link_directories(${ZLIB_LIB_DIRS}) +link_directories(${nlohmann_json_LIB_DIRS}) link_directories(${CMAKE_SOURCE_DIR}/build/centreon-clib/) # Version. +set(CENTREON_ENGINE_MAJOR 21) +set(CENTREON_ENGINE_MINOR 10) +set(CENTREON_ENGINE_PATCH 0) if (CENTREON_ENGINE_PRERELEASE) - set(CENTREON_ENGINE_VERSION "${COLLECT_MAJOR}.${COLLECT_MINOR}.${COLLECT_PATCH}-${CENTREON_ENGINE_PRERELEASE}") + set(CENTREON_ENGINE_VERSION "${CENTREON_ENGINE_MAJOR}.${CENTREON_ENGINE_MINOR}.${CENTREON_ENGINE_PATCH}-${CENTREON_ENGINE_PRERELEASE}") else () - set(CENTREON_ENGINE_VERSION "${COLLECT_MAJOR}.${COLLECT_MINOR}.${COLLECT_PATCH}") + set(CENTREON_ENGINE_VERSION "${CENTREON_ENGINE_MAJOR}.${CENTREON_ENGINE_MINOR}.${CENTREON_ENGINE_PATCH}") endif() message(STATUS "Generating version header (${CENTREON_ENGINE_VERSION}).") configure_file("${INC_DIR}/com/centreon/engine/version.hh.in" @@ -91,51 +115,52 @@ if (NOT CMAKE_USE_PTHREADS_INIT) endif () set(PTHREAD_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}") -## Find Centreon Clib's headers. -#if (WITH_CENTREON_CLIB_INCLUDE_DIR) -# find_file( -# CLIB_HEADER_FOUND -# "com/centreon/clib/version.hh" -# PATHS "${WITH_CENTREON_CLIB_INCLUDE_DIR}" -# NO_DEFAULT_PATH) -# if (NOT CLIB_HEADER_FOUND) -# message(FATAL_ERROR "Could not find Centreon Clib's headers in ${WITH_CENTREON_CLIB_INCLUDE_DIR}.") -# endif () -# set(CLIB_INCLUDE_DIR "${WITH_CENTREON_CLIB_INCLUDE_DIR}") -#elseif (CLIB_FOUND) # Was Centreon Clib detected with pkg-config ? -# if (CMAKE_CXX_FLAGS) -# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CLIB_CFLAGS}") -# else () -# set(CMAKE_CXX_FLAGS "${CLIB_CFLAGS}") -# endif () -#else () -# find_path(CLIB_INCLUDE_DIR "com/centreon/clib/version.hh" PATH_SUFFIXES "centreon-clib") -# if (NOT CLIB_INCLUDE_DIR) -# message(FATAL_ERROR "Could not find Centreon Clib's headers (try WITH_CENTREON_CLIB_INCLUDE_DIR).") -# endif () -#endif () -include_directories(${CMAKE_SOURCE_DIR}/centreon-clib/inc) - -## Find Centreon Clib's library. -#if (WITH_CENTREON_CLIB_LIBRARIES) -# set(CLIB_LIBRARIES "${WITH_CENTREON_CLIB_LIBRARIES}") -#elseif (WITH_CENTREON_CLIB_LIBRARY_DIR) -# find_library( -# CLIB_LIBRARIES -# "centreon_clib" -# PATHS "${WITH_CENTREON_CLIB_LIBRARY_DIR}" -# NO_DEFAULT_PATH) -# if (NOT CLIB_LIBRARIES) -# message(FATAL_ERROR "Could not find Centreon Clib's library in ${WITH_CENTREON_CLIB_LIBRARY_DIR}.") -# endif () -#elseif (CLIB_FOUND) # Was Centreon Clib detected with pkg-config ? -# set(CLIB_LIBRARIES "${CLIB_LDFLAGS}") -#else () -# find_library(CLIB_LIBRARIES "centreon_clib") -# if (NOT CLIB_LIBRARIES) -# message(FATAL_ERROR "Could not find Centreon Clib's library (try WITH_CENTREON_CLIB_LIBRARY_DIR or WITH_CENTREON_CLIB_LIBRARIES).") -# endif () -#endif () +# Find Centreon Clib's headers. +if (WITH_CENTREON_CLIB_INCLUDE_DIR) + find_file( + CLIB_HEADER_FOUND + "com/centreon/clib/version.hh" + PATHS "${WITH_CENTREON_CLIB_INCLUDE_DIR}" + NO_DEFAULT_PATH) + if (NOT CLIB_HEADER_FOUND) + message(FATAL_ERROR "Could not find Centreon Clib's headers in ${WITH_CENTREON_CLIB_INCLUDE_DIR}.") + endif () + include_directories("${WITH_CENTREON_CLIB_INCLUDE_DIR}") + set(CLIB_INCLUDE_DIR "${WITH_CENTREON_CLIB_INCLUDE_DIR}") +elseif (CLIB_FOUND) # Was Centreon Clib detected with pkg-config ? + if (CMAKE_CXX_FLAGS) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CLIB_CFLAGS}") + else () + set(CMAKE_CXX_FLAGS "${CLIB_CFLAGS}") + endif () +else () + find_path(CLIB_INCLUDE_DIR "com/centreon/clib/version.hh" PATH_SUFFIXES "centreon-clib") + if (NOT CLIB_INCLUDE_DIR) + message(FATAL_ERROR "Could not find Centreon Clib's headers (try WITH_CENTREON_CLIB_INCLUDE_DIR).") + endif () + include_directories("${CLIB_INCLUDE_DIR}") +endif () + +# Find Centreon Clib's library. +if (WITH_CENTREON_CLIB_LIBRARIES) + set(CLIB_LIBRARIES "${WITH_CENTREON_CLIB_LIBRARIES}") +elseif (WITH_CENTREON_CLIB_LIBRARY_DIR) + find_library( + CLIB_LIBRARIES + "centreon_clib" + PATHS "${WITH_CENTREON_CLIB_LIBRARY_DIR}" + NO_DEFAULT_PATH) + if (NOT CLIB_LIBRARIES) + message(FATAL_ERROR "Could not find Centreon Clib's library in ${WITH_CENTREON_CLIB_LIBRARY_DIR}.") + endif () +elseif (CLIB_FOUND) # Was Centreon Clib detected with pkg-config ? + set(CLIB_LIBRARIES "${CLIB_LDFLAGS}") +else () + find_library(CLIB_LIBRARIES "centreon_clib") + if (NOT CLIB_LIBRARIES) + message(FATAL_ERROR "Could not find Centreon Clib's library (try WITH_CENTREON_CLIB_LIBRARY_DIR or WITH_CENTREON_CLIB_LIBRARIES).") + endif () +endif () # Check functions. include(CheckIncludeFileCXX) @@ -171,19 +196,82 @@ option(BUILD_OFFLINE "Build offline" OFF) option(WITH_CREATE_FILES "Create centreon-engine files." ON) set(CREATE_FILES "${WITH_CREATE_FILES}") -set(PREFIX_ENGINE_CONF "${CMAKE_INSTALL_FULL_SYSCONFDIR}/centreon-engine") +# Main directory. +if (WITH_PREFIX) + set(CMAKE_INSTALL_PREFIX "${WITH_PREFIX}") +endif () + +# Executable directory. +if (WITH_PREFIX_BIN) + set(PREFIX_BIN "${WITH_PREFIX_BIN}") +else () + set(PREFIX_BIN "${CMAKE_INSTALL_PREFIX}/bin") +endif () + +# Configuration directory. +if (WITH_PREFIX_CONF_ENGINE) + set(PREFIX_CONF "${WITH_PREFIX_CONF_ENGINE}") +else () + set(PREFIX_CONF "${CMAKE_INSTALL_PREFIX}/etc") +endif () + +# Library directory. +if (WITH_PREFIX_LIB_ENGINE) + set(PREFIX_LIB "${WITH_PREFIX_LIB_ENGINE}") +else () + set(PREFIX_LIB "${CMAKE_INSTALL_PREFIX}/lib/centreon-engine") +endif () + +# Development headers directory. +if (WITH_PREFIX_INC) + set(PREFIX_INC "${WITH_PREFIX_INC}") +else () + set(PREFIX_INC "${CMAKE_INSTALL_PREFIX}/include/centreon-engine") +endif () + +# pkg-config directory. +option(WITH_PKGCONFIG_SCRIPT "Generate and install pkg-config script." ON) +if (WITH_PKGCONFIG_SCRIPT) + # Generate pkg-config file. + message(STATUS "Generating pkg-config file.") + configure_file( + "${SCRIPT_DIR}/centengine.pc.in" + "${SCRIPT_DIR}/centengine.pc" + @ONLY) + + # pkg-config file install directory. + if (WITH_PKGCONFIG_DIR) + set(PKGCONFIG_DIR "${WITH_PKGCONFIG_DIR}") + else () + set(PKGCONFIG_DIR "${PREFIX_LIB}/pkgconfig") + endif () + + # Install rule. + install(FILES "${SCRIPT_DIR}/centengine.pc" + DESTINATION "${PKGCONFIG_DIR}" + COMPONENT "runtime") +endif () -## Library directory. -#if (WITH_PREFIX_LIB_ENGINE) -# set(PREFIX_LIB "${WITH_PREFIX_LIB_ENGINE}") -#else () -# set(PREFIX_LIB "${CMAKE_INSTALL_PREFIX}/lib/centreon-engine") -#endif () -# # var directory. -set(VAR_LOG_DIR "${CMAKE_INSTALL_FULL_LOCALSTATEDIR}/log/centreon-engine") -set(VAR_LOG_ARCHIVE_DIR "${CMAKE_INSTALL_FULL_LOCALSTATEDIR}/log/centreon-engine/archives") -set(VAR_LIB_DIR "${CMAKE_INSTALL_FULL_LOCALSTATEDIR}/lib/centreon-engine") +if (WITH_VAR_DIR) + set(VAR_DIR "${WITH_VAR_DIR}") +else () + set(VAR_DIR "${CMAKE_INSTALL_PREFIX}/var") +endif () + +# Log archive dir. +if (WITH_LOG_ARCHIVE_DIR) + set(LOG_ARCHIVE_DIR "${WITH_LOG_ARCHIVE_DIR}") +else () + set(LOG_ARCHIVE_DIR "${VAR_DIR}/archives") +endif () + +# RW dir. +if (WITH_RW_DIR) + set(RW_DIR "${WITH_RW_DIR}") +else () + set(RW_DIR "${VAR_DIR}/rw") +endif () # User used to run Centreon Engine. if (WITH_USER_ENGINE) @@ -330,8 +418,8 @@ else () endif () # logrotate directory. -option(WITH_ENGINE_LOGROTATE_SCRIPT "Generate and install logrotate script." OFF) -if (WITH_ENGINE_LOGROTATE_SCRIPT) +option(WITH_LOGROTATE_SCRIPT "Generate and install logrotate script." OFF) +if (WITH_LOGROTATE_SCRIPT) # Generate logrotate file. message(STATUS "Generating logrorate file.") if (WITH_STARTUP_SCRIPT STREQUAL "upstart") @@ -352,7 +440,11 @@ if (WITH_ENGINE_LOGROTATE_SCRIPT) endif () # logrotate file install directory. - set(LOGROTATE_DIR "${CMAKE_INSTALL_FULL_SYSCONFDIR}/logrotate.d") + if (WITH_LOGROTATE_DIR) + set(LOGROTATE_DIR "${WITH_LOGROTATE_DIR}") + else () + set(LOGROTATE_DIR "/etc/logrotate.d") + endif () # Install rule. install( @@ -398,13 +490,13 @@ configure_file("${INC_DIR}/compatibility/common.h.in" "${INC_DIR}/compatibility/common.h") # Locations definitions -add_definitions(-DDEFAULT_STATUS_FILE="${VAR_LOG_DIR}/status.dat") -add_definitions(-DDEFAULT_LOG_FILE="${VAR_LOG_DIR}/centengine.log") -add_definitions(-DDEFAULT_LOG_ARCHIVE_PATH="${VAR_LOG_ARCHIVE_DIR}") -add_definitions(-DDEFAULT_DEBUG_FILE="${VAR_LOG_DIR}/centengine.debug") -add_definitions(-DDEFAULT_RETENTION_FILE="${VAR_LOG_DIR}/retention.dat") -add_definitions(-DDEFAULT_COMMAND_FILE="${VAR_LIB_DIR}/rw/centengine.cmd") -add_definitions(-DDEFAULT_CONFIG_FILE="${PREFIX_ENGINE_CONF}/centengine.cfg") +add_definitions(-DDEFAULT_STATUS_FILE="${VAR_DIR}/status.dat") +add_definitions(-DDEFAULT_LOG_FILE="${VAR_DIR}/centengine.log") +add_definitions(-DDEFAULT_LOG_ARCHIVE_PATH="${LOG_ARCHIVE_DIR}") +add_definitions(-DDEFAULT_DEBUG_FILE="${VAR_DIR}/centengine.debug") +add_definitions(-DDEFAULT_RETENTION_FILE="${VAR_DIR}/retention.dat") +add_definitions(-DDEFAULT_COMMAND_FILE="${RW_DIR}/centengine.cmd") +add_definitions(-DDEFAULT_CONFIG_FILE="${PREFIX_CONF}/centengine.cfg") # Add specific linker flags for Mac OS to build correctly shared libraries. if (APPLE) @@ -535,7 +627,7 @@ include_directories(enginerpc) # Library engine target. add_library(cce_core ${LIBRARY_TYPE} ${FILES}) add_dependencies(cce_core engine_rpc) -add_dependencies(cce_core centreon_clib) +add_dependencies(cce_core centreon_clib_shared) # Link target with required libraries. target_link_libraries(cce_core ${nlohmann_json_LIBS} @@ -549,15 +641,17 @@ target_link_libraries(cce_core ${nlohmann_json_LIBS} # centengine target. add_executable("centengine" "${SRC_DIR}/main.cc") set_property(TARGET "centengine" PROPERTY ENABLE_EXPORTS "1") -add_dependencies(centengine centreon_clib) +add_dependencies(centengine centreon_clib_shared) +get_property(CENTENGINE_BINARY TARGET "centengine" PROPERTY LOCATION) # Link centengine with required libraries. target_link_libraries(centengine centreon_clib "-Wl,-whole-archive" enginerpc cce_core "-Wl,-no-whole-archive" ${gRPC_LIBS} ${absl_LIBS} ${OpenSSL_LIBS} ${c-ares_LIBS} ${ZLIB_LIBS} dl) # centenginestats target. add_executable("centenginestats" "${SRC_DIR}/centenginestats.cc") -add_dependencies("centenginestats" centreon_clib) +add_dependencies("centenginestats" centreon_clib_shared) target_link_libraries("centenginestats" centreon_clib) +get_property(CENTENGINESTATS_BINARY TARGET "centenginestats" PROPERTY LOCATION) # Unit tests. add_subdirectory(tests) @@ -568,7 +662,7 @@ add_subdirectory(tests) # Install rules. install(TARGETS "centengine" "centenginestats" - DESTINATION "${CMAKE_INSTALL_FULL_SBINDIR}" + DESTINATION "${PREFIX_BIN}" COMPONENT "runtime") ## Create directories. @@ -596,11 +690,15 @@ if (CREATE_FILES) endif () endfunction() - mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}\") - mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/objects\") - mkdir_chown(\"${USER}\" \"${GROUP}\" \"${VAR_LOG_DIR}\") - mkdir_chown(\"${USER}\" \"${GROUP}\" \"${VAR_LOG_ARCHIVE_DIR}\") - mkdir_chown(\"${USER}\" \"${GROUP}\" \"${VAR_LIB_DIR}/rw\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${CMAKE_INSTALL_PREFIX}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_BIN}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/objects\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_INC}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_LIB}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${VAR_DIR}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${LOG_ARCHIVE_DIR}\") + mkdir_chown(\"${USER}\" \"${GROUP}\" \"${RW_DIR}\") if (LOCK_DIR) mkdir_chown(\"${USER}\" \"${GROUP}\" \"${LOCK_DIR}\") endif () @@ -608,16 +706,16 @@ if (CREATE_FILES) mkdir_chown(\"${USER}\" \"${GROUP}\" \"${PID_DIR}\") endif () - touch_chown(\"${USER}\" \"${GROUP}\" \"${VAR_LOG_DIR}/status.dat\") - touch_chown(\"${USER}\" \"${GROUP}\" \"${VAR_LOG_DIR}/centengine.log\") - touch_chown(\"${USER}\" \"${GROUP}\" \"${VAR_LOG_DIR}/centengine.debug\") - touch_chown(\"${USER}\" \"${GROUP}\" \"${VAR_LOG_DIR}/retention.dat\") + touch_chown(\"${USER}\" \"${GROUP}\" \"${VAR_DIR}/status.dat\") + touch_chown(\"${USER}\" \"${GROUP}\" \"${VAR_DIR}/centengine.log\") + touch_chown(\"${USER}\" \"${GROUP}\" \"${VAR_DIR}/centengine.debug\") + touch_chown(\"${USER}\" \"${GROUP}\" \"${VAR_DIR}/retention.dat\") ") endif () # Install header files for development. install(DIRECTORY "${INC_DIR}/" - DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}/centreon-engine/" + DESTINATION "${PREFIX_INC}" COMPONENT "development" FILES_MATCHING PATTERN "*.hh" PATTERN "${INC_DIR}/compatibility/" EXCLUDE @@ -666,7 +764,12 @@ if (WITH_TESTING) else () message(STATUS " - Unit tests disabled") endif () -if (WITH_ENGINE_LOGROTATE_SCRIPT) +if (WITH_PKGCONFIG_SCRIPT) + message(STATUS " - pkg-config script enabled") +else () + message(STATUS " - pkg-config script disabled") +endif () +if (WITH_LOGROTATE_SCRIPT) message(STATUS " - logrotate script enabled") else () message(STATUS " - logrotate script disabled") @@ -674,18 +777,21 @@ endif () message(STATUS " - Startup script ${STARTUP_SCRIPT}") message(STATUS "") message(STATUS " Install") -#message(STATUS " - Prefix ${CMAKE_INSTALL_PREFIX}") -message(STATUS " - Binary prefix ${CMAKE_INSTALL_FULL_SBINDIR}") -message(STATUS " - Configuration prefix ${PREFIX_ENGINE_CONF}") -#message(STATUS " - Library prefix ${PREFIX_LIB}") -message(STATUS " - Include prefix ${CMAKE_INSTALL_FULL_INCLUDEDIR}/centreon-engine") +message(STATUS " - Prefix ${CMAKE_INSTALL_PREFIX}") +message(STATUS " - Binary prefix ${PREFIX_BIN}") +message(STATUS " - Configuration prefix ${PREFIX_CONF}") +message(STATUS " - Library prefix ${PREFIX_LIB}") +message(STATUS " - Include prefix ${PREFIX_INC}") message(STATUS " - var directory ${VAR_DIR}") -message(STATUS " - Log archive directory ${VAR_LOG_ARCHIVE_DIR}") -message(STATUS " - RW directory ${VAR_LIB_DIR}/rw") +message(STATUS " - Log archive directory ${LOG_ARCHIVE_DIR}") +message(STATUS " - RW directory ${RW_DIR}") if (LOCK_FILE) message(STATUS " - Lock prefix ${LOCK_FILE}") endif () -if (WITH_ENGINE_LOGROTATE_SCRIPT) +if (WITH_PKGCONFIG_SCRIPT) + message(STATUS " - pkg-config directory ${PKGCONFIG_DIR}") +endif () +if (WITH_LOGROTATE_SCRIPT) message(STATUS " - logrotate directory ${LOGROTATE_DIR}") endif () if (STARTUP_DIR) diff --git a/centreon-engine/cmake/package.cmake b/centreon-engine/cmake/package.cmake index ceaedf7e97a..a3574cad9f6 100644 --- a/centreon-engine/cmake/package.cmake +++ b/centreon-engine/cmake/package.cmake @@ -32,9 +32,9 @@ if (WITH_PACKAGE_SH OR WITH_PACKAGE_NSIS) # Default settings. set(CPACK_PACKAGE_VENDOR "Merethis") - set(CPACK_PACKAGE_VERSION_MAJOR "${COLLECT_MAJOR}") - set(CPACK_PACKAGE_VERSION_MINOR "${COLLECT_MINOR}") - set(CPACK_PACKAGE_VERSION_PATCH "${COLLECT_PATCH}") + set(CPACK_PACKAGE_VERSION_MAJOR "${CENTREON_ENGINE_MAJOR}") + set(CPACK_PACKAGE_VERSION_MINOR "${CENTREON_ENGINE_MINOR}") + set(CPACK_PACKAGE_VERSION_PATCH "${CENTREON_ENGINE_PATCH}") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Centreon Engine is a monitoring engine fully Nagios-compatible but with additionnal features and performance improvements.") set(CPACK_PACKAGE_FILE_NAME diff --git a/centreon-engine/conf/CMakeLists.txt b/centreon-engine/conf/CMakeLists.txt index 03435fe57c2..06ffddef9a2 100644 --- a/centreon-engine/conf/CMakeLists.txt +++ b/centreon-engine/conf/CMakeLists.txt @@ -1,6 +1,5 @@ ## ## Copyright 2011-2013 Merethis -## Copyright 2020-2021 Centreon ## ## This file is part of Centreon Engine. ## @@ -47,7 +46,7 @@ configure_file("${SRC_DIR}/objects/windows.cfg.in" option(WITH_SAMPLE_CONFIG "Install sample configuration files." ON) if (WITH_SAMPLE_CONFIG) install(DIRECTORY "${SRC_DIR}/" - DESTINATION "${PREFIX_ENGINE_CONF}" + DESTINATION "${PREFIX_CONF}" COMPONENT "runtime" FILES_MATCHING PATTERN "*.cfg") @@ -58,15 +57,15 @@ if (WITH_SAMPLE_CONFIG) endif () endfunction() - my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/centengine.cfg\") - my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/resource.cfg\") - my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/objects/commands.cfg\") - my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/objects/contacts.cfg\") - my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/objects/localhost.cfg\") - my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/objects/printer.cfg\") - my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/objects/switch.cfg\") - my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/objects/templates.cfg\") - my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/objects/timeperiods.cfg\") - my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_ENGINE_CONF}/objects/windows.cfg\") + my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/centengine.cfg\") + my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/resource.cfg\") + my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/objects/commands.cfg\") + my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/objects/contacts.cfg\") + my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/objects/localhost.cfg\") + my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/objects/printer.cfg\") + my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/objects/switch.cfg\") + my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/objects/templates.cfg\") + my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/objects/timeperiods.cfg\") + my_chown(\"${USER}\" \"${GROUP}\" \"${PREFIX_CONF}/objects/windows.cfg\") ") endif () diff --git a/centreon-engine/enginerpc/CMakeLists.txt b/centreon-engine/enginerpc/CMakeLists.txt index 142ae2eb107..e2bd9a2359b 100644 --- a/centreon-engine/enginerpc/CMakeLists.txt +++ b/centreon-engine/enginerpc/CMakeLists.txt @@ -30,7 +30,9 @@ include_directories( ) +set(protobuf_MODULE_COMPATIBLE True) find_package(Protobuf REQUIRED) +find_package(gRPC REQUIRED) include_directories(${gRPC_INCLUDE_DIRS}) include_directories(${absl_INCLUDE_DIRS}) diff --git a/centreon-engine/enginerpc/engine_impl.cc b/centreon-engine/enginerpc/engine_impl.cc index cfde18924f8..c2874fb41d2 100644 --- a/centreon-engine/enginerpc/engine_impl.cc +++ b/centreon-engine/enginerpc/engine_impl.cc @@ -1,12 +1,12 @@ #include "com/centreon/engine/engine_impl.hh" -#include #include #include #include #include #include #include +#include #include "com/centreon/engine/anomalydetection.hh" #include "com/centreon/engine/broker.hh" @@ -160,48 +160,47 @@ grpc::Status engine_impl::GetHost(grpc::ServerContext* context __attribute__((unused)), EngineHost* response) { std::string err; - auto fn = std::packaged_task([&err, request, - host = response]() -> int32_t { - std::shared_ptr selectedhost; - /* checking identifier hostname (by name or by id) */ - switch (request->identifier_case()) { - case HostIdentifier::kName: { - /* get the host */ - auto ithostname = host::hosts.find(request->name()); - if (ithostname != host::hosts.end()) - selectedhost = ithostname->second; - else { - err = fmt::format("could not find host '{}'", request->name()); - return 1; - } - } break; - case HostIdentifier::kId: { - /* get the host */ - auto ithostid = host::hosts_by_id.find(request->id()); - if (ithostid != host::hosts_by_id.end()) - selectedhost = ithostid->second; - else { - err = fmt::format("could not find host {}", request->id()); - return 1; + auto fn = + std::packaged_task([&err, request, host = response]() -> int32_t { + std::shared_ptr selectedhost; + /* checking identifier hostname (by name or by id) */ + switch (request->identifier_case()) { + case HostIdentifier::kName: { + /* get the host */ + auto ithostname = host::hosts.find(request->name()); + if (ithostname != host::hosts.end()) + selectedhost = ithostname->second; + else { + err = fmt::format("could not find host '{}'", request->name()); + return 1; + } + } break; + case HostIdentifier::kId: { + /* get the host */ + auto ithostid = host::hosts_by_id.find(request->id()); + if (ithostid != host::hosts_by_id.end()) + selectedhost = ithostid->second; + else { + err = fmt::format("could not find host {}", request->id()); + return 1; + } + } break; + default: { + err = fmt::format("could not find identifier, you should inform a host"); + return 1; + break; + } } - } break; - default: { - err = - fmt::format("could not find identifier, you should inform a host"); - return 1; - break; - } - } - host->set_name(selectedhost->get_name()); - host->set_alias(selectedhost->get_alias()); - host->set_address(selectedhost->get_address()); - host->set_check_period(selectedhost->get_check_period()); - host->set_current_state( - static_cast(selectedhost->get_current_state())); - host->set_id(selectedhost->get_host_id()); - return 0; - }); + host->set_name(selectedhost->get_name()); + host->set_alias(selectedhost->get_alias()); + host->set_address(selectedhost->get_address()); + host->set_check_period(selectedhost->get_check_period()); + host->set_current_state( + static_cast(selectedhost->get_current_state())); + host->set_id(selectedhost->get_host_id()); + return 0; + }); std::future result = fn.get_future(); command_manager::instance().enqueue(std::move(fn)); @@ -209,7 +208,8 @@ grpc::Status engine_impl::GetHost(grpc::ServerContext* context if (res == 0) return grpc::Status::OK; else - return grpc::Status(grpc::INVALID_ARGUMENT, err); + return grpc::Status(grpc::INVALID_ARGUMENT, + err); } /** @@ -226,8 +226,8 @@ grpc::Status engine_impl::GetContact(grpc::ServerContext* context const ContactIdentifier* request, EngineContact* response) { std::string err; - auto fn = std::packaged_task( - [&err, request, contact = response]() -> int32_t { + auto fn = + std::packaged_task([&err, request, contact = response]() -> int32_t { std::shared_ptr selectedcontact; /* get the contact by his name */ auto itcontactname = contact::contacts.find(request->name()); @@ -248,7 +248,8 @@ grpc::Status engine_impl::GetContact(grpc::ServerContext* context if (result.get() == 0) return grpc::Status::OK; else - return grpc::Status(grpc::INVALID_ARGUMENT, err); + return grpc::Status(grpc::INVALID_ARGUMENT, + err); } /** @@ -266,8 +267,8 @@ grpc::Status engine_impl::GetService(grpc::ServerContext* context const ServiceIdentifier* request, EngineService* response) { std::string err; - auto fn = std::packaged_task( - [&err, request, service = response]() -> int32_t { + auto fn = + std::packaged_task([&err, request, service = response]() -> int32_t { std::shared_ptr selectedservice; /* checking identifier sesrname (by names or by ids) */ @@ -280,8 +281,7 @@ grpc::Status engine_impl::GetService(grpc::ServerContext* context if (itservicenames != service::services.end()) selectedservice = itservicenames->second; else { - err = fmt::format("could not find service ('{}', '{}')", - names.host_name(), names.service_name()); + err = fmt::format("could not find service ('{}', '{}')", names.host_name(), names.service_name()); return 1; } } break; @@ -293,8 +293,7 @@ grpc::Status engine_impl::GetService(grpc::ServerContext* context if (itserviceids != service::services_by_id.end()) selectedservice = itserviceids->second; else { - err = fmt::format("could not find service ({}, {})", - ids.host_id(), ids.service_id()); + err = fmt::format("could not find service ({}, {})", ids.host_id(), ids.service_id()); return 1; } } break; @@ -529,7 +528,7 @@ grpc::Status engine_impl::GetHostDependenciesCount( grpc::Status engine_impl::AddHostComment(grpc::ServerContext* context __attribute__((unused)), const EngineComment* request, - CommandSuccess* response + CommandSuccess* response __attribute__((unused))) { std::string err; auto fn = std::packaged_task([&err, request]() -> int32_t { @@ -556,7 +555,7 @@ grpc::Status engine_impl::AddHostComment(grpc::ServerContext* context if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -591,8 +590,7 @@ grpc::Status engine_impl::AddServiceComment(grpc::ServerContext* context if (it != service::services.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service ('{}', '{}')", - request->host_name(), request->svc_desc()); + err = fmt::format("could not find service ('{}', '{}')", request->host_name(), request->svc_desc()); return 1; } auto it2 = host::hosts.find(request->host_name()); @@ -608,9 +606,8 @@ grpc::Status engine_impl::AddServiceComment(grpc::ServerContext* context temp_service->get_service_id(), request->entry_time(), request->user(), request->comment_data(), request->persistent(), comment::external, false, (time_t)0); - if (!cmt) { - err = - fmt::format("could not insert comment '{}'", request->comment_data()); + if (!cmt) { + err = fmt::format("could not insert comment '{}'", request->comment_data()); return 1; } comment::comments.insert({cmt->get_comment_id(), cmt}); @@ -622,7 +619,7 @@ grpc::Status engine_impl::AddServiceComment(grpc::ServerContext* context if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -646,7 +643,8 @@ grpc::Status engine_impl::DeleteComment(grpc::ServerContext* context return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "comment_id must not be set to 0"); - auto fn = std::packaged_task([&err, &comment_id]() -> int32_t { + auto fn = std::packaged_task([&err, &comment_id]() + -> int32_t { if (comment::delete_comment(comment_id)) return 0; else { @@ -660,7 +658,7 @@ grpc::Status engine_impl::DeleteComment(grpc::ServerContext* context if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -678,6 +676,7 @@ grpc::Status engine_impl::DeleteAllHostComments(grpc::ServerContext* context const HostIdentifier* request, CommandSuccess* response __attribute__((unused))) { + std::string err; auto fn = std::packaged_task([&err, request]() -> int32_t { std::shared_ptr temp_host; @@ -718,7 +717,7 @@ grpc::Status engine_impl::DeleteAllHostComments(grpc::ServerContext* context if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -750,8 +749,7 @@ grpc::Status engine_impl::DeleteAllServiceComments( if (it != service::services.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service '{}', '{}'", - names.host_name(), names.service_name()); + err = fmt::format("could not find service '{}', '{}'", names.host_name(), names.service_name()); return 1; } } break; @@ -762,9 +760,8 @@ grpc::Status engine_impl::DeleteAllServiceComments( service::services_by_id.find({ids.host_id(), ids.service_id()}); if (it != service::services_by_id.end()) temp_service = it->second; - if (temp_service == nullptr) { - err = fmt::format("could not find service {}, {}", ids.host_id(), - ids.service_id()); + if (temp_service == nullptr) { + err = fmt::format("could not find service {}, {}", ids.host_id(), ids.service_id()); return 1; } } break; @@ -783,7 +780,7 @@ grpc::Status engine_impl::DeleteAllServiceComments( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -847,7 +844,7 @@ grpc::Status engine_impl::RemoveHostAcknowledgement( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -879,8 +876,7 @@ grpc::Status engine_impl::RemoveServiceAcknowledgement( if (it != service::services.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service ('{}', '{}')", - names.host_name(), names.service_name()); + err = fmt::format("could not find service ('{}', '{}')", names.host_name(), names.service_name()); return 1; } } break; @@ -892,8 +888,7 @@ grpc::Status engine_impl::RemoveServiceAcknowledgement( if (it != service::services_by_id.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service ({}, {})", ids.host_id(), - ids.service_id()); + err = fmt::format("could not find service ({}, {})", ids.host_id(), ids.service_id()); return 1; } } break; @@ -918,7 +913,7 @@ grpc::Status engine_impl::RemoveServiceAcknowledgement( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -981,7 +976,7 @@ grpc::Status engine_impl::AcknowledgementHostProblem( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -997,14 +992,12 @@ grpc::Status engine_impl::AcknowledgementServiceProblem( if (it != service::services.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service '{}', '{}'", - request->host_name(), request->service_desc()); + err = fmt::format("could not find service '{}', '{}'", request->host_name(), request->service_desc()); return 1; } /* cannot acknowledge a non-existent problem */ if (temp_service->get_current_state() == service::state_ok) { - err = fmt::format("state of service '{}', '{}' is up", - request->host_name(), request->service_desc()); + err = fmt::format("state of service '{}', '{}' is up", request->host_name(), request->service_desc()); return 1; } /* set the acknowledgement flag */ @@ -1047,7 +1040,7 @@ grpc::Status engine_impl::AcknowledgementServiceProblem( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -1103,10 +1096,10 @@ grpc::Status engine_impl::ScheduleHostDowntime( request->comment_data().c_str(), request->start(), request->end(), request->fixed(), request->triggered_by(), duration, &downtime_id); if (res == ERROR) { - err = fmt::format("could not schedule downtime of host '{}'", - request->host_name()); + err = fmt::format("could not schedule downtime of host '{}'", request->host_name()); return 1; - } else { + } + else { return 0; } }); @@ -1116,7 +1109,7 @@ grpc::Status engine_impl::ScheduleHostDowntime( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else { + else { response->set_value(1); return grpc::Status::OK; } @@ -1162,8 +1155,7 @@ grpc::Status engine_impl::ScheduleServiceDowntime( if (it != service::services.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service '{}', '{}'", - request->host_name(), request->service_desc()); + err = fmt::format("could not find service '{}', '{}'", request->host_name(), request->service_desc()); return 1; } if (request->fixed()) @@ -1178,9 +1170,8 @@ grpc::Status engine_impl::ScheduleServiceDowntime( request->author().c_str(), request->comment_data().c_str(), request->start(), request->end(), request->fixed(), request->triggered_by(), duration, &downtime_id); - if (res == ERROR) { - err = fmt::format("could not schedule downtime of service '{}', '{}'", - request->host_name(), request->service_desc()); + if (res == ERROR) { + err = fmt::format("could not schedule downtime of service '{}', '{}'", request->host_name(), request->service_desc()); return 1; } else return 0; @@ -1191,7 +1182,7 @@ grpc::Status engine_impl::ScheduleServiceDowntime( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else { + else { response->set_value(1); return grpc::Status::OK; } @@ -1308,8 +1299,7 @@ grpc::Status engine_impl::ScheduleHostGroupHostsDowntime( hostgroup_map::const_iterator it( hostgroup::hostgroups.find(request->host_group_name())); if (it == hostgroup::hostgroups.end() || !it->second) { - err = fmt::format("could not find host group name '{}'", - request->host_group_name()); + err = fmt::format("could not find host group name '{}'", request->host_group_name()); return 1; } hg = it->second.get(); @@ -1336,7 +1326,7 @@ grpc::Status engine_impl::ScheduleHostGroupHostsDowntime( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else { + else { response->set_value(1); return grpc::Status::OK; } @@ -1381,8 +1371,7 @@ grpc::Status engine_impl::ScheduleHostGroupServicesDowntime( hostgroup_map::const_iterator it( hostgroup::hostgroups.find(request->host_group_name())); if (it == hostgroup::hostgroups.end() || !it->second) { - err = fmt::format("could not find host group name '{}'", - request->host_group_name()); + err = fmt::format("could not find host group name '{}'", request->host_group_name()); return 1; } hg = it->second.get(); @@ -1465,8 +1454,7 @@ grpc::Status engine_impl::ScheduleServiceGroupHostsDowntime( /* verify that the servicegroup is valid */ sg_it = servicegroup::servicegroups.find(request->service_group_name()); if (sg_it == servicegroup::servicegroups.end() || !sg_it->second) { - err = fmt::format("could not find servicegroupname '{}'", - request->service_group_name()); + err = fmt::format("could not find servicegroupname '{}'", request->service_group_name()); return 1; } if (request->fixed()) @@ -1500,7 +1488,7 @@ grpc::Status engine_impl::ScheduleServiceGroupHostsDowntime( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else { + else { response->set_value(1); return grpc::Status::OK; } @@ -1543,8 +1531,7 @@ grpc::Status engine_impl::ScheduleServiceGroupServicesDowntime( /* verify that the servicegroup is valid */ sg_it = servicegroup::servicegroups.find(request->service_group_name()); if (sg_it == servicegroup::servicegroups.end() || !sg_it->second) { - err = fmt::format("could not find servicegroupname '{}'", - request->service_group_name()); + err = fmt::format("could not find servicegroupname '{}'", request->service_group_name()); return 1; } if (request->fixed()) @@ -1738,23 +1725,22 @@ grpc::Status engine_impl::DeleteDowntime(grpc::ServerContext* context __attribute__((unused))) { uint32_t downtime_id = request->value(); std::string err; - auto fn = - std::packaged_task([&err, &downtime_id]() -> int32_t { - /* deletes scheduled downtime */ - if (downtime_manager::instance().unschedule_downtime(downtime_id) == - ERROR) { - err = fmt::format("could not delete downtime {}", downtime_id); - return 1; - } else - return 0; - }); + auto fn = std::packaged_task([&err, &downtime_id]() -> int32_t { + /* deletes scheduled downtime */ + if (downtime_manager::instance().unschedule_downtime(downtime_id) == ERROR) { + err = fmt::format("could not delete downtime {}", downtime_id); + return 1; + } + else + return 0; + }); std::future result = fn.get_future(); command_manager::instance().enqueue(std::move(fn)); - + if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -1821,7 +1807,7 @@ grpc::Status engine_impl::DeleteHostDowntimeFull( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -1894,7 +1880,7 @@ grpc::Status engine_impl::DeleteServiceDowntimeFull( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -1939,8 +1925,7 @@ grpc::Status engine_impl::DeleteDowntimeByHostName( .delete_downtime_by_hostname_service_description_start_time_comment( host_name, service_desc, start_time, comment_data); if (deleted == 0) { - err = fmt::format("could not delete downtime with hostname '{}'", - request->host_name()); + err = fmt::format("could not delete downtime with hostname '{}'", request->host_name()); return 1; } return 0; @@ -1951,7 +1936,7 @@ grpc::Status engine_impl::DeleteDowntimeByHostName( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -1986,8 +1971,7 @@ grpc::Status engine_impl::DeleteDowntimeByHostGroupName( auto it = hostgroup::hostgroups.find(host_group_name); if (it == hostgroup::hostgroups.end() || !it->second) { - err = fmt::format("could not find host group name '{}'", - request->host_group_name()); + err = fmt::format("could not find host group name '{}'", request->host_group_name()); return 1; } if (!(request->host_name().empty())) @@ -2015,8 +1999,7 @@ grpc::Status engine_impl::DeleteDowntimeByHostGroupName( } if (deleted == 0) { - err = fmt::format("could not delete downtime with host group name '{}'", - request->host_group_name()); + err = fmt::format("could not delete downtime with host group name '{}'", request->host_group_name()); return 1; } return 0; @@ -2027,7 +2010,7 @@ grpc::Status engine_impl::DeleteDowntimeByHostGroupName( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2067,8 +2050,7 @@ grpc::Status engine_impl::DeleteDowntimeByStartTimeComment( .delete_downtime_by_hostname_service_description_start_time_comment( "", "", {true, start_time}, comment_data); if (0 == deleted) { - err = fmt::format("could not delete comment with comment_data '{}'", - comment_data); + err = fmt::format("could not delete comment with comment_data '{}'", comment_data); return 1; } return 0; @@ -2078,7 +2060,7 @@ grpc::Status engine_impl::DeleteDowntimeByStartTimeComment( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2125,7 +2107,7 @@ grpc::Status engine_impl::ScheduleHostCheck(grpc::ServerContext* context if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2179,7 +2161,7 @@ grpc::Status engine_impl::ScheduleHostServiceCheck( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2214,8 +2196,7 @@ grpc::Status engine_impl::ScheduleServiceCheck( if (it != service::services.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service '{}', '{}'", - request->host_name(), request->service_desc()); + err = fmt::format("could not find service '{}', '{}'", request->host_name(), request->service_desc()); return 1; } if (!request->force()) @@ -2231,7 +2212,7 @@ grpc::Status engine_impl::ScheduleServiceCheck( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2277,7 +2258,7 @@ grpc::Status engine_impl::SignalProcess(grpc::ServerContext* context if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2334,7 +2315,7 @@ grpc::Status engine_impl::DelayHostNotification( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2364,8 +2345,7 @@ grpc::Status engine_impl::DelayServiceNotification( if (it != service::services.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service ('{}', '{}')", - names.host_name(), names.service_name()); + err = fmt::format("could not find service ('{}', '{}')", names.host_name(), names.service_name()); return 1; } } break; @@ -2376,8 +2356,7 @@ grpc::Status engine_impl::DelayServiceNotification( if (it != service::services_by_id.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service ({}, {})", ids.host_id(), - ids.service_id()); + err = fmt::format("could not find service ({}, {})", ids.host_id(), ids.service_id()); return 1; } } break; @@ -2397,7 +2376,7 @@ grpc::Status engine_impl::DelayServiceNotification( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2491,7 +2470,7 @@ grpc::Status engine_impl::ChangeHostObjectIntVar(grpc::ServerContext* context if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2509,8 +2488,7 @@ grpc::Status engine_impl::ChangeServiceObjectIntVar( if (it != service::services.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service '{}', '{}'", - request->host_name(), request->service_desc()); + err = fmt::format("could not find service '{}', '{}'", request->host_name(), request->service_desc()); return 1; } if (ChangeObjectInt::Mode_Name(request->mode()) == @@ -2587,7 +2565,7 @@ grpc::Status engine_impl::ChangeServiceObjectIntVar( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2643,7 +2621,7 @@ grpc::Status engine_impl::ChangeContactObjectIntVar( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else response->set_value(result.get()); return grpc::Status::OK; @@ -2687,18 +2665,15 @@ grpc::Status engine_impl::ChangeHostObjectCharVar( if (found != timeperiod::timeperiods.end()) temp_timeperiod = found->second.get(); if (temp_timeperiod == nullptr) { - err = fmt::format("could not find timeperiod with value '{}'", - request->charval()); + err = fmt::format("could not find timeperiod with value '{}'", request->charval()); return 1; } } /* make sure the command exists */ else { cmd_found = commands::command::commands.find(request->charval()); - if (cmd_found == commands::command::commands.end() || - !cmd_found->second) { - err = - fmt::format("no command found with value '{}'", request->charval()); + if (cmd_found == commands::command::commands.end() || !cmd_found->second) { + err = fmt::format("no command found with value '{}'", request->charval()); return 1; } } @@ -2768,7 +2743,7 @@ grpc::Status engine_impl::ChangeHostObjectCharVar( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2798,8 +2773,7 @@ grpc::Status engine_impl::ChangeServiceObjectCharVar( if (it != service::services.end()) temp_service = it->second; if (temp_service == nullptr) { - err = fmt::format("could not find service ('{}', '{}')", - request->host_name(), request->service_desc()); + err = fmt::format("could not find service ('{}', '{}')", request->host_name(), request->service_desc()); return 1; } } @@ -2812,8 +2786,7 @@ grpc::Status engine_impl::ChangeServiceObjectCharVar( if (found != timeperiod::timeperiods.end()) temp_timeperiod = found->second.get(); if (temp_timeperiod == nullptr) { - err = fmt::format("could not find timeperiod with value '{}'", - request->charval()); + err = fmt::format("could not find timeperiod with value '{}'", request->charval()); return 1; } } @@ -2822,8 +2795,7 @@ grpc::Status engine_impl::ChangeServiceObjectCharVar( cmd_found = commands::command::commands.find(request->charval()); if (cmd_found == commands::command::commands.end() || !cmd_found->second) { - err = - fmt::format("no command found with value '{}'", request->charval()); + err = fmt::format("no command found with value '{}'", request->charval()); return 1; } } @@ -2894,7 +2866,7 @@ grpc::Status engine_impl::ChangeServiceObjectCharVar( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -2925,8 +2897,7 @@ grpc::Status engine_impl::ChangeContactObjectCharVar( if (found != timeperiod::timeperiods.end()) temp_timeperiod = found->second.get(); if (temp_timeperiod == nullptr) { - err = fmt::format("could not find timeperiod with value '{}'", - request->charval()); + err = fmt::format("could not find timeperiod with value '{}'", request->charval()); return 1; } if (ChangeContactObjectChar::Mode_Name(request->mode()) == @@ -2969,7 +2940,7 @@ grpc::Status engine_impl::ChangeContactObjectCharVar( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -3011,7 +2982,7 @@ grpc::Status engine_impl::ChangeHostObjectCustomVar( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -3037,8 +3008,7 @@ grpc::Status engine_impl::ChangeServiceObjectCustomVar( if (it_s != service::services.end()) temp_service = it_s->second.get(); if (temp_service == nullptr) { - err = fmt::format("could not find service ('{}', '{}')", - request->host_name(), request->service_desc()); + err = fmt::format("could not find service ('{}', '{}')", request->host_name(), request->service_desc()); return 1; } map_customvar::iterator it(temp_service->custom_variables.find(varname)); @@ -3057,7 +3027,7 @@ grpc::Status engine_impl::ChangeServiceObjectCustomVar( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } @@ -3097,7 +3067,7 @@ grpc::Status engine_impl::ChangeContactObjectCustomVar( if (result.get()) return grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, err); - else + else return grpc::Status::OK; } diff --git a/centreon-engine/enginerpc/enginerpc.cc b/centreon-engine/enginerpc/enginerpc.cc index 4e436260cfd..7cf124d7ef6 100644 --- a/centreon-engine/enginerpc/enginerpc.cc +++ b/centreon-engine/enginerpc/enginerpc.cc @@ -17,10 +17,10 @@ * */ -#include "com/centreon/engine/enginerpc.hh" #include -#include #include "com/centreon/engine/logging/logger.hh" +#include +#include "com/centreon/engine/enginerpc.hh" using namespace com::centreon::engine; diff --git a/centreon-engine/enginerpc/examples/service_check.py b/centreon-engine/enginerpc/examples/service_check.py index 896a3640ae6..5ad62e8e437 100755 --- a/centreon-engine/enginerpc/examples/service_check.py +++ b/centreon-engine/enginerpc/examples/service_check.py @@ -10,13 +10,13 @@ def run(): with grpc.insecure_channel("127.0.0.1:{}".format(sys.argv[1])) as channel: stub = engine_pb2_grpc.EngineStub(channel) k = 0.0 - for j in range(10000): - print("Step{}".format(j)) + for j in range(100000): now = time.time() seconds = int(now) nanos = int((now - seconds) * 10**9) timestamp = timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos) for i in range(1, 200): + print("Step{}".format(i)) check = stub.ProcessServiceCheckResult(engine_pb2.Check( check_time=timestamp, host_name = 'ceïntràl', diff --git a/centreon-engine/inc/com/centreon/engine/anomalydetection.hh b/centreon-engine/inc/com/centreon/engine/anomalydetection.hh index 896033a3f6e..0ea46c9a45c 100644 --- a/centreon-engine/inc/com/centreon/engine/anomalydetection.hh +++ b/centreon-engine/inc/com/centreon/engine/anomalydetection.hh @@ -20,9 +20,9 @@ #ifndef CCE_ANOMALYDETECTION_HH #define CCE_ANOMALYDETECTION_HH +#include #include #include -#include #include #include "com/centreon/engine/service.hh" diff --git a/centreon-engine/inc/com/centreon/engine/commands/command_listener.hh b/centreon-engine/inc/com/centreon/engine/commands/command_listener.hh index 567934c9f1c..541c659adad 100644 --- a/centreon-engine/inc/com/centreon/engine/commands/command_listener.hh +++ b/centreon-engine/inc/com/centreon/engine/commands/command_listener.hh @@ -29,7 +29,7 @@ CCE_BEGIN() namespace commands { -class command; + class command; /** * @class command_listener command_listener.hh * @brief Notify command events. @@ -42,7 +42,7 @@ class command_listener { public: virtual ~command_listener() noexcept { for (auto it = _clean_callbacks.begin(), end = _clean_callbacks.end(); - it != end; ++it) { + it != end; ++it) { (it->second)(); } } @@ -51,7 +51,9 @@ class command_listener { void reg(command* const ptr, std::function& regf) { _clean_callbacks.insert({ptr, regf}); } - void unreg(command* const ptr) { _clean_callbacks.erase(ptr); } + void unreg(command* const ptr) { + _clean_callbacks.erase(ptr); + } }; } // namespace commands diff --git a/centreon-engine/inc/com/centreon/engine/configuration/anomalydetection.hh b/centreon-engine/inc/com/centreon/engine/configuration/anomalydetection.hh index f75764e88a1..3e7ce6729a9 100644 --- a/centreon-engine/inc/com/centreon/engine/configuration/anomalydetection.hh +++ b/centreon-engine/inc/com/centreon/engine/configuration/anomalydetection.hh @@ -227,8 +227,7 @@ class anomalydetection : public object { typedef std::shared_ptr anomalydetection_ptr; typedef std::list list_anomalydetection; typedef std::set set_anomalydetection; -typedef std::unordered_map, - anomalydetection_ptr> +typedef std::unordered_map, anomalydetection_ptr> map_anomalydetection; } // namespace configuration diff --git a/centreon-engine/inc/com/centreon/engine/configuration/applier/scheduler.hh b/centreon-engine/inc/com/centreon/engine/configuration/applier/scheduler.hh index 0ff83edd33e..69b1635bfcb 100644 --- a/centreon-engine/inc/com/centreon/engine/configuration/applier/scheduler.hh +++ b/centreon-engine/inc/com/centreon/engine/configuration/applier/scheduler.hh @@ -23,8 +23,8 @@ #include #include #include "com/centreon/engine/configuration/applier/difference.hh" -#include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/configuration/state.hh" // Forward declaration. CCE_BEGIN() diff --git a/centreon-engine/inc/com/centreon/engine/configuration/applier/state.hh b/centreon-engine/inc/com/centreon/engine/configuration/applier/state.hh index eac33f5f3d5..115c945a4c7 100644 --- a/centreon-engine/inc/com/centreon/engine/configuration/applier/state.hh +++ b/centreon-engine/inc/com/centreon/engine/configuration/applier/state.hh @@ -21,8 +21,8 @@ #define CCE_CONFIGURATION_APPLIER_STATE_HH #include -#include #include +#include #include #include "com/centreon/engine/configuration/applier/difference.hh" #include "com/centreon/engine/configuration/state.hh" diff --git a/centreon-engine/inc/com/centreon/engine/configuration/parser.hh b/centreon-engine/inc/com/centreon/engine/configuration/parser.hh index a51edcba2a2..2c3880caf1e 100644 --- a/centreon-engine/inc/com/centreon/engine/configuration/parser.hh +++ b/centreon-engine/inc/com/centreon/engine/configuration/parser.hh @@ -20,8 +20,8 @@ #ifndef CCE_CONFIGURATION_PARSER_HH #define CCE_CONFIGURATION_PARSER_HH -#include #include +#include #include #include "com/centreon/engine/configuration/command.hh" #include "com/centreon/engine/configuration/connector.hh" diff --git a/centreon-engine/inc/com/centreon/engine/downtimes/downtime.hh b/centreon-engine/inc/com/centreon/engine/downtimes/downtime.hh index db0be7f8dd0..10cce56716c 100644 --- a/centreon-engine/inc/com/centreon/engine/downtimes/downtime.hh +++ b/centreon-engine/inc/com/centreon/engine/downtimes/downtime.hh @@ -30,7 +30,11 @@ CCE_BEGIN() namespace downtimes { class downtime { public: - enum type { service_downtime = 1, host_downtime = 2, any_downtime = 3 }; + enum type { + service_downtime = 1, + host_downtime = 2, + any_downtime = 3 + }; downtime(type type, std::string const& host_name, time_t entry_time, diff --git a/centreon-engine/inc/com/centreon/engine/downtimes/downtime_manager.hh b/centreon-engine/inc/com/centreon/engine/downtimes/downtime_manager.hh index 828a93a0aba..9ce44254c0b 100644 --- a/centreon-engine/inc/com/centreon/engine/downtimes/downtime_manager.hh +++ b/centreon-engine/inc/com/centreon/engine/downtimes/downtime_manager.hh @@ -37,8 +37,7 @@ class downtime_manager { void delete_downtime(uint64_t downtime_id); int unschedule_downtime(uint64_t downtime_id); - std::shared_ptr find_downtime(downtime::type type, - uint64_t downtime_id); + std::shared_ptr find_downtime(downtime::type type, uint64_t downtime_id); int check_pending_flex_host_downtime(host* hst); int check_pending_flex_service_downtime(service* svc); void add_downtime(downtime* dt) noexcept; diff --git a/centreon-engine/inc/com/centreon/engine/engine_impl.hh b/centreon-engine/inc/com/centreon/engine/engine_impl.hh index 9cf26739933..68e8375994d 100644 --- a/centreon-engine/inc/com/centreon/engine/engine_impl.hh +++ b/centreon-engine/inc/com/centreon/engine/engine_impl.hh @@ -9,7 +9,7 @@ class engine_impl final : public Engine::Service { grpc::Status GetVersion(grpc::ServerContext* context, const ::google::protobuf::Empty* /*request*/, Version* response) override; - grpc::Status GetStats(grpc::ServerContext* context, + grpc::Status GetStats(grpc::ServerContext* context, const GenericString* request, Stats* response) override; grpc::Status ProcessServiceCheckResult(grpc::ServerContext* context, @@ -118,8 +118,8 @@ class engine_impl final : public Engine::Service { const ScheduleDowntimeIdentifier* request, CommandSuccess* response) override; grpc::Status DeleteDowntime(grpc::ServerContext* context, - const GenericValue* request, - CommandSuccess* response) override; + const GenericValue* request, + CommandSuccess* response) override; grpc::Status DeleteHostDowntimeFull(grpc::ServerContext* context, const DowntimeCriterias* request, CommandSuccess* response) override; @@ -187,8 +187,8 @@ class engine_impl final : public Engine::Service { const ChangeObjectCustomVar* request, CommandSuccess* response) override; grpc::Status ShutdownProgram(grpc::ServerContext* context, - const ::google::protobuf::Empty*, - ::google::protobuf::Empty*) override; + const ::google::protobuf::Empty*, + ::google::protobuf::Empty*) override; }; CCE_END() diff --git a/centreon-engine/inc/com/centreon/engine/events/loop.hh b/centreon-engine/inc/com/centreon/engine/events/loop.hh index dfb7579c236..47863d8b71c 100644 --- a/centreon-engine/inc/com/centreon/engine/events/loop.hh +++ b/centreon-engine/inc/com/centreon/engine/events/loop.hh @@ -57,7 +57,11 @@ class loop { void _dispatching(); public: - enum priority { low = 0, high = 1, priority_num }; + enum priority { + low = 0, + high = 1, + priority_num + }; static loop& instance(); void clear(); @@ -69,7 +73,9 @@ class loop { void remove_downtime(uint64_t downtime_id); void remove_event(timed_event* event, priority priority); void remove_events(priority, uint32_t event_type, void* data) noexcept; - timed_event* find_event(priority priority, uint32_t event_type, void* data); + timed_event* find_event(priority priority, + uint32_t event_type, + void* data); void reschedule_event(timed_event* event, priority priority); void resort_event_list(priority priority); void schedule(timed_event* evt, bool high_priority); diff --git a/centreon-engine/inc/com/centreon/engine/events/timed_event.hh b/centreon-engine/inc/com/centreon/engine/events/timed_event.hh index acd70d1baaa..66d712a7d0d 100644 --- a/centreon-engine/inc/com/centreon/engine/events/timed_event.hh +++ b/centreon-engine/inc/com/centreon/engine/events/timed_event.hh @@ -23,9 +23,9 @@ #ifndef CCE_EVENTS_TIMED_EVENT_HH #define CCE_EVENTS_TIMED_EVENT_HH +#include #include #include -#include #include "com/centreon/engine/downtimes/downtime.hh" #include "com/centreon/engine/namespace.hh" diff --git a/centreon-engine/inc/com/centreon/engine/exceptions/error.hh b/centreon-engine/inc/com/centreon/engine/exceptions/error.hh index bc0abdb0129..80d53bd3614 100644 --- a/centreon-engine/inc/com/centreon/engine/exceptions/error.hh +++ b/centreon-engine/inc/com/centreon/engine/exceptions/error.hh @@ -61,7 +61,7 @@ class error : public std::exception { char const* what() const throw() override; }; -} // namespace exceptions +} CCE_END() diff --git a/centreon-engine/inc/com/centreon/engine/my_lock.hh b/centreon-engine/inc/com/centreon/engine/my_lock.hh index 4be35dfe334..f5273a7622f 100644 --- a/centreon-engine/inc/com/centreon/engine/my_lock.hh +++ b/centreon-engine/inc/com/centreon/engine/my_lock.hh @@ -1,5 +1,5 @@ -#include #include +#include template class my_lock_guard : public std::lock_guard { @@ -8,15 +8,12 @@ class my_lock_guard : public std::lock_guard { M* _m; public: - my_lock_guard(M& m, const char* file, int line) - : std::lock_guard(m), _file{file}, _line{line}, _m(&m) { - std::cout << "Lock(G): " << _file << ": " << _m << ":" << _line - << std::endl; + my_lock_guard(M& m, const char* file, int line) : std::lock_guard(m), _file{file}, _line{line}, _m(&m) { + std::cout << "Lock(G): " << _file << ": " << _m << ":" << _line << std::endl; } ~my_lock_guard() { - std::cout << "Unlock(G): " << _file << ": " << _m << ":" << _line - << std::endl; + std::cout << "Unlock(G): " << _file << ": " << _m << ":" << _line << std::endl; } }; @@ -27,20 +24,16 @@ class my_unique_lock : public std::unique_lock { M* _m; public: - my_unique_lock(M& m, const char* file, int line) - : std::unique_lock(m), _file{file}, _line{line}, _m{&m} { - std::cout << "Lock(U): " << _file << ": " << _m << ":" << _line - << std::endl; + my_unique_lock(M& m, const char* file, int line) : std::unique_lock(m), _file{file}, _line{line}, _m{&m} { + std::cout << "Lock(U): " << _file << ": " << _m << ":" << _line << std::endl; } ~my_unique_lock() { - std::cout << "Destroy Lock(U): " << _file << ": " << _m << ":" << _line - << std::endl; + std::cout << "Destroy Lock(U): " << _file << ": " << _m << ":" << _line << std::endl; } void unlock(int line) { - std::cout << "unlock(): " << _file << ": " << _m << ":" << line - << std::endl; + std::cout << "unlock(): " << _file << ": " << _m << ":" << line << std::endl; std::unique_lock::unlock(); } diff --git a/centreon-engine/inc/com/centreon/engine/nebstructs.hh b/centreon-engine/inc/com/centreon/engine/nebstructs.hh index c9cdc103bbf..3fe26753828 100644 --- a/centreon-engine/inc/com/centreon/engine/nebstructs.hh +++ b/centreon-engine/inc/com/centreon/engine/nebstructs.hh @@ -320,8 +320,8 @@ typedef struct nebstruct_flapping_struct { struct timeval timestamp; int flapping_type; - uint64_t host_id; - uint64_t service_id; + uint64_t host_id; + uint64_t service_id; double percent_change; double high_threshold; double low_threshold; diff --git a/centreon-engine/inc/com/centreon/engine/notifier.hh b/centreon-engine/inc/com/centreon/engine/notifier.hh index 6f44b169761..d1ec780c159 100644 --- a/centreon-engine/inc/com/centreon/engine/notifier.hh +++ b/centreon-engine/inc/com/centreon/engine/notifier.hh @@ -114,8 +114,8 @@ class notifier : public checkable { uint32_t recovery_notification_delay, std::string const& notification_period, bool notifications_enabled, - const std::string& check_period, - const std::string& event_handler, + std::string const& check_period, + std::string const& event_handler, bool event_handler_enabled, std::string const& notes, std::string const& notes_url, diff --git a/centreon-engine/inc/com/centreon/engine/opt.hh b/centreon-engine/inc/com/centreon/engine/opt.hh index c4469051906..6d00eb0a05f 100644 --- a/centreon-engine/inc/com/centreon/engine/opt.hh +++ b/centreon-engine/inc/com/centreon/engine/opt.hh @@ -49,7 +49,7 @@ class opt { bool operator<(opt const& right) const throw() { return (_data < right._data); } - operator T const &() const throw() { return (_data); } + operator T const&() const throw() { return (_data); } T& operator*() throw() { return (_data); } T const& operator*() const throw() { return (_data); } T* operator->() throw() { return (&_data); } diff --git a/centreon-engine/inc/com/centreon/engine/service.hh b/centreon-engine/inc/com/centreon/engine/service.hh index 04696684dde..432e4dda372 100644 --- a/centreon-engine/inc/com/centreon/engine/service.hh +++ b/centreon-engine/inc/com/centreon/engine/service.hh @@ -1,5 +1,5 @@ /* -** Copyright 2011-2021 Centreon +** Copyright 2011-2019 Centreon ** ** This file is part of Centreon Engine. ** diff --git a/centreon-engine/inc/com/centreon/engine/statistics.hh b/centreon-engine/inc/com/centreon/engine/statistics.hh index 78db97f2344..296ab38961a 100644 --- a/centreon-engine/inc/com/centreon/engine/statistics.hh +++ b/centreon-engine/inc/com/centreon/engine/statistics.hh @@ -20,9 +20,9 @@ #ifndef CCE_STATISTICS_HH #define CCE_STATISTICS_HH +#include #include #include -#include #include "com/centreon/engine/namespace.hh" struct buffer_stats { @@ -34,7 +34,6 @@ struct buffer_stats { CCE_BEGIN() class statistics { statistics(); - public: static statistics& instance(); pid_t get_pid() const noexcept; diff --git a/centreon-engine/inc/com/centreon/engine/timezone_manager.hh b/centreon-engine/inc/com/centreon/engine/timezone_manager.hh index cfadc1b0369..a80c12df795 100644 --- a/centreon-engine/inc/com/centreon/engine/timezone_manager.hh +++ b/centreon-engine/inc/com/centreon/engine/timezone_manager.hh @@ -44,10 +44,7 @@ class timezone_manager { * * @return Class instance. */ - static timezone_manager& instance() { - static timezone_manager instance; - return instance; - } + static timezone_manager& instance() { static timezone_manager instance; return instance; } private: struct tz_info { diff --git a/centreon-engine/inc/com/centreon/engine/version.hh.in b/centreon-engine/inc/com/centreon/engine/version.hh.in index c6f1dd8ede7..b442c09fa96 100644 --- a/centreon-engine/inc/com/centreon/engine/version.hh.in +++ b/centreon-engine/inc/com/centreon/engine/version.hh.in @@ -21,9 +21,9 @@ #define CCE_VERSION_HH // Compile-time values. -#define CENTREON_ENGINE_VERSION_MAJOR @COLLECT_MAJOR@ -#define CENTREON_ENGINE_VERSION_MINOR @COLLECT_MINOR@ -#define CENTREON_ENGINE_VERSION_PATCH @COLLECT_PATCH@ +#define CENTREON_ENGINE_VERSION_MAJOR @CENTREON_ENGINE_MAJOR@ +#define CENTREON_ENGINE_VERSION_MINOR @CENTREON_ENGINE_MINOR@ +#define CENTREON_ENGINE_VERSION_PATCH @CENTREON_ENGINE_PATCH@ #define CENTREON_ENGINE_VERSION_STRING "@CENTREON_ENGINE_VERSION@" #endif // !CCE_VERSION_HH diff --git a/centreon-engine/modules/bench/CMakeLists.txt b/centreon-engine/modules/bench/CMakeLists.txt index e11df844d66..9da932ae96f 100644 --- a/centreon-engine/modules/bench/CMakeLists.txt +++ b/centreon-engine/modules/bench/CMakeLists.txt @@ -32,16 +32,16 @@ if (WITH_BENCH) set_target_properties("bench_passive_module" PROPERTIES PREFIX "") install(TARGETS "bench_passive_module" - DESTINATION "${ENGINE_MODULES_DIR}" + DESTINATION "${PREFIX_LIB}" COMPONENT "bench") # Passive checks benchmarking command line tool. add_executable("centengine_bench_passive" "${SRC_DIR}/passive/engine_cfg.cc" "${SRC_DIR}/passive/main.cc") - add_dependencies("centengine_bench_passive" centreon_clib) + add_dependencies("centengine_bench_passive" centreon_clib_shared) target_link_libraries("centengine_bench_passive" centreon_clib) install(TARGETS "centengine_bench_passive" - DESTINATION "${CMAKE_INSTALL_FULL_SBINDIR}" + DESTINATION "${PREFIX_BIN}" COMPONENT "bench") endif () diff --git a/centreon-engine/modules/external_commands/CMakeLists.txt b/centreon-engine/modules/external_commands/CMakeLists.txt index fdbe9800724..21958dcbcca 100644 --- a/centreon-engine/modules/external_commands/CMakeLists.txt +++ b/centreon-engine/modules/external_commands/CMakeLists.txt @@ -46,12 +46,16 @@ add_library( ) # Prettier name. set_property(TARGET "externalcmd" PROPERTY PREFIX "") - +# Location. +get_property( + EXTERNALCMD_MODULE + TARGET "externalcmd" + PROPERTY LOCATION) set(EXTERNALCMD_MODULE "${EXTERNALCMD_MODULE}" PARENT_SCOPE) -add_dependencies(externalcmd centreon_clib) +add_dependencies(externalcmd centreon_clib_shared) target_link_libraries(externalcmd centreon_clib) # Install rule. install(TARGETS "externalcmd" - DESTINATION "${ENGINE_MODULES_DIR}" + DESTINATION "${PREFIX_LIB}" COMPONENT "runtime") diff --git a/centreon-engine/modules/external_commands/inc/com/centreon/engine/modules/external_commands/processing.hh b/centreon-engine/modules/external_commands/inc/com/centreon/engine/modules/external_commands/processing.hh index 33aedd12a0d..020f954ca54 100644 --- a/centreon-engine/modules/external_commands/inc/com/centreon/engine/modules/external_commands/processing.hh +++ b/centreon-engine/modules/external_commands/inc/com/centreon/engine/modules/external_commands/processing.hh @@ -257,9 +257,7 @@ class processing { } template - static void _redirector_file(int id __attribute__((unused)), - time_t entry_time __attribute__((unused)), - char* args) { + static void _redirector_file(int id __attribute__((unused)), time_t entry_time __attribute__((unused)), char* args) { char* filename(my_strtok(args, ";")); (*fptr)(filename); } diff --git a/centreon-engine/modules/external_commands/src/utils.cc b/centreon-engine/modules/external_commands/src/utils.cc index 86fa22496a8..d2f14a1340a 100644 --- a/centreon-engine/modules/external_commands/src/utils.cc +++ b/centreon-engine/modules/external_commands/src/utils.cc @@ -318,8 +318,7 @@ int shutdown_command_file_worker_thread(void) { should_exit = true; /* wait for the worker thread to exit */ - if (worker && worker->joinable()) - worker->join(); + worker->join(); } return OK; diff --git a/centreon-engine/packaging/rpm/centreon-engine.spectemplate b/centreon-engine/packaging/rpm/centreon-engine.spectemplate new file mode 100644 index 00000000000..b09286387d4 --- /dev/null +++ b/centreon-engine/packaging/rpm/centreon-engine.spectemplate @@ -0,0 +1,506 @@ +## +## Copyright 2011-2020 Centreon +## + +%if 0%{?suse_version} +%define group "System/Monitoring" +%else +%define group "Applications/System" +%endif +%define user centreon-engine + +Name: centreon-engine +Version: %{VERSION} +Release: %{RELEASE}%{?dist} +Summary: Centreon Engine monitoring core. +%define thismajor 22.04.0 +%define nextmajor 22.05.0 + +Group: %{group} +License: GPLv2 +URL: https://github.com/centreon/centreon-engine +Packager: Matthieu Kermagoret +Vendor: Centreon Entreprise Server (CES) Repository, http://yum.centreon.com/standard/ + +Source0: %{name}-%{version}.tar.gz +Source1: centreonengine_integrate_centreon_engine2centreon.sh +BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root + +BuildRequires: cmake3 >= 3.15 + +BuildRequires: gcc +BuildRequires: gcc-c++ +BuildRequires: make +BuildRequires: centreon-clib-devel >= %{thismajor} +BuildRequires: centreon-clib-devel < %{nextmajor} +BuildRequires: systemd +Requires: %{name}-daemon = %{version}-%{release} +Requires: %{name}-extcommands = %{version}-%{release} + +%description +Centreon Engine is a monitoring engine, compatible with Nagios +configuration, designed to monitor hosts and services on your network. + +%package daemon +Summary: Centreon Engine Daemon is the daemon to schedule checks. +Group: %{group} +Requires: centreon-clib >= %{thismajor} +Requires: centreon-clib < %{nextmajor} +%{?systemd_requires} + +%description daemon +Centreon Engine is a monitoring engine that schedule checks on your +network services and hosts. + +%package extcommands +Summary: Centreon Engine External Commands allow to other applications to send command into the daemon. +Group: %{group} +Requires: %{name}-daemon = %{version}-%{release} + +%description extcommands +Centreon Engine External Commands allow to other applications to send +command into the daemon. External applications can submit commands by +writing to the command file, which is periodically processed by the +engine daemon. + +%package devel +Summary: Provide include files for Centreon Engine. +Group: %{group} +Requires: centreon-clib-devel >= %{thismajor} +Requires: centreon-clib-devel < %{nextmajor} + +%description devel +Centreon Engine devel provide include files to develop Centreon Engine +Modules or Centreon Engine Connector. + +%package bench +Summary: Centreon Engine benchmarking tools. +Group: %{group} +Requires: centreon-clib >= %{thismajor} +Requires: centreon-clib < %{nextmajor} + +%description bench +Some Centreon Engine benchmarking tools. + +%prep +%setup + +%build +pip3 install conan --upgrade +cpp11=$(gcc --version | awk '/gcc/ && ($3+0)>5.0{print 1}') +if [ $cpp11 -eq 1 ] ; then + conan install . -s compiler.libcxx=libstdc++11 --build=missing +else + conan install . -s compiler.libcxx=libstdc++ +fi + +CXXFLAGS="-DNDEBUG -g -O2 -Wno-long-long" cmake3 \ + -DWITH_BENCH=1 \ + -DWITH_CREATE_FILES=0 \ + -DWITH_GROUP_ENGINE=%{user} \ + -DWITH_LOGROTATE_DIR=%{_sysconfdir}/logrotate.d \ + -DWITH_LOGROTATE_SCRIPT=1 \ + -DWITH_PKGCONFIG_DIR=%{_libdir}/pkgconfig \ + -DWITH_PKGCONFIG_SCRIPT=1 \ + -DWITH_STARTUP_SCRIPT=systemd \ + -DWITH_PREFIX=%{_prefix} \ + -DWITH_PREFIX_BIN=%{_sbindir} \ + -DWITH_PREFIX_CONF_ENGINE=%{_sysconfdir}/centreon-engine \ + -DWITH_PREFIX_LIB_ENGINE=%{_libdir}/centreon-engine \ + -DWITH_RW_DIR=%{_localstatedir}/lib/centreon-engine/rw \ + -DWITH_STARTUP_DIR=%{_unitdir} \ + -DWITH_TESTING=0 \ + -DWITH_USER_ENGINE=%{user} \ + -DWITH_VAR_DIR=%{_localstatedir}/log/centreon-engine +%{__make} %{?jobs:-j%jobs} %{?_smp_mflags} VERBOSE="1" + +%install +%{__rm} -rf $RPM_BUILD_ROOT +%{__make} -j9 install DESTDIR="$RPM_BUILD_ROOT" +# Engine 2.x +#%{__install} -d $RPM_BUILD_ROOT%{_sysconfdir}/centreon-engine +#%{__install} -d $RPM_BUILD_ROOT%{_sysconfdir}/centreon-engine/conf.d +#%{__install} -d $RPM_BUILD_ROOT%{_sysconfdir}/centreon-engine/objects.d +%{__install} -d $RPM_BUILD_ROOT%{_localstatedir}/log/centreon-engine +%{__install} -d $RPM_BUILD_ROOT%{_localstatedir}/log/centreon-engine/archives +%{__install} -d $RPM_BUILD_ROOT%{_localstatedir}/lib/centreon-engine +%{__install} -d $RPM_BUILD_ROOT%{_localstatedir}/lib/centreon-engine/rw +touch $RPM_BUILD_ROOT%{_localstatedir}/log/centreon-engine/centengine.debug +%{__install} -d $RPM_BUILD_ROOT%{_datadir}/centreon-engine/extra +%{__cp} %SOURCE1 $RPM_BUILD_ROOT%{_datadir}/centreon-engine/extra/integrate_centreon_engine2centreon.sh + +%clean +%{__rm} -rf $RPM_BUILD_ROOT + +%pre daemon +if ! id %{user} &>/dev/null; then + %{_sbindir}/useradd -d %{_localstatedir}/lib/centreon-engine -r %{user} &>/dev/null +fi +if id centreon-broker &>/dev/null; then + %{_sbindir}/usermod -a -G %{user} centreon-broker +fi +if id centreon-gorgone &>/dev/null; then + %{_sbindir}/usermod -a -G centreon-gorgone %{user} +fi +%if 0%{?suse_version} + %define httpgroup www +%else +%if 0%{?centos_version} + %define httpgroup apache +%else + %define httpgroup apache +%endif +%endif +if id -g %{httpgroup} &>/dev/null; then + %{_sbindir}/usermod -a -G %{user} %{httpgroup} +fi +if id -g nagios &>/dev/null; then + %{_sbindir}/usermod -a -G %{user} nagios +fi + +%post daemon +%systemd_post centengine.service || : + +%preun daemon +%systemd_preun centengine.service || : + +%files + +%files daemon +%defattr(-,centreon-engine,centreon-engine,-) +%attr(0664,%{user},%{user}) %config(noreplace) %{_sysconfdir}/centreon-engine/centengine.cfg +# Centreon Engine 2.x +#%attr(0775,%{user},%{user}) %config(noreplace) %{_sysconfdir}/centreon-engine/conf.d/ +#%attr(0775,%{user},%{user}) %config(noreplace) %{_sysconfdir}/centreon-engine/objects.d/ +# Centreon Engine 1.x +%attr(0664,%{user},%{user}) %config(noreplace) %{_sysconfdir}/centreon-engine/resource.cfg +%attr(0664,%{user},%{user}) %config(noreplace) %{_sysconfdir}/centreon-engine/objects/*.cfg + +%defattr(-,root,root,-) +%config(noreplace) %{_sysconfdir}/logrotate.d/centengine +%{_unitdir}/centengine.service +%{_sbindir}/centengine +%{_sbindir}/centenginestats +%attr(0775,root,root) %{_datadir}/centreon-engine/extra/integrate_centreon_engine2centreon.sh +%attr(0755,%{user},%{user}) %{_localstatedir}/log/centreon-engine/ +%attr(0755,%{user},%{user}) %dir %{_localstatedir}/lib/centreon-engine/ +%doc license.txt + +%files extcommands +%defattr(-,root,root,-) +%{_libdir}/centreon-engine/externalcmd.so +%attr(0775,%{user},%{user}) %{_localstatedir}/lib/centreon-engine/rw +%doc license.txt + +%files devel +%defattr(-,root,root,-) +%{_libdir}/pkgconfig/centengine.pc +%{_prefix}/include/centreon-engine +%doc license.txt + +%files bench +%defattr(-,root,root,-) +%{_libdir}/centreon-engine/bench_passive_module.so +%{_sbindir}/centengine_bench_passive + +%changelog +* Thu Dec 24 2015 Matthieu Kermagoret 1.5.0-12 +- Do not install rw directory twice. + +* Wed Dec 02 2015 Matthieu Kermagoret 1.5.0-11 +- Fix diagnostic tarball generation in case of invalid configuration file. + +* Wed Nov 25 2015 Alexandre Fouille 1.5.0-10 +- Small fixes to unit tests. + +* Tue Nov 17 2015 Matthieu Kermagoret 1.5.0-9 +- Multiple bugfixes. + +* Tue Nov 10 2015 Alexandre Fouille 1.5.0-8 +- Don't immediately reload at startup. +- Various small fixes. + +* Tue Nov 03 2015 Alexandre Fouille 1.5.0-7 +- Add extended user macros. + +* Tue Oct 27 2015 Matthieu Kermagoret 1.5.0-6 +- Schedule host/service checks if enabled after configuration reload. + +* Mon Oct 26 2015 Matthieu Kermagoret 1.5.0-5 +- Fix configuration reloading mechanism. + +* Thu Oct 22 2015 Matthieu Kermagoret 1.5.0-4 +- Remove support code for failure prediction (which never worked). + +* Fri Oct 16 2015 Alexandre Fouille 1.5.0-3 +- Add hostgroup_id and servicegroup_id in the configuration for hostgroups/servicegroups. +- Add host_id and service_id to hosts/services. + +* Mon Oct 05 2015 Matthieu Kermagoret 1.5.0-2 +- Do not package non-existing centenginews binary. + +* Mon Oct 05 2015 Matthieu Kermagoret 1.5.0-1 +- Handle timezone on hosts, services and contacts. +- Use UNKNOWN state whenever the plugin does not report a valid state. +- New macros HOSTCHILDREN and HOSTPARENTS. + +* Thu Oct 01 2015 Matthieu Kermagoret 1.4.15-6 +- ...but still install Centreon Engine binaries (see 1.4.15-5). + +* Thu Oct 01 2015 Matthieu Kermagoret 1.4.15-5 +- Do not install _sbindir. + +* Tue Sep 29 2015 Matthieu Kermagoret 1.4.15-4 +- Do not warn about missing contact or contact group on hosts and services. + +* Mon Sep 28 2015 Matthieu Kermagoret 1.4.15-3 +- Allow empty groups internal structures to be created. + +* Fri Sep 25 2015 Matthieu Kermagoret 1.4.15-2 +- Allow implicit inheritance of contacts and contact groups of base objects in escalations. + +* Wed Sep 23 2015 Matthieu Kermagoret 1.4.15-1 +- Implicitely inherit contacts of hosts in services. +- Repair additive inheritance flag to work only with first template. + +* Mon Jul 06 2015 Matthieu Kermagoret 1.4.14-4 +- Update of passive checks benchmarking tool. + +* Fri Jun 26 2015 Matthieu Kermagoret 1.4.14-3 +- Update version in binaries (was still 1.4.13). +- Update default paths of benchmarking module. + +* Wed Jun 24 2015 Matthieu Kermagoret 2.0.0-7 +- Use /etc/centreon-engine/conf.d and /etc/centreon-engine/objects.d + +* Mon Jun 22 2015 Matthieu Kermagoret 2.0.0-6 +- Merge changes of the 1.4 branch. + +* Mon Jun 22 2015 Matthieu Kermagoret 1.4.14-2 +- Change /var/lib/centreon-engine and /var/log/centreon-engine modes to 755. + +* Mon Jun 22 2015 Matthieu Kermagoret 1.4.14-1 +- Add some benchmarking tools. + +* Tue May 12 2015 Alexandre Fouille 1.4.13-1 +- Fix an erronuous condition preventing recovery notification from firing. + +* Fri Apr 24 2015 Matthieu Kermagoret 2.0.0-5 +- Inherit check_command property from templates. + +* Fri Apr 24 2015 Matthieu Kermagoret 1.4.12-2 +- Make notification work with MKlivestatus. + +* Thu Apr 23 2015 Matthieu Kermagoret 2.0.0-4 +- Make service check_command really optional. + +* Thu Apr 23 2015 Matthieu Kermagoret 2.0.0-3 +- Update of spec file. + +* Wed Apr 22 2015 Matthieu Kermagoret 2.0.0-2 +- Set default configuration files compatible with Centreon UI. +- Remove resource file. +- Minor cleanup. + +* Thu Apr 16 2015 Matthieu Kermagoret 2.0.0-1 +- Heavily clean the code. +- Remove webservice module. +- Remove notifications system. +- Remove groups (host groups, service groups, contact groups). +- Remove many useless little features and configuration options. + +* Fri Apr 10 2015 Alexandre Fouille 1.4.12-1 +- Don't send recovery notification when it shouldn't. +- Fix the debug level not taken into account in 32 bits architectures. + +* Wed Mar 04 2015 Alexandre Fouille 1.4.11-4 +- Don't send up notification of a service or host in downtime. + +* Mon Mar 02 2015 Alexandre Fouille 1.4.11-3 +- Don't reschedule all the notifications when a notification was not sent. + +* Thu Feb 26 2015 Alexandre Fouille 1.4.11-2 +- Integrate the reschedule check notification fix. + +* Mon Feb 23 2015 Matthieu Kermagoret 1.4.11-1 +- Properly save/restore custom variables to/from retention file. +- Reschedule checks even if notification fail. + +* Fri Jan 23 2015 Alexandre Fouille 1.4.10-2 +- Bump centreon engine version to 1.4.10 + +* Wed Jan 21 2015 Alexandre Fouille 1.4.10-1 +- Fix a crash at the software exit on a non-terminated command. + +* Wed Jan 07 2015 Alexandre Fouille 1.4.9-4 +- Add centreon-broker user to centreon-engine group on install. + +* Thu Dec 18 2014 Alexandre Fouille 1.4.9-3 +- Fix a logical mistake in the notification messages. + +* Wed Dec 17 2014 Alexandre Fouille 1.4.9-2 +- Properly print normal notification messages. +- Correctly fill the service groups compatibility structures. +- Disable existing custom variables at reload. + +* Tue Dec 16 2014 Alexandre Fouille 1.4.9-1 +- Don't segfault when warning that a hostgroup dependency is empty. + +* Mon Oct 20 2014 Alexandre Fouille 1.4.8-3 +- Properly handle end-of-line comments. +- Show an error when objects use illegal object chars. +- Fix object inheritance. Templates were previously only allowed if not registered. + +* Wed Oct 15 2014 Alexandre Fouille 1.4.8-2 +- Fix a bug causing a segfault when the software exits. + +* Mon Oct 13 2014 Alexandre Fouille 1.4.8-1 +- Fix a bug which can cause an host check to be instantly flagged HARD. + +* Thu Sep 04 2014 Alexandre Fouille 1.4.7-1 +- Fix a bug which can cause the checks of hosts to stop being scheduled. + +* Thu Aug 21 2014 Matthieu Kermagoret 1.4.6-2 +- Fix check_command_interval parsing (error in 's' suffix). + +* Tue Aug 19 2014 Matthieu Kermagoret 1.4.6-1 +- Fix compatibility with MKlivestatus. +- Fix command_check_interval parsing (inverted logic with 's'). +- Fix dependencies attached to service groups. +- Fix escalations attached to service groups. +- Fix escalations attached to multiple contacts/contact groups. +- Allow empty contact groups. + +* Fri Aug 01 2014 Matthieu Kermagoret 1.4.5-2 +- Properly scope iteration regarding last fix. + +* Fri Aug 01 2014 Matthieu Kermagoret 1.4.5-1 +- Fix an infinite loop in service escalation validity check. + +* Tue Jun 24 2014 Matthieu Kermagoret 1.4.4-1 +- Fix access of field /address6/ of contacts. +- Properly schedule modified hosts and services. +- Do not allow rescheduling to generate multiple check events. + +* Mon Jun 09 2014 Matthieu Kermagoret 1.4.3-3 +- Fix changelog order. + +* Mon Jun 09 2014 Matthieu Kermagoret 1.4.3-2 +- Modify Clib version required (1.4). + +* Mon Jun 09 2014 Matthieu Kermagoret 1.4.3-1 +- Minor fixes. + +* Wed May 21 2014 Matthieu Kermagoret 1.3.8-2 +- Use the partial check result method to avoid dead lock. + +* Thu Apr 10 2014 Matthieu Kermagoret 1.3.8-1 +- Death of connector could block Engine. +- Need Clib 1.3. + +* Tue Feb 18 2014 Matthieu Kermagoret 1.3.7-1 +- Do not keep plugin input open. + +* Fri Feb 07 2014 Matthieu Kermagoret 1.3.6-1 +- Do not delete command upon restart. + +* Wed Dec 18 2013 Dorian Guillois 1.3.5-1 +- Fix rescheduling dependencies. + +* Wed Nov 20 2013 Remi Werquin 1.4.2-1 +- Minor fixes. + +* Thu Oct 17 2013 Dorian Guillois 1.4.0.5 +- Change centreon-engine spec to use the new cmake package. + +* Thu Oct 17 2013 Dorian Guillois 1.3.4.3 +- Change centreon-engine spec to use the new cmake package. + +* Mon Oct 14 2013 Dorian Guillois 1.3.4-1 +- Fix webservice undefined symbol on i386. + +* Mon Sep 30 2013 Dorian Guillois 1.3.3-1 +- Update to the 1.2 branch of Centreon Clib. + +* Tue Jul 30 2013 Matthieu Kermagoret 1.3.2-1 +- Return connector errors in plugin output + +* Thu May 2 2013 Dorian Guillois 1.3.1-1 +- Fix segfault on process host check result. + +* Wed Jan 16 2013 Julien Mathis 1.3.0-18 +- Don't provides nagios + +* Fri Jan 11 2013 Julien Mathis 1.3.0-17 +- Fix problem with config file right +- Remove touch for status.dat and retention.dat + +* Fri Aug 17 2012 Dorian Guillois 1.3.0-1 +- Replace Qt by centreon-clib library. + +* Tue Jun 26 2012 Maximilien Bersoult 1.1.3-4 +- Fix migration scripts + +* Tue Jun 26 2012 Maximilien Bersoult 1.2.0-6 +- Fix migration scripts + +* Tue Jun 26 2012 Maximilien Bersoult 1.2.0-5 +- Fix no replace configuration file +- Add help to migration scripts + +* Tue Jun 26 2012 Maximilien Bersoult 1.1.3-3 +- Fix no replace configuration file +- Add help to migration scripts + +* Thu Jun 21 2012 Matthieu Kermagoret 1.2.0-4 +- Fix bug preventing log insertion in NEB modules (Centreon Broker, NDO) + +* Thu Jun 21 2012 Matthieu Kermagoret 1.1.3-2 +- Fix release number in sources +- Do not load modules of current directory + +* Wed Jun 20 2012 Matthieu Kermagoret 1.1.3-1 +- Fix bug preventing log insertion in NEB modules (Centreon Broker, NDO) + +* Mon Jun 18 2012 Matthieu Kermagoret 1.2.0-3 +- spec file was not using proper variable to set var directory + +* Mon Jun 18 2012 Matthieu Kermagoret 1.2.0-2 +- Bugfix in configuration sample files + +* Fri Jun 15 2012 Matthieu Kermagoret 1.2.0-1 +- Major performance improvement by using vfork() syscall + +* Mon Jun 04 2012 Maximilien Bersoult 1.1.2-3 +- Remove centengine.cmd +- Add requires redhat-lsb for daemon +- Add integration script for Centreon + +* Mon May 07 2012 Matthieu Kermagoret 1.1.2-2 +- Fix potential termination error + +* Fri Apr 06 2012 Maximilien Bersoult 1.1.2-1 +- New packaging +- Centreon Engine 1.1.2 +- Bugfix parsing command with quote +- Replace command id by command name in log files + +* Mon Mar 05 2012 Cedric Temple 1.1.1-1 +- Update to new version 1.1.1 + +* Thu Mar 01 2012 Cedric Temple 1.1.0-3 +- Do not include all /usr/include/centreon-engine +- Add /var/log/centreon-engine + +* Mon Feb 06 2012 Cedric Temple 1.1.0-2 +- Do not include all /etc/init.d +- Provides nagios* +- Obsolotes nagios* +- gsoap dependancy + +* Tue Jan 31 2012 Cedric Temple 1.1-1 +- Update to new version +- Fix PATH during build and install + +* Tue Oct 18 2011 Julien Mathis 1.0.1-1 +- Initial build diff --git a/packaging/rpm/centreonengine_integrate_centreon_engine2centreon.sh b/centreon-engine/packaging/rpm/centreonengine_integrate_centreon_engine2centreon.sh similarity index 100% rename from packaging/rpm/centreonengine_integrate_centreon_engine2centreon.sh rename to centreon-engine/packaging/rpm/centreonengine_integrate_centreon_engine2centreon.sh diff --git a/centreon-engine/packaging/rpm/debian/centreon-engine.triggers b/centreon-engine/packaging/rpm/debian/centreon-engine.triggers new file mode 100644 index 00000000000..dd866036784 --- /dev/null +++ b/centreon-engine/packaging/rpm/debian/centreon-engine.triggers @@ -0,0 +1 @@ +activate-noawait ldconfig diff --git a/centreon-engine/packaging/rpm/debian/changelog.in b/centreon-engine/packaging/rpm/debian/changelog.in new file mode 100644 index 00000000000..9e4e57c945e --- /dev/null +++ b/centreon-engine/packaging/rpm/debian/changelog.in @@ -0,0 +1,5 @@ +centreon-engine (@VERSION@-@RELEASE@) UNRELEASED; urgency=medium + + * Release. + + -- Matthieu Kermagoret Thu, 13 Jul 2017 10:40:36 +0200 diff --git a/centreon-engine/packaging/rpm/debian/compat b/centreon-engine/packaging/rpm/debian/compat new file mode 100644 index 00000000000..f599e28b8ab --- /dev/null +++ b/centreon-engine/packaging/rpm/debian/compat @@ -0,0 +1 @@ +10 diff --git a/centreon-engine/packaging/rpm/debian/control b/centreon-engine/packaging/rpm/debian/control new file mode 100644 index 00000000000..849cff202bf --- /dev/null +++ b/centreon-engine/packaging/rpm/debian/control @@ -0,0 +1,13 @@ +Source: centreon-engine +Section: net +Priority: optional +Maintainer: Matthieu Kermagoret +Build-Depends: debhelper (>=10), centreon-clib, cmake, lsb-base, make (>=3) +Standards-Version: 3.9.8 +Homepage: https://github.com/centreon/centreon-engine + +Package: centreon-engine +Architecture: any +Depends: centreon-clib, centreon-common, ${shlibs:Depends}, ${misc:Depends} +Description: Centreon Engine is a monitoring engine, compatible with Nagios + configuration, designed to monitor hosts and services on your network. diff --git a/centreon-engine/packaging/rpm/debian/copyright b/centreon-engine/packaging/rpm/debian/copyright new file mode 100644 index 00000000000..4a6a913dec1 --- /dev/null +++ b/centreon-engine/packaging/rpm/debian/copyright @@ -0,0 +1 @@ +See /usr/share/common-licenses/GPL-2 diff --git a/centreon-engine/packaging/rpm/debian/postinst b/centreon-engine/packaging/rpm/debian/postinst new file mode 100755 index 00000000000..a8548eb7150 --- /dev/null +++ b/centreon-engine/packaging/rpm/debian/postinst @@ -0,0 +1,7 @@ +#!/bin/sh + +if [ "$1" = "configure" ] ; then + adduser --system --group --no-create-home centreon-engine + usermod -a -G centreon-engine centreon + chown -R centreon-engine:centreon-engine /etc/centreon-engine /var/lib/centreon-engine /var/log/centreon-engine +fi diff --git a/centreon-engine/packaging/rpm/debian/postrm b/centreon-engine/packaging/rpm/debian/postrm new file mode 100755 index 00000000000..d7c1fb38324 --- /dev/null +++ b/centreon-engine/packaging/rpm/debian/postrm @@ -0,0 +1,5 @@ +#!/bin/sh + +deluser centreon centreon-engine || true +deluser centreon-engine || true +delgroup centreon-engine || true diff --git a/centreon-engine/packaging/rpm/debian/rules b/centreon-engine/packaging/rpm/debian/rules new file mode 100755 index 00000000000..6800b696396 --- /dev/null +++ b/centreon-engine/packaging/rpm/debian/rules @@ -0,0 +1,36 @@ +#!/usr/bin/make -f + +export DH_VERBOSE=1 +ABI=$(shell grep -q "ABI=1" CMakeLists.txt && echo -n 11) +USE_CXX11=$(shell grep -q "ABI=1" CMakeLists.txt && echo -n 1 || echo -n 0) + +%: + dh $@ + +override_dh_auto_configure: + conan install -s arch=$(ARCH) -s compiler.libcxx=libstdc++$(ABI) . + CXXFLAGS="-std=c++11 -DNDEBUG -O2" cmake \ + -DUSE_CXX11_ABI=$(USE_CXX11) \ + -DWITH_PREFIX=/usr \ + -DWITH_PREFIX_CONF=/etc/centreon-engine \ + -DWITH_VAR_DIR=/var/lib/centreon-engine \ + -DWITH_STARTUP_SCRIPT=systemd \ + -DWITH_STARTUP_DIR=/lib/systemd/system \ + -DWITH_BENCH=1 \ + -DWITH_CREATE_FILES=0 \ + -DWITH_GROUP=centreon-engine \ + -DWITH_LOGROTATE_SCRIPT=1 \ + -DWITH_LOGROTATE_DIR=/etc/logrotate.d \ + -DWITH_PKGCONFIG_SCRIPT=0 \ + -DWITH_TESTING=0 \ + -DWITH_USER=centreon-engine \ + . + +override_dh_auto_install: + make install DESTDIR=debian/centreon-engine + mkdir -p debian/centreon-engine/var/lib/centreon-engine/rw + mkdir -p debian/centreon-engine/var/log/centreon-engine + +override_dh_fixperms: + dh_fixperms + chmod -R g+w debian/centreon-engine/etc/centreon-engine debian/centreon-engine/var/lib/centreon-engine debian/centreon-engine/var/log/centreon-engine diff --git a/centreon-engine/packaging/rpm/debian/source/format b/centreon-engine/packaging/rpm/debian/source/format new file mode 100644 index 00000000000..163aaf8d82b --- /dev/null +++ b/centreon-engine/packaging/rpm/debian/source/format @@ -0,0 +1 @@ +3.0 (quilt) diff --git a/centreon-engine/packaging/script/rpmbuild.sh b/centreon-engine/packaging/script/rpmbuild.sh new file mode 100755 index 00000000000..20b58110264 --- /dev/null +++ b/centreon-engine/packaging/script/rpmbuild.sh @@ -0,0 +1,43 @@ +#!/bin/bash + +show_help() { +cat << EOF +Usage: ${0##*/} -n=[yes|no] -v + +This program build Centreon-engine + + -v : major version + -r : release number + -h : help +EOF +exit 2 +} + +VERSION=$1 +RELEASE=$2 + +if [ -z $VERSION ] || [ -z $RELEASE ] ; then + echo "Some or all of the parameters are empty"; + echo $VERSION; + echo $RELEASE; + show_help +fi + +ln -s /usr/bin/cmake3 /usr/bin/cmake + +# dossier racine du nouveau centreon collect +if [ ! -d /root/rpmbuild/SOURCES ] ; then + mkdir -p /root/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} +fi + +cd "../../../" + +mkdir centreon-engine-$VERSION +cp -r centreon-engine/* centreon-engine-$VERSION +tar -czf centreon-engine-$VERSION.tar.gz centreon-engine-$VERSION cmake.sh +mv centreon-engine-$VERSION.tar.gz /root/rpmbuild/SOURCES/ +rm -rf centreon-engine-$VERSION + +cp centreon-engine/packaging/rpm/centreonengine_integrate_centreon_engine2centreon.sh /root/rpmbuild/SOURCES/ +rpmbuild -ba centreon-engine/packaging/rpm/centreon-engine.spectemplate -D "VERSION $VERSION" -D "RELEASE $RELEASE" + diff --git a/centreon-engine/scripts/centengine.service.in b/centreon-engine/scripts/centengine.service.in index 0ca8a3784e2..11a6237963c 100644 --- a/centreon-engine/scripts/centengine.service.in +++ b/centreon-engine/scripts/centengine.service.in @@ -24,10 +24,10 @@ ReloadPropagatedFrom=centreon.service After=cbd.service [Service] -ExecStart=@CMAKE_INSTALL_FULL_SBINDIR@/centengine @PREFIX_ENGINE_CONF@/centengine.cfg +ExecStart=@PREFIX_BIN@/centengine @PREFIX_CONF@/centengine.cfg ExecReload=/bin/kill -HUP $MAINPID Type=simple -User=centreon-engine +User=@USER@ [Install] WantedBy=centreon.service diff --git a/centreon-engine/src/broker.cc b/centreon-engine/src/broker.cc index 8e60d66117b..e91543568fe 100644 --- a/centreon-engine/src/broker.cc +++ b/centreon-engine/src/broker.cc @@ -383,6 +383,7 @@ void broker_aggregated_status_data(int type, // Make callbacks. neb_make_callbacks(NEBCALLBACK_AGGREGATED_STATUS_DATA, &ds); + } /** @@ -707,6 +708,7 @@ void broker_custom_variable(int type, // Make callback. neb_make_callbacks(NEBCALLBACK_CUSTOM_VARIABLE_DATA, &ds); + } /** @@ -909,6 +911,7 @@ void broker_external_command(int type, // Make callbacks. neb_make_callbacks(NEBCALLBACK_EXTERNAL_COMMAND_DATA, &ds); + } /** @@ -996,6 +999,7 @@ void broker_group(int type, // Make callbacks. neb_make_callbacks(NEBCALLBACK_GROUP_DATA, &ds); + } /** @@ -1029,6 +1033,7 @@ void broker_group_member(int type, // Make callbacks. neb_make_callbacks(NEBCALLBACK_GROUP_MEMBER_DATA, &ds); + } /** @@ -1126,7 +1131,7 @@ int broker_host_check(int type, // Free data. delete[] command_buf; - return return_code; + return (return_code); } /** diff --git a/centreon-engine/src/command_manager_old.cc b/centreon-engine/src/command_manager_old.cc new file mode 100644 index 00000000000..8205f2c6eb1 --- /dev/null +++ b/centreon-engine/src/command_manager_old.cc @@ -0,0 +1,223 @@ +/* + * Copyright 2019 Centreon (https://www.centreon.com/) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * For more information : contact@centreon.com + * + */ + +#include "com/centreon/engine/checks/checker.hh" +#include "com/centreon/engine/command_manager.hh" +#include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/logging/logger.hh" + +using namespace com::centreon::engine; +using namespace com::centreon::engine::logging; + +/** + * The default constructor + */ +command_manager::command_manager() {} + +/** + * @brief Just an accessor to the command_manager instance. + * + * @return A reference to the instance. + */ +command_manager& command_manager::instance() { + static command_manager instance; + return instance; +} + +void command_manager::enqueue(std::function&& f) { + std::lock_guard lock(_queue_m); + _queue.push_back(f); +} + +void command_manager::execute() { + std::unique_lock lock(_queue_m); + if (_queue.empty()) + return; + auto end = _queue.end(); + lock.unlock(); + + auto it = _queue.begin(); + while (it != end) { + auto fn = *it; + fn(); + ++it; + _queue.pop_front(); + } +} + +/* submits a passive service check result for later processing */ +int command_manager::process_passive_service_check(time_t check_time, + const std::string& host_name, + const std::string& svc_description, + uint32_t return_code, + const std::string& output) { + const std::string* real_host_name = nullptr; + + /* skip this service check result if we aren't accepting passive service + * checks */ + if (!config->accept_passive_service_checks()) + return ERROR; + + /* make sure we have a reasonable return code */ + if (return_code > 3) + return ERROR; + + /* find the host by its name or address */ + host_map::const_iterator it(host::hosts.find(host_name)); + if (it != host::hosts.end() && it->second) + real_host_name = &host_name; + else { + for (host_map::iterator itt(host::hosts.begin()), end(host::hosts.end()); + itt != end; ++itt) { + if (itt->second && itt->second->get_address() == host_name) { + real_host_name = &itt->first; + it = itt; + break; + } + } + } + + /* we couldn't find the host */ + if (real_host_name == nullptr) { + logger(log_runtime_warning, basic) + << "Warning: Passive check result was received for service '" + << svc_description << "' on host '" << host_name + << "', but the host could not be found!"; + return ERROR; + } + + /* make sure the service exists */ + service_map::const_iterator found( + service::services.find({*real_host_name, svc_description})); + if (found == service::services.end() || !found->second) { + logger(log_runtime_warning, basic) + << "Warning: Passive check result was received for service '" + << svc_description << "' on host '" << host_name + << "', but the service could not be found!"; + return ERROR; + } + + /* skip this is we aren't accepting passive checks for this service */ + if (!found->second->get_accept_passive_checks()) + return ERROR; + + timeval tv; + gettimeofday(&tv, nullptr); + + timeval set_tv = {.tv_sec = check_time, .tv_usec = 0}; + + check_result* result = + new check_result(service_check, + found->second.get(), + checkable::check_passive, + CHECK_OPTION_NONE, + false, + static_cast(tv.tv_sec - check_time) + + static_cast(tv.tv_usec) / 1000000.0, + set_tv, + set_tv, + false, + true, + return_code, + output); + + /* make sure the return code is within bounds */ + if (result->get_return_code() < 0 || result->get_return_code() > 3) + result->set_return_code(service::state_unknown); + + if (result->get_latency() < 0.0) + result->set_latency(0.0); + + checks::checker::instance().add_check_result_to_reap(result); + return OK; +} + +/* process passive host check result */ +int command_manager::process_passive_host_check(time_t check_time, + const std::string& host_name, + uint32_t return_code, + const std::string& output) { + const std::string* real_host_name = nullptr; + + /* skip this host check result if we aren't accepting passive host checks */ + if (!config->accept_passive_service_checks()) + return ERROR; + + /* make sure we have a reasonable return code */ + if (return_code > 2) + return ERROR; + + /* find the host by its name or address */ + host_map::const_iterator it(host::hosts.find(host_name)); + if (it != host::hosts.end() && it->second) + real_host_name = &host_name; + else { + for (host_map::iterator itt(host::hosts.begin()), end(host::hosts.end()); + itt != end; ++itt) { + if (itt->second && itt->second->get_address() == host_name) { + real_host_name = &itt->first; + it = itt; + break; + } + } + } + + /* we couldn't find the host */ + if (real_host_name == nullptr) { + logger(log_runtime_warning, basic) + << "Warning: Passive check result was received for host '" << host_name + << "', but the host could not be found!"; + return ERROR; + } + + /* skip this is we aren't accepting passive checks for this host */ + if (!it->second->get_accept_passive_checks()) + return ERROR; + + timeval tv; + gettimeofday(&tv, nullptr); + timeval tv_start; + tv_start.tv_sec = check_time; + tv_start.tv_usec = 0; + + check_result* result = + new check_result(host_check, + it->second.get(), + checkable::check_passive, + CHECK_OPTION_NONE, + false, + static_cast(tv.tv_sec - check_time) + + static_cast(tv.tv_usec) / 1000000.0, + tv_start, + tv_start, + false, + true, + return_code, + output); + + /* make sure the return code is within bounds */ + if (result->get_return_code() < 0 || result->get_return_code() > 3) + result->set_return_code(service::state_unknown); + + if (result->get_latency() < 0.0) + result->set_latency(0.0); + + checks::checker::instance().add_check_result_to_reap(result); + return OK; +} diff --git a/centreon-engine/src/comment.cc b/centreon-engine/src/comment.cc index b99380a11b5..fea3a318c5f 100644 --- a/centreon-engine/src/comment.cc +++ b/centreon-engine/src/comment.cc @@ -90,12 +90,13 @@ comment::comment(comment::type comment_type, bool comment::delete_comment(uint64_t comment_id) { comment_map::iterator found = comment::comments.find(comment_id); - // check that comment exist + //check that comment exist if (found != comment::comments.end() && found->second) { broker_comment_data( NEBTYPE_COMMENT_DELETE, NEBFLAG_NONE, NEBATTR_NONE, found->second->get_comment_type(), found->second->get_entry_type(), - found->second->get_host_id(), found->second->get_service_id(), + found->second->get_host_id(), + found->second->get_service_id(), found->second->get_entry_time(), found->second->get_author().c_str(), found->second->get_comment_data().c_str(), found->second->get_persistent(), found->second->get_source(), @@ -103,9 +104,8 @@ bool comment::delete_comment(uint64_t comment_id) { comment_id, nullptr); comment::comments.erase(comment_id); return true; - } else { - return false; - } + } + else { return false; } } void comment::delete_host_comments(uint64_t host_id) { @@ -116,8 +116,9 @@ void comment::delete_host_comments(uint64_t host_id) { it->second->get_host_id() == host_id) { broker_comment_data( NEBTYPE_COMMENT_DELETE, NEBFLAG_NONE, NEBATTR_NONE, - it->second->get_comment_type(), it->second->get_entry_type(), host_id, - 0, it->second->get_entry_time(), it->second->get_author().c_str(), + it->second->get_comment_type(), it->second->get_entry_type(), + host_id, 0, it->second->get_entry_time(), + it->second->get_author().c_str(), it->second->get_comment_data().c_str(), it->second->get_persistent(), it->second->get_source(), it->second->get_expires(), it->second->get_expire_time(), it->first, nullptr); @@ -136,9 +137,9 @@ void comment::delete_service_comments(uint64_t host_id, uint64_t service_id) { it->second->get_service_id() == service_id) { broker_comment_data( NEBTYPE_COMMENT_DELETE, NEBFLAG_NONE, NEBATTR_NONE, - it->second->get_comment_type(), it->second->get_entry_type(), host_id, - service_id, it->second->get_entry_time(), - it->second->get_author().c_str(), + it->second->get_comment_type(), it->second->get_entry_type(), + host_id, service_id, + it->second->get_entry_time(), it->second->get_author().c_str(), it->second->get_comment_data().c_str(), it->second->get_persistent(), it->second->get_source(), it->second->get_expires(), it->second->get_expire_time(), it->first, nullptr); @@ -161,8 +162,8 @@ void comment::delete_host_acknowledgement_comments(engine::host* hst) { broker_comment_data( NEBTYPE_COMMENT_DELETE, NEBFLAG_NONE, NEBATTR_NONE, it->second->get_comment_type(), it->second->get_entry_type(), - it->second->get_host_id(), 0, it->second->get_entry_time(), - it->second->get_author().c_str(), + it->second->get_host_id(), 0, + it->second->get_entry_time(), it->second->get_author().c_str(), it->second->get_comment_data().c_str(), it->second->get_persistent(), it->second->get_source(), it->second->get_expires(), it->second->get_expire_time(), it->first, nullptr); @@ -187,7 +188,8 @@ void comment::delete_service_acknowledgement_comments(::service* svc) { broker_comment_data( NEBTYPE_COMMENT_DELETE, NEBFLAG_NONE, NEBATTR_NONE, it->second->get_comment_type(), it->second->get_entry_type(), - it->second->get_host_id(), it->second->get_service_id(), + it->second->get_host_id(), + it->second->get_service_id(), it->second->get_entry_time(), it->second->get_author().c_str(), it->second->get_comment_data().c_str(), it->second->get_persistent(), it->second->get_source(), it->second->get_expires(), @@ -270,9 +272,10 @@ bool comment::operator==(comment const& obj) throw() { _comment_id == obj.get_comment_id() && _source == obj.get_source() && _persistent == obj.get_persistent() && _entry_time == obj.get_entry_time() && _expires == obj.get_expires() && - _expire_time == obj.get_expire_time() && _host_id == obj.get_host_id() && - _service_id == obj.get_service_id() && _author == obj.get_author() && - _comment_data == obj.get_comment_data()); + _expire_time == obj.get_expire_time() && + _host_id == obj.get_host_id() && + _service_id == obj.get_service_id() && + _author == obj.get_author() && _comment_data == obj.get_comment_data()); } /** diff --git a/centreon-engine/src/compatibility/CMakeLists.txt b/centreon-engine/src/compatibility/CMakeLists.txt index 91da531ec6c..ce8b0f7f4a6 100644 --- a/centreon-engine/src/compatibility/CMakeLists.txt +++ b/centreon-engine/src/compatibility/CMakeLists.txt @@ -76,7 +76,7 @@ set( ) # Install header files for development. -install(DIRECTORY "${INC_DIR}/" - DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}/centreon-engine" +install(DIRECTORY "${INC_DIR}" + DESTINATION "${PREFIX_INC}" COMPONENT "development" FILES_MATCHING PATTERN "*.h") diff --git a/centreon-engine/src/configuration/anomalydetection.cc b/centreon-engine/src/configuration/anomalydetection.cc index cfddc0896d5..e279df91aea 100644 --- a/centreon-engine/src/configuration/anomalydetection.cc +++ b/centreon-engine/src/configuration/anomalydetection.cc @@ -35,73 +35,70 @@ using namespace com::centreon::engine::logging; #define SETTER(type, method) \ &object::setter::generic -std::unordered_map const - anomalydetection::_setters{ - {"host_name", SETTER(std::string const&, _set_host_name)}, - {"service_description", - SETTER(std::string const&, _set_service_description)}, - {"host_id", SETTER(uint64_t, set_host_id)}, - {"_HOST_ID", SETTER(uint64_t, set_host_id)}, - {"service_id", SETTER(uint64_t, set_service_id)}, - {"_SERVICE_ID", SETTER(uint64_t, set_service_id)}, - {"dependent_service_id", SETTER(uint64_t, set_dependent_service_id)}, - {"acknowledgement_timeout", SETTER(int, set_acknowledgement_timeout)}, - {"description", SETTER(std::string const&, _set_service_description)}, - {"display_name", SETTER(std::string const&, _set_display_name)}, - {"service_groups", SETTER(std::string const&, _set_servicegroups)}, - {"servicegroups", SETTER(std::string const&, _set_servicegroups)}, - {"metric_name", SETTER(std::string const&, _set_metric_name)}, - {"thresholds_file", SETTER(std::string const&, _set_thresholds_file)}, - {"event_handler", SETTER(std::string const&, _set_event_handler)}, - {"notification_period", - SETTER(std::string const&, _set_notification_period)}, - {"contact_groups", SETTER(std::string const&, _set_contactgroups)}, - {"contacts", SETTER(std::string const&, _set_contacts)}, - {"failure_prediction_options", - SETTER(std::string const&, _set_failure_prediction_options)}, - {"notes", SETTER(std::string const&, _set_notes)}, - {"notes_url", SETTER(std::string const&, _set_notes_url)}, - {"action_url", SETTER(std::string const&, _set_action_url)}, - {"icon_image", SETTER(std::string const&, _set_icon_image)}, - {"icon_image_alt", SETTER(std::string const&, _set_icon_image_alt)}, - {"initial_state", SETTER(std::string const&, _set_initial_state)}, - {"max_check_attempts", SETTER(unsigned int, _set_max_check_attempts)}, - {"check_interval", SETTER(unsigned int, _set_check_interval)}, - {"normal_check_interval", SETTER(unsigned int, _set_check_interval)}, - {"retry_interval", SETTER(unsigned int, _set_retry_interval)}, - {"retry_check_interval", SETTER(unsigned int, _set_retry_interval)}, - {"recovery_notification_delay", - SETTER(unsigned int, _set_recovery_notification_delay)}, - {"status_change", SETTER(bool, _set_status_change)}, - {"active_checks_enabled", SETTER(bool, _set_checks_active)}, - {"passive_checks_enabled", SETTER(bool, _set_checks_passive)}, - {"parallelize_check", SETTER(bool, _set_parallelize_check)}, - {"is_volatile", SETTER(bool, _set_is_volatile)}, - {"obsess_over_service", SETTER(bool, _set_obsess_over_service)}, - {"event_handler_enabled", SETTER(bool, _set_event_handler_enabled)}, - {"check_freshness", SETTER(bool, _set_check_freshness)}, - {"freshness_threshold", SETTER(unsigned int, _set_freshness_threshold)}, - {"low_flap_threshold", SETTER(unsigned int, _set_low_flap_threshold)}, - {"high_flap_threshold", SETTER(unsigned int, _set_high_flap_threshold)}, - {"flap_detection_enabled", SETTER(bool, _set_flap_detection_enabled)}, - {"flap_detection_options", - SETTER(std::string const&, _set_flap_detection_options)}, - {"notification_options", - SETTER(std::string const&, _set_notification_options)}, - {"notifications_enabled", SETTER(bool, _set_notifications_enabled)}, - {"notification_interval", - SETTER(unsigned int, _set_notification_interval)}, - {"first_notification_delay", - SETTER(unsigned int, _set_first_notification_delay)}, - {"stalking_options", SETTER(std::string const&, _set_stalking_options)}, - {"process_perf_data", SETTER(bool, _set_process_perf_data)}, - {"failure_prediction_enabled", - SETTER(bool, _set_failure_prediction_enabled)}, - {"retain_status_information", - SETTER(bool, _set_retain_status_information)}, - {"retain_nonstatus_information", - SETTER(bool, _set_retain_nonstatus_information)}, - {"timezone", SETTER(std::string const&, _set_timezone)}}; +std::unordered_map const anomalydetection::_setters{ + {"host_name", SETTER(std::string const&, _set_host_name)}, + {"service_description", + SETTER(std::string const&, _set_service_description)}, + {"host_id", SETTER(uint64_t, set_host_id)}, + {"_HOST_ID", SETTER(uint64_t, set_host_id)}, + {"service_id", SETTER(uint64_t, set_service_id)}, + {"_SERVICE_ID", SETTER(uint64_t, set_service_id)}, + {"dependent_service_id", SETTER(uint64_t, set_dependent_service_id)}, + {"acknowledgement_timeout", SETTER(int, set_acknowledgement_timeout)}, + {"description", SETTER(std::string const&, _set_service_description)}, + {"display_name", SETTER(std::string const&, _set_display_name)}, + {"service_groups", SETTER(std::string const&, _set_servicegroups)}, + {"servicegroups", SETTER(std::string const&, _set_servicegroups)}, + {"metric_name", SETTER(std::string const&, _set_metric_name)}, + {"thresholds_file", SETTER(std::string const&, _set_thresholds_file)}, + {"event_handler", SETTER(std::string const&, _set_event_handler)}, + {"notification_period", + SETTER(std::string const&, _set_notification_period)}, + {"contact_groups", SETTER(std::string const&, _set_contactgroups)}, + {"contacts", SETTER(std::string const&, _set_contacts)}, + {"failure_prediction_options", + SETTER(std::string const&, _set_failure_prediction_options)}, + {"notes", SETTER(std::string const&, _set_notes)}, + {"notes_url", SETTER(std::string const&, _set_notes_url)}, + {"action_url", SETTER(std::string const&, _set_action_url)}, + {"icon_image", SETTER(std::string const&, _set_icon_image)}, + {"icon_image_alt", SETTER(std::string const&, _set_icon_image_alt)}, + {"initial_state", SETTER(std::string const&, _set_initial_state)}, + {"max_check_attempts", SETTER(unsigned int, _set_max_check_attempts)}, + {"check_interval", SETTER(unsigned int, _set_check_interval)}, + {"normal_check_interval", SETTER(unsigned int, _set_check_interval)}, + {"retry_interval", SETTER(unsigned int, _set_retry_interval)}, + {"retry_check_interval", SETTER(unsigned int, _set_retry_interval)}, + {"recovery_notification_delay", + SETTER(unsigned int, _set_recovery_notification_delay)}, + {"status_change", SETTER(bool, _set_status_change)}, + {"active_checks_enabled", SETTER(bool, _set_checks_active)}, + {"passive_checks_enabled", SETTER(bool, _set_checks_passive)}, + {"parallelize_check", SETTER(bool, _set_parallelize_check)}, + {"is_volatile", SETTER(bool, _set_is_volatile)}, + {"obsess_over_service", SETTER(bool, _set_obsess_over_service)}, + {"event_handler_enabled", SETTER(bool, _set_event_handler_enabled)}, + {"check_freshness", SETTER(bool, _set_check_freshness)}, + {"freshness_threshold", SETTER(unsigned int, _set_freshness_threshold)}, + {"low_flap_threshold", SETTER(unsigned int, _set_low_flap_threshold)}, + {"high_flap_threshold", SETTER(unsigned int, _set_high_flap_threshold)}, + {"flap_detection_enabled", SETTER(bool, _set_flap_detection_enabled)}, + {"flap_detection_options", + SETTER(std::string const&, _set_flap_detection_options)}, + {"notification_options", + SETTER(std::string const&, _set_notification_options)}, + {"notifications_enabled", SETTER(bool, _set_notifications_enabled)}, + {"notification_interval", SETTER(unsigned int, _set_notification_interval)}, + {"first_notification_delay", + SETTER(unsigned int, _set_first_notification_delay)}, + {"stalking_options", SETTER(std::string const&, _set_stalking_options)}, + {"process_perf_data", SETTER(bool, _set_process_perf_data)}, + {"failure_prediction_enabled", + SETTER(bool, _set_failure_prediction_enabled)}, + {"retain_status_information", SETTER(bool, _set_retain_status_information)}, + {"retain_nonstatus_information", + SETTER(bool, _set_retain_nonstatus_information)}, + {"timezone", SETTER(std::string const&, _set_timezone)}}; // Default values. static int default_acknowledgement_timeout(0); @@ -113,9 +110,10 @@ static unsigned int const default_check_interval(5); static bool const default_event_handler_enabled(true); static unsigned int const default_first_notification_delay(0); static bool const default_flap_detection_enabled(true); -static unsigned short const default_flap_detection_options( - anomalydetection::ok | anomalydetection::warning | - anomalydetection::unknown | anomalydetection::critical); +static unsigned short const default_flap_detection_options(anomalydetection::ok | + anomalydetection::warning | + anomalydetection::unknown | + anomalydetection::critical); static unsigned int const default_freshness_threshold(0); static unsigned int const default_high_flap_threshold(0); static unsigned int const default_initial_state(engine::service::state_ok); @@ -125,8 +123,7 @@ static unsigned int const default_max_check_attempts(3); static bool const default_notifications_enabled(true); static unsigned int const default_notification_interval(30); static unsigned short const default_notification_options( - anomalydetection::ok | anomalydetection::warning | - anomalydetection::critical | anomalydetection::unknown | + anomalydetection::ok | anomalydetection::warning | anomalydetection::critical | anomalydetection::unknown | anomalydetection::flapping | anomalydetection::downtime); static std::string const default_notification_period; static bool const default_obsess_over_service(true); @@ -297,8 +294,7 @@ anomalydetection& anomalydetection::operator=(anomalydetection const& other) { * * @return True if is the same anomalydetection, otherwise false. */ -bool anomalydetection::operator==( - anomalydetection const& other) const noexcept { +bool anomalydetection::operator==(anomalydetection const& other) const noexcept { if (!object::operator==(other)) { logger(dbg_config, more) << "configuration::anomalydetection::equality => object don't match"; @@ -310,48 +306,48 @@ bool anomalydetection::operator==( return false; } if (_action_url != other._action_url) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "action_url don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => action_url don't match"; return false; } if (_status_change != other._status_change) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "status_change don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => status_change don't match"; return false; } if (_checks_active != other._checks_active) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "checks_active don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => checks_active don't match"; return false; } if (_checks_passive != other._checks_passive) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "checks_passive don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => checks_passive don't match"; return false; } if (_metric_name != other._metric_name) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "metric_name don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => metric_name don't match"; return false; } if (_thresholds_file != other._thresholds_file) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "thresholds_file don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => thresholds_file don't match"; return false; } if (_check_freshness != other._check_freshness) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "check_freshness don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => check_freshness don't match"; return false; } if (_check_interval != other._check_interval) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "check_interval don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => check_interval don't match"; return false; } if (_contactgroups != other._contactgroups) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "contactgroups don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => contactgroups don't match"; return false; } if (_contacts != other._contacts) { @@ -360,23 +356,23 @@ bool anomalydetection::operator==( return false; } if (std::operator!=(_customvariables, other._customvariables)) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "customvariables don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => customvariables don't match"; return false; } if (_display_name != other._display_name) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "display_name don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => display_name don't match"; return false; } if (_event_handler != other._event_handler) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "event_handler don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => event_handler don't match"; return false; } if (_event_handler_enabled != other._event_handler_enabled) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "event_handler don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => event_handler don't match"; return false; } if (_first_notification_delay != other._first_notification_delay) { @@ -405,38 +401,38 @@ bool anomalydetection::operator==( return false; } if (_host_name != other._host_name) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "_host_name don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => _host_name don't match"; return false; } if (_icon_image != other._icon_image) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "icon_image don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => icon_image don't match"; return false; } if (_icon_image_alt != other._icon_image_alt) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "icon_image_alt don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => icon_image_alt don't match"; return false; } if (_initial_state != other._initial_state) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "initial_state don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => initial_state don't match"; return false; } if (_is_volatile != other._is_volatile) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "is_volatile don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => is_volatile don't match"; return false; } if (_low_flap_threshold != other._low_flap_threshold) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "low_flap_threshold don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => low_flap_threshold don't match"; return false; } if (_max_check_attempts != other._max_check_attempts) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "max_check_attempts don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => max_check_attempts don't match"; return false; } if (_notes != other._notes) { @@ -475,8 +471,8 @@ bool anomalydetection::operator==( return false; } if (_process_perf_data != other._process_perf_data) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "process_perf_data don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => process_perf_data don't match"; return false; } if (_retain_nonstatus_information != other._retain_nonstatus_information) { @@ -490,8 +486,8 @@ bool anomalydetection::operator==( return false; } if (_retry_interval != other._retry_interval) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "retry_interval don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => retry_interval don't match"; return false; } if (_recovery_notification_delay != other._recovery_notification_delay) { @@ -500,8 +496,8 @@ bool anomalydetection::operator==( return false; } if (_servicegroups != other._servicegroups) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "servicegroups don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => servicegroups don't match"; return false; } if (_service_description != other._service_description) { @@ -520,18 +516,18 @@ bool anomalydetection::operator==( return false; } if (_service_id != other._service_id) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "service_id don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => service_id don't match"; return false; } if (_dependent_service_id != other._dependent_service_id) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "dependent_service_id don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => dependent_service_id don't match"; return false; } if (_stalking_options != other._stalking_options) { - logger(dbg_config, more) << "configuration::anomalydetection::equality => " - "stalking_options don't match"; + logger(dbg_config, more) + << "configuration::anomalydetection::equality => stalking_options don't match"; return false; } if (_timezone != other._timezone) { @@ -550,8 +546,7 @@ bool anomalydetection::operator==( * * @return True if is not the same anomalydetection, otherwise false. */ -bool anomalydetection::operator!=( - anomalydetection const& other) const noexcept { +bool anomalydetection::operator!=(anomalydetection const& other) const noexcept { return !operator==(other); } @@ -711,8 +706,7 @@ void anomalydetection::merge(configuration::serviceextinfo const& tmpl) { */ void anomalydetection::merge(object const& obj) { if (obj.type() != _type) - throw engine_error() << "Cannot merge anomalydetection with '" << obj.type() - << "'"; + throw engine_error() << "Cannot merge anomalydetection with '" << obj.type() << "'"; anomalydetection const& tmpl(static_cast(obj)); MRG_OPTION(_acknowledgement_timeout); @@ -769,8 +763,8 @@ void anomalydetection::merge(object const& obj) { * @return True on success, otherwise false. */ bool anomalydetection::parse(char const* key, char const* value) { - std::unordered_map::const_iterator - it{_setters.find(key)}; + std::unordered_map::const_iterator it{ + _setters.find(key)}; if (it != _setters.end()) return (it->second)(*this, value); @@ -927,8 +921,7 @@ com::centreon::engine::map_customvar const& anomalydetection::customvariables() * * @return The customvariables. */ -com::centreon::engine::map_customvar& -anomalydetection::customvariables() noexcept { +com::centreon::engine::map_customvar& anomalydetection::customvariables() noexcept { return _customvariables; } @@ -1528,8 +1521,7 @@ bool anomalydetection::_set_failure_prediction_enabled(bool value) { * * @return True on success, otherwise false. */ -bool anomalydetection::_set_failure_prediction_options( - std::string const& value) { +bool anomalydetection::_set_failure_prediction_options(std::string const& value) { (void)value; logger(log_verification_error, basic) << "Warning: anomalydetection failure_prediction_options is deprecated." diff --git a/centreon-engine/src/configuration/applier/anomalydetection.cc b/centreon-engine/src/configuration/applier/anomalydetection.cc index 71be60aa660..b735a9a32f7 100644 --- a/centreon-engine/src/configuration/applier/anomalydetection.cc +++ b/centreon-engine/src/configuration/applier/anomalydetection.cc @@ -20,12 +20,12 @@ #include "com/centreon/engine/configuration/applier/anomalydetection.hh" #include #include -#include "com/centreon/engine/anomalydetection.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/config.hh" #include "com/centreon/engine/configuration/applier/scheduler.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/anomalydetection.hh" #include "com/centreon/engine/globals.hh" using namespace com::centreon; @@ -60,8 +60,7 @@ applier::anomalydetection::anomalydetection() {} * * @param[in] right Object to copy. */ -applier::anomalydetection::anomalydetection( - applier::anomalydetection const& right) { +applier::anomalydetection::anomalydetection(applier::anomalydetection const& right) { (void)right; } @@ -77,8 +76,7 @@ applier::anomalydetection::~anomalydetection() {} * * @return This object. */ -applier::anomalydetection& applier::anomalydetection::operator=( - applier::anomalydetection const& right) { +applier::anomalydetection& applier::anomalydetection::operator=(applier::anomalydetection const& right) { (void)right; return *this; } @@ -163,7 +161,7 @@ void applier::anomalydetection::add_object( obj.service_description()}] ->set_service_id(obj.service_id()); ad->set_acknowledgement_timeout(obj.get_acknowledgement_timeout() * - config->interval_length()); + config->interval_length()); ad->set_last_acknowledgement(0); // Add contacts. @@ -208,12 +206,14 @@ void applier::anomalydetection::expand_objects(configuration::state& s) { for (configuration::set_anomalydetection::iterator it_ad = s.anomalydetections().begin(), end_ad = s.anomalydetections().end(); - it_ad != end_ad; ++it_ad) { + it_ad != end_ad; + ++it_ad) { // Should custom variables be sent to broker ? for (map_customvar::iterator it = const_cast(it_ad->customvariables()).begin(), end = const_cast(it_ad->customvariables()).end(); - it != end; ++it) { + it != end; + ++it) { if (!s.enable_macros_filter() || s.macros_filter().find(it->first) != s.macros_filter().end()) { it->second.set_sent(true); @@ -228,15 +228,14 @@ void applier::anomalydetection::expand_objects(configuration::state& s) { * @param[in] obj The new anomalydetection to modify into the monitoring * engine. */ -void applier::anomalydetection::modify_object( - configuration::anomalydetection const& obj) { +void applier::anomalydetection::modify_object(configuration::anomalydetection const& obj) { std::string const& host_name(obj.host_name()); std::string const& service_description(obj.service_description()); // Logging. logger(logging::dbg_config, logging::more) - << "Modifying new anomalydetection '" << service_description - << "' of host '" << host_name << "'."; + << "Modifying new anomalydetection '" << service_description << "' of host '" + << host_name << "'."; // Find the configuration object. set_anomalydetection::iterator it_cfg( @@ -277,8 +276,8 @@ void applier::anomalydetection::modify_object( s->set_thresholds_file(obj.thresholds_file()); s->set_event_handler(obj.event_handler()); s->set_event_handler_enabled(obj.event_handler_enabled()); - s->set_initial_state(static_cast( - obj.initial_state())); + s->set_initial_state( + static_cast(obj.initial_state())); s->set_check_interval(obj.check_interval()); s->set_retry_interval(obj.retry_interval()); s->set_max_attempts(obj.max_check_attempts()); @@ -312,16 +311,13 @@ void applier::anomalydetection::modify_object( s->add_stalk_on(obj.stalking_options() & configuration::anomalydetection::ok ? notifier::ok : notifier::none); - s->add_stalk_on(obj.stalking_options() & - configuration::anomalydetection::warning + s->add_stalk_on(obj.stalking_options() & configuration::anomalydetection::warning ? notifier::warning : notifier::none); - s->add_stalk_on(obj.stalking_options() & - configuration::anomalydetection::unknown + s->add_stalk_on(obj.stalking_options() & configuration::anomalydetection::unknown ? notifier::unknown : notifier::none); - s->add_stalk_on(obj.stalking_options() & - configuration::anomalydetection::critical + s->add_stalk_on(obj.stalking_options() & configuration::anomalydetection::critical ? notifier::critical : notifier::none); @@ -434,8 +430,7 @@ void applier::anomalydetection::modify_object( * @param[in] obj The new anomalydetection to remove from the monitoring * engine. */ -void applier::anomalydetection::remove_object( - configuration::anomalydetection const& obj) { +void applier::anomalydetection::remove_object(configuration::anomalydetection const& obj) { std::string const& host_name(obj.host_name()); std::string const& service_description(obj.service_description()); @@ -460,11 +455,10 @@ void applier::anomalydetection::remove_object( host_name, service_description, {false, (time_t)0}, ""); // Remove events related to this anomalydetection. - applier::scheduler::instance().remove_service(obj.host_id(), - obj.service_id()); + applier::scheduler::instance().remove_service(obj.host_id(), obj.service_id()); - // remove anomalydetection from servicegroup->members - for (auto& it_s : it->second->get_parent_groups()) + //remove anomalydetection from servicegroup->members + for (auto& it_s: it->second->get_parent_groups()) it_s->members.erase({host_name, service_description}); // Notify event broker. @@ -487,16 +481,14 @@ void applier::anomalydetection::remove_object( * * @param[in] obj Service object. */ -void applier::anomalydetection::resolve_object( - configuration::anomalydetection const& obj) { +void applier::anomalydetection::resolve_object(configuration::anomalydetection const& obj) { // Logging. logger(logging::dbg_config, logging::more) - << "Resolving anomalydetection '" << obj.service_description() - << "' of host '" << obj.host_name() << "'."; + << "Resolving anomalydetection '" << obj.service_description() << "' of host '" + << obj.host_name() << "'."; // Find anomalydetection. - service_id_map::iterator it( - engine::anomalydetection::services_by_id.find(obj.key())); + service_id_map::iterator it(engine::anomalydetection::services_by_id.find(obj.key())); if (engine::anomalydetection::services_by_id.end() == it) throw engine_error() << "Cannot resolve non-existing anomalydetection '" << obj.service_description() << "' of host '" @@ -524,9 +516,8 @@ void applier::anomalydetection::resolve_object( * @param[in] obj Target anomalydetection. * @param[out] s Configuration state. */ -void applier::anomalydetection::_expand_service_memberships( - configuration::anomalydetection& obj, - configuration::state& s) { +void applier::anomalydetection::_expand_service_memberships(configuration::anomalydetection& obj, + configuration::state& s) { // Browse anomalydetection groups. for (set_string::const_iterator it(obj.servicegroups().begin()), end(obj.servicegroups().end()); @@ -538,8 +529,8 @@ void applier::anomalydetection::_expand_service_memberships( throw(engine_error() << "Could not add anomalydetection '" << obj.service_description() << "' of host '" << obj.host_name() - << "' to non-existing anomalydetection group '" - << *it << "'"); + << "' to non-existing anomalydetection group '" << *it + << "'"); // Remove anomalydetection group from state. configuration::servicegroup backup(*it_group); diff --git a/centreon-engine/src/configuration/applier/contact.cc b/centreon-engine/src/configuration/applier/contact.cc index 34420dbeb80..355d4b27e60 100644 --- a/centreon-engine/src/configuration/applier/contact.cc +++ b/centreon-engine/src/configuration/applier/contact.cc @@ -360,7 +360,7 @@ void applier::contact::remove_object(configuration::contact const& obj) { if (it != engine::contact::contacts.end()) { engine::contact* cntct(it->second.get()); - for (auto& it_c : it->second->get_parent_groups()) + for (auto& it_c: it->second->get_parent_groups()) it_c.second->get_members().erase(obj.contact_name()); // Notify event broker. diff --git a/centreon-engine/src/configuration/applier/hostescalation.cc b/centreon-engine/src/configuration/applier/hostescalation.cc index f253cf51ada..a67e2c8547d 100644 --- a/centreon-engine/src/configuration/applier/hostescalation.cc +++ b/centreon-engine/src/configuration/applier/hostescalation.cc @@ -162,9 +162,10 @@ void applier::hostescalation::remove_object( /* ... and its escalations */ if (hit == engine::host::hosts.end()) { logger(logging::dbg_config, logging::more) - << "Cannot find host '" << host_name << "' - already removed."; + << "Cannot find host '" << host_name << "' - already removed."; host_exists = false; - } else + } + else host_exists = true; for (hostescalation_mmap::iterator it{range.first}, end{range.second}; @@ -195,8 +196,7 @@ void applier::hostescalation::remove_object( if (host_exists) { logger(logging::dbg_config, logging::more) - << "Host '" << host_name - << "' found - removing escalation from it."; + << "Host '" << host_name << "' found - removing escalation from it."; std::list& escalations(hit->second->get_escalations()); /* We need also to remove the escalation from the host */ for (std::list::iterator heit{escalations.begin()}, diff --git a/centreon-engine/src/configuration/applier/scheduler.cc b/centreon-engine/src/configuration/applier/scheduler.cc index 8ace54e2799..cf437be4517 100644 --- a/centreon-engine/src/configuration/applier/scheduler.cc +++ b/centreon-engine/src/configuration/applier/scheduler.cc @@ -25,6 +25,7 @@ #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/deleter/listmember.hh" #include "com/centreon/engine/events/loop.hh" +#include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/statusdata.hh" @@ -100,8 +101,7 @@ void applier::scheduler::apply( {it->host_id(), it->service_id()})); if (svc != services.end()) { bool has_event(events::loop::instance().find_event( - events::loop::low, timed_event::EVENT_SERVICE_CHECK, - svc->second.get())); + events::loop::low, timed_event::EVENT_SERVICE_CHECK, svc->second.get())); bool should_schedule(it->checks_active() && (it->check_interval() > 0)); if (has_event && should_schedule) { svc_to_unschedule.insert(*it); @@ -114,8 +114,7 @@ void applier::scheduler::apply( } } - for (set_anomalydetection::iterator - it(diff_anomalydetections.modified().begin()), + for (set_anomalydetection::iterator it(diff_anomalydetections.modified().begin()), end(diff_anomalydetections.modified().end()); it != end; ++it) { service_id_map const& services(engine::service::services_by_id); @@ -123,8 +122,7 @@ void applier::scheduler::apply( {it->host_id(), it->service_id()})); if (svc != services.end()) { bool has_event(events::loop::instance().find_event( - events::loop::low, timed_event::EVENT_SERVICE_CHECK, - svc->second.get())); + events::loop::low, timed_event::EVENT_SERVICE_CHECK, svc->second.get())); bool should_schedule(it->checks_active() && (it->check_interval() > 0)); if (has_event && should_schedule) { ad_to_unschedule.insert(*it); @@ -158,8 +156,7 @@ void applier::scheduler::apply( _unschedule_service_events(old_anomalydetections); } // Check if we need to add or modify objects into the scheduler. - if (!hst_to_schedule.empty() || !svc_to_schedule.empty() || - !ad_to_schedule.empty()) { + if (!hst_to_schedule.empty() || !svc_to_schedule.empty() || !ad_to_schedule.empty()) { // Reset scheduling info. // Keep data that has been set manually by the user // (service interleave and intercheck delays). @@ -197,8 +194,7 @@ void applier::scheduler::apply( _get_services(svc_to_schedule, true); std::vector new_anomalydetections = _get_anomalydetections(ad_to_schedule, true); - new_services.insert( - new_services.end(), + new_services.insert(new_services.end(), std::make_move_iterator(new_anomalydetections.begin()), std::make_move_iterator(new_anomalydetections.end())); _schedule_service_events(new_services); @@ -329,8 +325,8 @@ void applier::scheduler::_apply_misc_event() { unsigned long interval(5); if (_config->command_check_interval() != -1) interval = (unsigned long)_config->command_check_interval(); - _evt_command_check = _create_misc_event(timed_event::EVENT_COMMAND_CHECK, - now + interval, interval); + _evt_command_check = + _create_misc_event(timed_event::EVENT_COMMAND_CHECK, now + interval, interval); } _old_command_check_interval = _config->command_check_interval(); } @@ -369,10 +365,9 @@ void applier::scheduler::_apply_misc_event() { _config->auto_rescheduling_interval())) { _remove_misc_event(_evt_reschedule_checks); if (_config->auto_reschedule_checks()) - _evt_reschedule_checks = - _create_misc_event(timed_event::EVENT_RESCHEDULE_CHECKS, - now + _config->auto_rescheduling_interval(), - _config->auto_rescheduling_interval()); + _evt_reschedule_checks = _create_misc_event( + timed_event::EVENT_RESCHEDULE_CHECKS, now + _config->auto_rescheduling_interval(), + _config->auto_rescheduling_interval()); _old_auto_rescheduling_interval = _config->auto_rescheduling_interval(); } @@ -385,8 +380,8 @@ void applier::scheduler::_apply_misc_event() { if (_config->retain_state_information() && _config->retention_update_interval() > 0) { unsigned long interval(_config->retention_update_interval() * 60); - _evt_retention_save = _create_misc_event( - timed_event::EVENT_RETENTION_SAVE, now + interval, interval); + _evt_retention_save = + _create_misc_event(timed_event::EVENT_RETENTION_SAVE, now + interval, interval); } _old_retention_update_interval = _config->retention_update_interval(); } @@ -579,6 +574,7 @@ void applier::scheduler::_calculate_host_scheduling_params() { scheduling_info.host_check_interval_total * _config->interval_length(); _calculate_host_inter_check_delay(_config->host_inter_check_delay_method()); + } /** @@ -780,7 +776,7 @@ std::vector applier::scheduler::_get_hosts( if (hst == hosts.end()) { if (throw_if_not_found) throw engine_error() - << "Could not schedule non-existing host '" << host_name << "'"; + << "Could not schedule non-existing host '" << host_name << "'"; } else retval.push_back(&*hst->second); } @@ -809,8 +805,8 @@ std::vector applier::scheduler::_get_services( if (svc == services.end()) { if (throw_if_not_found) throw engine_error() - << "Cannot schedule non-existing service '" << service_description - << "' on host '" << host_name << "'"; + << "Cannot schedule non-existing service '" << service_description + << "' on host '" << host_name << "'"; } else retval.push_back(svc->second.get()); } @@ -948,9 +944,9 @@ void applier::scheduler::_schedule_host_events( com::centreon::engine::host& hst(*it->second); // Schedule a new host check event. - timed_event* evt = new timed_event( - timed_event::EVENT_HOST_CHECK, hst.get_next_check(), false, 0, nullptr, - true, (void*)&hst, NULL, hst.get_check_options()); + timed_event* evt = new timed_event(timed_event::EVENT_HOST_CHECK, hst.get_next_check(), + false, 0, nullptr, true, (void*)&hst, + NULL, hst.get_check_options()); events::loop::instance().schedule(evt, false); } @@ -1054,9 +1050,9 @@ void applier::scheduler::_schedule_service_events( it != end; ++it) { engine::service& svc(*it->second); // Create a new service check event. - timed_event* evt(new timed_event( - timed_event::EVENT_SERVICE_CHECK, svc.get_next_check(), false, 0, - nullptr, true, (void*)&svc, nullptr, svc.get_check_options())); + timed_event* evt(new timed_event(timed_event::EVENT_SERVICE_CHECK, svc.get_next_check(), + false, 0, nullptr, true, (void*)&svc, + nullptr, svc.get_check_options())); events::loop::instance().schedule(evt, false); } @@ -1066,6 +1062,7 @@ void applier::scheduler::_schedule_service_events( for (int i(0), end(services.size()); i < end; ++i) if (services[i]->get_problem_has_been_acknowledged()) services[i]->schedule_acknowledgement_expiration(); + } /** @@ -1076,8 +1073,8 @@ void applier::scheduler::_schedule_service_events( void applier::scheduler::_unschedule_host_events( std::vector const& hosts) { for (auto& h : hosts) { - events::loop::instance().remove_events(events::loop::low, - timed_event::EVENT_HOST_CHECK, h); + events::loop::instance().remove_events( + events::loop::low, timed_event::EVENT_HOST_CHECK, h); events::loop::instance().remove_events( events::loop::low, timed_event::EVENT_EXPIRE_HOST_ACK, h); } @@ -1091,8 +1088,8 @@ void applier::scheduler::_unschedule_host_events( void applier::scheduler::_unschedule_service_events( std::vector const& services) { for (auto& s : services) { - events::loop::instance().remove_events(events::loop::low, - timed_event::EVENT_SERVICE_CHECK, s); + events::loop::instance().remove_events( + events::loop::low, timed_event::EVENT_SERVICE_CHECK, s); events::loop::instance().remove_events( events::loop::low, timed_event::EVENT_EXPIRE_SERVICE_ACK, s); } diff --git a/centreon-engine/src/configuration/applier/serviceescalation.cc b/centreon-engine/src/configuration/applier/serviceescalation.cc index ca99f075572..93f563d200a 100644 --- a/centreon-engine/src/configuration/applier/serviceescalation.cc +++ b/centreon-engine/src/configuration/applier/serviceescalation.cc @@ -185,10 +185,11 @@ void applier::serviceescalation::remove_object( /* ... and its escalations */ if (sit == engine::service::services.end()) { logger(logging::dbg_config, logging::more) - << "Cannot find service '" << host_name << "/" << description - << "' - already removed."; + << "Cannot find service '" << host_name << "/" << description + << "' - already removed."; service_exists = false; - } else + } + else service_exists = true; for (serviceescalation_mmap::iterator it{range.first}, end{range.second}; @@ -204,8 +205,8 @@ void applier::serviceescalation::remove_object( if (service_exists) { logger(logging::dbg_config, logging::more) - << "Service '" << host_name << "/" << description - << "' found - removing escalation from it."; + << "Service '" << host_name << "/" << description + << "' found - removing escalation from it."; std::list& srv_escalations(sit->second->get_escalations()); /* We need also to remove the escalation from the service */ for (std::list::iterator diff --git a/centreon-engine/src/configuration/object.cc b/centreon-engine/src/configuration/object.cc index e4fc440f586..6d8e9962d11 100644 --- a/centreon-engine/src/configuration/object.cc +++ b/centreon-engine/src/configuration/object.cc @@ -18,7 +18,6 @@ */ #include "com/centreon/engine/configuration/object.hh" -#include "com/centreon/engine/configuration/anomalydetection.hh" #include "com/centreon/engine/configuration/command.hh" #include "com/centreon/engine/configuration/connector.hh" #include "com/centreon/engine/configuration/contact.hh" @@ -28,6 +27,7 @@ #include "com/centreon/engine/configuration/hostescalation.hh" #include "com/centreon/engine/configuration/hostextinfo.hh" #include "com/centreon/engine/configuration/hostgroup.hh" +#include "com/centreon/engine/configuration/anomalydetection.hh" #include "com/centreon/engine/configuration/service.hh" #include "com/centreon/engine/configuration/servicedependency.hh" #include "com/centreon/engine/configuration/serviceescalation.hh" @@ -249,22 +249,13 @@ object::object_type object::type() const noexcept { * @return The object type name. */ std::string const& object::type_name() const noexcept { - static std::string const tab[] = {"command", - "connector", - "contact", - "contactgroup", - "host", - "hostdependency", - "hostescalation", - "hostextinfo", - "hostgroup", - "service", - "servicedependency", - "serviceescalation", - "serviceextinfo", - "servicegroup", - "timeperiod", - "anomalydetection"}; + static std::string const tab[] = { + "command", "connector", "contact", + "contactgroup", "host", "hostdependency", + "hostescalation", "hostextinfo", "hostgroup", + "service", "servicedependency", "serviceescalation", + "serviceextinfo", "servicegroup", "timeperiod", + "anomalydetection"}; return tab[_type]; } diff --git a/centreon-engine/src/configuration/service.cc b/centreon-engine/src/configuration/service.cc index 0e45d7ade68..c2ce2958573 100644 --- a/centreon-engine/src/configuration/service.cc +++ b/centreon-engine/src/configuration/service.cc @@ -658,9 +658,9 @@ void service::check_validity() const { << "'service_description')"); if (_hosts->empty() && _hostgroups->empty()) throw engine_error() - << "Service '" << _service_description - << "' is not attached to any host or host group (properties " - << "'host_name' or 'hostgroup_name', respectively)"; + << "Service '" << _service_description + << "' is not attached to any host or host group (properties " + << "'host_name' or 'hostgroup_name', respectively)"; if (_check_command.empty()) throw engine_error() << "Service '" << _service_description << "' has no check command (property 'check_command')"; diff --git a/centreon-engine/src/configuration/state.cc b/centreon-engine/src/configuration/state.cc index 3224cc717dc..185e5c0206e 100644 --- a/centreon-engine/src/configuration/state.cc +++ b/centreon-engine/src/configuration/state.cc @@ -2113,8 +2113,8 @@ void state::host_perfdata_file_mode(perfdata_file_mode value) { * * @return The host_perfdata_file_processing_command value. */ -std::string const& state::host_perfdata_file_processing_command() - const noexcept { +std::string const& state::host_perfdata_file_processing_command() const + noexcept { return _host_perfdata_file_processing_command; } @@ -3143,8 +3143,8 @@ void state::service_freshness_check_interval(unsigned int value) { * * @return The service_inter_check_delay_method value. */ -state::inter_check_delay state::service_inter_check_delay_method() - const noexcept { +state::inter_check_delay state::service_inter_check_delay_method() const + noexcept { return _service_inter_check_delay_method; } @@ -3162,8 +3162,8 @@ void state::service_inter_check_delay_method(inter_check_delay value) { * * @return The service_interleave_factor_method value. */ -state::interleave_factor state::service_interleave_factor_method() - const noexcept { +state::interleave_factor state::service_interleave_factor_method() const + noexcept { return _service_interleave_factor_method; } @@ -3235,8 +3235,8 @@ void state::service_perfdata_file_mode(perfdata_file_mode value) { * * @return The service_perfdata_file_processing_command value. */ -std::string const& state::service_perfdata_file_processing_command() - const noexcept { +std::string const& state::service_perfdata_file_processing_command() const + noexcept { return _service_perfdata_file_processing_command; } @@ -3508,8 +3508,8 @@ void state::translate_passive_host_checks(bool value) { * * @return The users resources list. */ -std::unordered_map const& state::user() - const noexcept { +std::unordered_map const& state::user() const + noexcept { return _users; } @@ -3547,6 +3547,7 @@ void state::user(unsigned int key, std::string const& value) { _users[string::from(key)] = value; } + /** * Set use_aggressive_host_checking value. This function is still there just * to warn the user. It should be removed soon. diff --git a/centreon-engine/src/contactgroup.cc b/centreon-engine/src/contactgroup.cc index 2492db81568..c01d63ea6ca 100644 --- a/centreon-engine/src/contactgroup.cc +++ b/centreon-engine/src/contactgroup.cc @@ -80,37 +80,24 @@ contactgroup& contactgroup::operator=(contactgroup const& other) { /** * Destructor. */ -contactgroup::~contactgroup() { - _members.clear(); -} +contactgroup::~contactgroup() { _members.clear(); } -std::string const& contactgroup::get_name() const { - return _name; -} +std::string const& contactgroup::get_name() const { return _name; } -void contactgroup::clear_members() { - _members.clear(); -} +void contactgroup::clear_members() { _members.clear(); } -contact_map_unsafe& contactgroup::get_members() { - return _members; -} +contact_map_unsafe& contactgroup::get_members() { return _members; } -contact_map_unsafe const& contactgroup::get_members() const { - return _members; -} +contact_map_unsafe const& contactgroup::get_members() const { return _members; } -std::string const& contactgroup::get_alias() const { - return _alias; -} +std::string const& contactgroup::get_alias() const { return _alias; } -void contactgroup::set_alias(std::string const& alias) { - _alias = alias; -} +void contactgroup::set_alias(std::string const& alias) { _alias = alias; } std::ostream& operator<<(std::ostream& os, contactgroup_map_unsafe const& obj) { for (contactgroup_map_unsafe::const_iterator it{obj.begin()}, end{obj.end()}; - it != end; ++it) { + it != end; + ++it) { os << it->first; if (next(it) != end) os << ", "; @@ -124,7 +111,8 @@ void contactgroup::resolve(int& w __attribute__((unused)), int& e) { int errors{0}; for (contact_map_unsafe::iterator it{_members.begin()}, end{_members.end()}; - it != end; ++it) { + it != end; + ++it) { /* Check members */ if (!it->second) { logger(log_verification_error, basic) diff --git a/centreon-engine/src/customvariable.cc b/centreon-engine/src/customvariable.cc index 20fe7fbc982..df83cd44ed5 100644 --- a/centreon-engine/src/customvariable.cc +++ b/centreon-engine/src/customvariable.cc @@ -37,7 +37,9 @@ customvariable::customvariable(std::string const& value, bool is_sent) * @param other Another customvariable */ customvariable::customvariable(customvariable const& other) - : _value{other._value}, _is_sent{other._is_sent}, _modified{false} {} + : _value{other._value}, + _is_sent{other._is_sent}, + _modified{false} {} /** * Affectation operator of customvariable diff --git a/centreon-engine/src/dependency.cc b/centreon-engine/src/dependency.cc index a66ce772c11..c4520138fe8 100644 --- a/centreon-engine/src/dependency.cc +++ b/centreon-engine/src/dependency.cc @@ -64,9 +64,7 @@ void dependency::set_dependent_hostname(std::string const& dependent_hostname) { _dependent_hostname = dependent_hostname; } -std::string const& dependency::get_hostname() const { - return _hostname; -} +std::string const& dependency::get_hostname() const { return _hostname; } void dependency::set_hostname(std::string const& hostname) { _hostname = hostname; @@ -80,17 +78,13 @@ void dependency::set_dependency_period(std::string const& dependency_period) { _dependency_period = dependency_period; } -bool dependency::get_inherits_parent() const { - return _inherits_parent; -} +bool dependency::get_inherits_parent() const { return _inherits_parent; } void dependency::set_inherits_parent(bool inherits_parent) { _inherits_parent = inherits_parent; } -bool dependency::get_fail_on_pending() const { - return _fail_on_pending; -} +bool dependency::get_fail_on_pending() const { return _fail_on_pending; } void dependency::set_fail_on_pending(bool fail_on_pending) { _fail_on_pending = fail_on_pending; diff --git a/centreon-engine/src/downtimes/downtime.cc b/centreon-engine/src/downtimes/downtime.cc index aab6b398205..dd5f54da455 100644 --- a/centreon-engine/src/downtimes/downtime.cc +++ b/centreon-engine/src/downtimes/downtime.cc @@ -64,8 +64,8 @@ downtime::downtime(downtime::type type, _start_flex_downtime{0}, _incremented_pending_downtime{false} { /* don't add triggered downtimes that don't have a valid parent */ - if (triggered_by > 0 && !downtime_manager::instance().find_downtime( - downtime::any_downtime, triggered_by)) + if (triggered_by > 0 && + !downtime_manager::instance().find_downtime(downtime::any_downtime, triggered_by)) throw engine_error() << "can not add triggered host downtime without a valid parent"; @@ -80,8 +80,7 @@ downtime::~downtime() {} /* handles scheduled downtime (id passed from timed event queue) */ int handle_scheduled_downtime_by_id(uint64_t downtime_id) { std::shared_ptr temp_downtime{ - downtime_manager::instance().find_downtime(downtime::any_downtime, - downtime_id)}; + downtime_manager::instance().find_downtime(downtime::any_downtime, downtime_id)}; /* find the downtime entry */ if (!temp_downtime) return ERROR; diff --git a/centreon-engine/src/downtimes/host_downtime.cc b/centreon-engine/src/downtimes/host_downtime.cc index dceb881d59f..c7c760b856d 100644 --- a/centreon-engine/src/downtimes/host_downtime.cc +++ b/centreon-engine/src/downtimes/host_downtime.cc @@ -58,11 +58,10 @@ host_downtime::~host_downtime() { comment::delete_comment(_get_comment_id()); /* send data to event broker */ broker_downtime_data(NEBTYPE_DOWNTIME_DELETE, NEBFLAG_NONE, NEBATTR_NONE, - downtime::host_downtime, _hostname.c_str(), nullptr, - _entry_time, _author.c_str(), _comment.c_str(), - get_start_time(), get_end_time(), is_fixed(), - get_triggered_by(), get_duration(), get_downtime_id(), - nullptr); + downtime::host_downtime, _hostname.c_str(), nullptr, _entry_time, + _author.c_str(), _comment.c_str(), get_start_time(), + get_end_time(), is_fixed(), get_triggered_by(), + get_duration(), get_downtime_id(), nullptr); } /* adds a host downtime entry to the list in memory */ @@ -267,8 +266,8 @@ int host_downtime::subscribe() { if (get_triggered_by() == 0) { uint64_t* new_downtime_id{new uint64_t{get_downtime_id()}}; timed_event* evt = - new timed_event(timed_event::EVENT_SCHEDULED_DOWNTIME, get_start_time(), - false, 0, NULL, false, (void*)new_downtime_id, NULL, 0); + new timed_event(timed_event::EVENT_SCHEDULED_DOWNTIME, get_start_time(), false, 0, + NULL, false, (void*)new_downtime_id, NULL, 0); events::loop::instance().schedule(evt, true); } @@ -318,9 +317,16 @@ int host_downtime::handle() { temp = get_end_time() + 1; /*** Sometimes, get_end_time() == longlong::max(), if we add 1 to it, * it becomes < 0 ***/ - timed_event* evt = - new timed_event(timed_event::EVENT_EXPIRE_DOWNTIME, temp, false, 0, - NULL, false, NULL, NULL, 0); + timed_event* evt = new timed_event( + timed_event::EVENT_EXPIRE_DOWNTIME, + temp, + false, + 0, + NULL, + false, + NULL, + NULL, + 0); events::loop::instance().schedule(evt, true); return OK; } @@ -437,8 +443,7 @@ int host_downtime::handle() { if (!is_fixed()) event_time = (time_t)((uint64_t)time(NULL) + get_duration()); else { - /* Sometimes, get_end_time() == longlong::max(), if we add 1 to it, it - * becomes < 0 */ + /* Sometimes, get_end_time() == longlong::max(), if we add 1 to it, it becomes < 0 */ if (get_end_time() == INT64_MAX) event_time = get_end_time(); else @@ -447,8 +452,8 @@ int host_downtime::handle() { uint64_t* new_downtime_id{new uint64_t{get_downtime_id()}}; timed_event* evt = - new timed_event(timed_event::EVENT_SCHEDULED_DOWNTIME, event_time, - false, 0, NULL, false, (void*)new_downtime_id, NULL, 0); + new timed_event(timed_event::EVENT_SCHEDULED_DOWNTIME, event_time, false, 0, NULL, + false, (void*)new_downtime_id, NULL, 0); events::loop::instance().schedule(evt, true); /* handle (start) downtime that is triggered by this one */ @@ -469,8 +474,8 @@ void host_downtime::schedule() { /* send data to event broker */ broker_downtime_data(NEBTYPE_DOWNTIME_LOAD, NEBFLAG_NONE, NEBATTR_NONE, - downtime::host_downtime, _hostname.c_str(), nullptr, - _entry_time, _author.c_str(), _comment.c_str(), - _start_time, _end_time, _fixed, _triggered_by, _duration, + downtime::host_downtime, _hostname.c_str(), nullptr, _entry_time, + _author.c_str(), _comment.c_str(), _start_time, + _end_time, _fixed, _triggered_by, _duration, _downtime_id, nullptr); } diff --git a/centreon-engine/src/downtimes/service_downtime.cc b/centreon-engine/src/downtimes/service_downtime.cc index 96ad4d0d44b..1970338ff5a 100644 --- a/centreon-engine/src/downtimes/service_downtime.cc +++ b/centreon-engine/src/downtimes/service_downtime.cc @@ -18,9 +18,9 @@ */ #include "com/centreon/engine/downtimes/service_downtime.hh" -#include -#include #include +#include +#include #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/comment.hh" #include "com/centreon/engine/configuration/applier/state.hh" @@ -46,17 +46,9 @@ service_downtime::service_downtime(std::string const& host_name, uint64_t triggered_by, int32_t duration, uint64_t downtime_id) - : downtime{downtime::service_downtime, - host_name, - entry_time, - author, - comment_data, - start_time, - end_time, - fixed, - triggered_by, - duration, - downtime_id}, + : downtime{downtime::service_downtime, host_name, entry_time, author, + comment_data, start_time, end_time, fixed, + triggered_by, duration, downtime_id}, _service_description{service_desc} {} /* finds a specific service downtime entry */ @@ -70,11 +62,11 @@ service_downtime::~service_downtime() { comment::delete_comment(_get_comment_id()); /* send data to event broker */ broker_downtime_data( - NEBTYPE_DOWNTIME_DELETE, NEBFLAG_NONE, NEBATTR_NONE, - downtime::service_downtime, get_hostname().c_str(), - get_service_description().c_str(), _entry_time, get_author().c_str(), - get_comment().c_str(), get_start_time(), get_end_time(), is_fixed(), - get_triggered_by(), get_duration(), get_downtime_id(), nullptr); + NEBTYPE_DOWNTIME_DELETE, NEBFLAG_NONE, NEBATTR_NONE, downtime::service_downtime, + get_hostname().c_str(), get_service_description().c_str(), _entry_time, + get_author().c_str(), get_comment().c_str(), get_start_time(), + get_end_time(), is_fixed(), get_triggered_by(), get_duration(), + get_downtime_id(), nullptr); } /** @@ -244,20 +236,19 @@ int service_downtime::subscribe() { int seconds{get_duration() - hours * 3600 - minutes * 60}; char const* type_string{"service"}; - std::string msg; + std::ostringstream oss; if (is_fixed()) - msg = fmt::format( - "This {0} has been scheduled for fixed downtime from {1} to {2}. " - "Notifications for the {0} will not be sent out during that time " - "period.", - type_string, start_time_string, end_time_string); + oss << "This " << type_string + << " has been scheduled for fixed downtime from " << start_time_string + << " to " << end_time_string << " Notifications for the " << type_string + << " will not be sent out during that time period."; else - msg = fmt::format( - "This {0} has been scheduled for flexible downtime starting between " - "{1} and {2} and lasting for a period of {3} hours and {4} minutes. " - "Notifications for the {0} will not be sent out during that time " - "period.", - type_string, start_time_string, end_time_string, hours, minutes); + oss << "This " << type_string + << " has been scheduled for flexible downtime starting between " + << start_time_string << " and " << end_time_string + << " and lasting for a period of " << hours << " hours and " << minutes + << " minutes. Notifications for the " << type_string + << " will not be sent out during that time period."; logger(dbg_downtime, basic) << "Scheduled Downtime Details:"; logger(dbg_downtime, basic) << " Type: Service Downtime\n" @@ -284,10 +275,10 @@ int service_downtime::subscribe() { /* add a non-persistent comment to the host or service regarding the scheduled * outage */ - auto com{std::make_shared( + std::shared_ptr com{new comment( comment::service, comment::downtime, found->second->get_host_id(), found->second->get_service_id(), time(nullptr), - "(Centreon Engine Process)", msg, false, comment::internal, false, + "(Centreon Engine Process)", oss.str(), false, comment::internal, false, (time_t)0)}; comment::comments.insert({com->get_comment_id(), com}); @@ -299,9 +290,15 @@ int service_downtime::subscribe() { /* only non-triggered downtime is scheduled... */ if (get_triggered_by() == 0) { uint64_t* new_downtime_id{new uint64_t{get_downtime_id()}}; - timed_event* evt = new timed_event( - timed_event::EVENT_SCHEDULED_DOWNTIME, get_start_time(), false, 0, - nullptr, false, (void*)new_downtime_id, nullptr, 0); + timed_event* evt = new timed_event(timed_event::EVENT_SCHEDULED_DOWNTIME, + get_start_time(), + false, + 0, + nullptr, + false, + (void*)new_downtime_id, + nullptr, + 0); events::loop::instance().schedule(evt, true); } @@ -351,10 +348,17 @@ int service_downtime::handle() { else temp = get_end_time() + 1; /*** Sometimes, get_end_time() == longlong::max(), if we add 1 to it, - * it becomes < 0 ***/ - timed_event* evt = - new timed_event(timed_event::EVENT_EXPIRE_DOWNTIME, temp, false, 0, - nullptr, false, nullptr, nullptr, 0); + * it becomes < 0 ***/ + timed_event* evt = new timed_event( + timed_event::EVENT_EXPIRE_DOWNTIME, + temp, + false, + 0, + nullptr, + false, + nullptr, + nullptr, + 0); events::loop::instance().schedule(evt, true); return OK; } @@ -477,8 +481,7 @@ int service_downtime::handle() { if (!is_fixed()) event_time = (time_t)((unsigned long)time(nullptr) + get_duration()); else { - /* Sometimes, get_end_time() == longlong::max(), if we add 1 to it, it - * becomes < 0 */ + /* Sometimes, get_end_time() == longlong::max(), if we add 1 to it, it becomes < 0 */ if (get_end_time() == INT64_MAX) event_time = get_end_time(); else @@ -487,8 +490,14 @@ int service_downtime::handle() { uint64_t* new_downtime_id{new uint64_t{get_downtime_id()}}; timed_event* evt = new timed_event(timed_event::EVENT_SCHEDULED_DOWNTIME, - event_time, false, 0, nullptr, false, - (void*)new_downtime_id, nullptr, 0); + event_time, + false, + 0, + nullptr, + false, + (void*)new_downtime_id, + nullptr, + 0); events::loop::instance().schedule(evt, true); /* handle (start) downtime that is triggered by this one */ @@ -513,10 +522,9 @@ void service_downtime::schedule() { downtime_manager::instance().add_downtime(this); /* send data to event broker */ - broker_downtime_data(NEBTYPE_DOWNTIME_LOAD, NEBFLAG_NONE, NEBATTR_NONE, - downtime::service_downtime, _hostname.c_str(), - _service_description.c_str(), _entry_time, - _author.c_str(), _comment.c_str(), _start_time, - _end_time, _fixed, _triggered_by, _duration, - _downtime_id, nullptr); + broker_downtime_data( + NEBTYPE_DOWNTIME_LOAD, NEBFLAG_NONE, NEBATTR_NONE, downtime::service_downtime, + _hostname.c_str(), _service_description.c_str(), _entry_time, + _author.c_str(), _comment.c_str(), _start_time, _end_time, _fixed, + _triggered_by, _duration, _downtime_id, nullptr); } diff --git a/centreon-engine/src/events/loop.cc b/centreon-engine/src/events/loop.cc index 570741c89cf..c374cd80c8f 100644 --- a/centreon-engine/src/events/loop.cc +++ b/centreon-engine/src/events/loop.cc @@ -399,8 +399,8 @@ void loop::_dispatching() { } auto t1 = std::chrono::system_clock::now(); - auto delay = std::chrono::nanoseconds( - static_cast(1000000000 * config->sleep_time())); + auto delay = std::chrono::nanoseconds(static_cast( + 1000000000 * config->sleep_time())); command_manager::instance().execute(); // Set time to sleep so we don't hog the CPU... diff --git a/centreon-engine/src/events/sched_info.cc b/centreon-engine/src/events/sched_info.cc index 3dbc0035659..5ee3330a924 100644 --- a/centreon-engine/src/events/sched_info.cc +++ b/centreon-engine/src/events/sched_info.cc @@ -30,6 +30,7 @@ using namespace com::centreon::engine; using namespace com::centreon::engine::logging; + /** * Displays service check scheduling information. */ diff --git a/centreon-engine/src/exceptions/error.cc b/centreon-engine/src/exceptions/error.cc index 45880b8433c..5f6a4c2e438 100644 --- a/centreon-engine/src/exceptions/error.cc +++ b/centreon-engine/src/exceptions/error.cc @@ -50,8 +50,7 @@ error::error(char const* file, char const* function, int line) noexcept * * @param[in] e Object to copy. */ -error::error(error const& e) noexcept - : std::exception(e), _current(e._current) { +error::error(error const& e) noexcept : std::exception(e), _current(e._current) { memcpy(_buffer, e._buffer, _current * sizeof(*_buffer)); } diff --git a/centreon-engine/src/main.cc b/centreon-engine/src/main.cc index 5a4880362dc..db99e519112 100644 --- a/centreon-engine/src/main.cc +++ b/centreon-engine/src/main.cc @@ -40,7 +40,6 @@ #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/diagnostic.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" -#include "com/centreon/engine/enginerpc.hh" #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging.hh" @@ -57,6 +56,7 @@ #include "com/centreon/engine/version.hh" #include "com/centreon/io/directory_entry.hh" #include "com/centreon/logging/engine.hh" +#include "com/centreon/engine/enginerpc.hh" using namespace com::centreon::engine; diff --git a/centreon-engine/src/retention/applier/comment.cc b/centreon-engine/src/retention/applier/comment.cc index 10d827605b1..bc1dd0b0455 100644 --- a/centreon-engine/src/retention/applier/comment.cc +++ b/centreon-engine/src/retention/applier/comment.cc @@ -83,8 +83,8 @@ void applier::comment::_add_host_comment( */ void applier::comment::_add_service_comment( retention::comment const& obj) noexcept { - service_map::const_iterator it_svc( - service::services.find({obj.host_name(), obj.service_description()})); + service_map::const_iterator it_svc(service::services.find( + {obj.host_name(), obj.service_description()})); if (it_svc == service::services.end() || !it_svc->second) return; diff --git a/centreon-engine/src/service.cc b/centreon-engine/src/service.cc index 3c1131443a2..9a6583e9da1 100644 --- a/centreon-engine/src/service.cc +++ b/centreon-engine/src/service.cc @@ -3092,10 +3092,8 @@ bool service::is_result_fresh(time_t current_time, int log_this) { return true; } -/** - * @brief Handles the details for a service when flap detection is disabled - * (globally or per-service). - */ +/* handles the details for a service when flap detection is disabled (globally + * or per-service) */ void service::handle_flap_detection_disabled() { logger(dbg_functions, basic) << "handle_service_flap_detection_disabled()"; @@ -3104,14 +3102,15 @@ void service::handle_flap_detection_disabled() { set_is_flapping(false); /* delete the original comment we added earlier */ - if (get_flapping_comment_id() != 0) - comment::delete_comment(get_flapping_comment_id()); - set_flapping_comment_id(0); + if (this->get_flapping_comment_id() != 0) + comment::delete_comment(this->get_flapping_comment_id()); + this->set_flapping_comment_id(0); /* log a notice - this one is parsed by the history CGI */ logger(log_info_message, basic) - << "SERVICE FLAPPING ALERT: " << get_hostname() << ";" - << get_description() << ";DISABLED; Flap detection has been disabled"; + << "SERVICE FLAPPING ALERT: " << this->get_hostname() << ";" + << this->get_description() + << ";DISABLED; Flap detection has been disabled"; /* send data to event broker */ broker_flapping_data(NEBTYPE_FLAPPING_STOP, NEBFLAG_NONE, @@ -3119,7 +3118,7 @@ void service::handle_flap_detection_disabled() { get_percent_state_change(), 0.0, 0.0, nullptr); /* send a notification */ - notify(reason_flappingdisabled, "", "", notification_option_none); + this->notify(reason_flappingdisabled, "", "", notification_option_none); /* should we send a recovery notification? */ notify(reason_recovery, "", "", notification_option_none); diff --git a/centreon-engine/src/simumod/CMakeLists.txt b/centreon-engine/src/simumod/CMakeLists.txt index b0413f5d5e7..9a16d620e18 100644 --- a/centreon-engine/src/simumod/CMakeLists.txt +++ b/centreon-engine/src/simumod/CMakeLists.txt @@ -43,6 +43,6 @@ get_property(SIMUMOD_MODULE TARGET "${SIMUMOD}" PROPERTY LOCATION) set(SIMUMOD_MODULE "${SIMUMOD_MODULE}" PARENT_SCOPE) -add_dependencies("${SIMUMOD}" centreon_clib) +add_dependencies("${SIMUMOD}" centreon_clib_shared) target_link_libraries("${SIMUMOD}" centreon_clib) diff --git a/centreon-engine/src/statistics.cc b/centreon-engine/src/statistics.cc index 385b14eec2a..689b69e70b6 100644 --- a/centreon-engine/src/statistics.cc +++ b/centreon-engine/src/statistics.cc @@ -17,8 +17,8 @@ * */ -#include "com/centreon/engine/statistics.hh" #include "com/centreon/engine/globals.hh" +#include "com/centreon/engine/statistics.hh" using namespace com::centreon::engine; @@ -41,7 +41,7 @@ statistics& statistics::instance() { * @brief Returns the centengine pid. * * @return A pid_t - */ + */ pid_t statistics::get_pid() const noexcept { return getpid(); } @@ -54,8 +54,8 @@ pid_t statistics::get_pid() const noexcept { * * @return A boolean telling if the struct has been filled. */ -bool statistics::get_external_command_buffer_stats( - buffer_stats& retval) const noexcept { +bool statistics::get_external_command_buffer_stats(buffer_stats& retval) const + noexcept { if (config->check_external_commands()) { pthread_mutex_lock(&external_command_buffer.buffer_lock); retval.used = external_command_buffer.items; diff --git a/centreon-engine/src/xsddefault.cc b/centreon-engine/src/xsddefault.cc index 87d21f39a4b..874cf066ed3 100644 --- a/centreon-engine/src/xsddefault.cc +++ b/centreon-engine/src/xsddefault.cc @@ -109,7 +109,7 @@ int xsddefault_save_status_data() { // get number of items in the command buffer if (config->check_external_commands()) { - // FIXME DBR + //FIXME DBR pthread_mutex_lock(&external_command_buffer.buffer_lock); used_external_command_buffer_slots = external_command_buffer.items; high_external_command_buffer_slots = external_command_buffer.high; @@ -690,7 +690,8 @@ int xsddefault_save_status_data() { stream << "\thost_id=" << it->second->get_host_id() << "\n"; if (it->second->get_comment_type() == com::centreon::engine::comment::service) - stream << "\tservice_id=" << it->second->get_service_id() << "\n"; + stream << "\tservice_id=" + << it->second->get_service_id() << "\n"; stream << "\tentry_type=" << it->second->get_entry_type() << "\n" "\tcomment_id=" diff --git a/centreon-engine/test/commands/CMakeLists.txt b/centreon-engine/test/commands/CMakeLists.txt index 461c0f81118..0ec4f277833 100644 --- a/centreon-engine/test/commands/CMakeLists.txt +++ b/centreon-engine/test/commands/CMakeLists.txt @@ -23,11 +23,11 @@ link_directories(${CMAKE_SOURCE_DIR}/build/centreon-clib/) # Test binary. add_executable("bin_connector_test_run" "${TEST_DIR}/bin_connector_test_run.cc") -add_dependencies("bin_connector_test_run" centreon_clib) +add_dependencies("bin_connector_test_run" centreon_clib_shared) target_link_libraries("bin_connector_test_run" centreon_clib) add_executable("bin_test_run" "${TEST_DIR}/bin_test_run.cc") -add_dependencies("bin_test_run" centreon_clib) +add_dependencies("bin_test_run" centreon_clib_shared) target_link_libraries("bin_test_run" centreon_clib) # Test connector. diff --git a/centreon-engine/test/configuration/applier/check_scheduler.cc b/centreon-engine/test/configuration/applier/check_scheduler.cc index 81fcb714b1f..77681c48642 100644 --- a/centreon-engine/test/configuration/applier/check_scheduler.cc +++ b/centreon-engine/test/configuration/applier/check_scheduler.cc @@ -25,9 +25,9 @@ #include "com/centreon/engine/configuration/state.hh" #include "com/centreon/engine/deleter/listmember.hh" #include "com/centreon/engine/deleter/timedevent.hh" +#include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/events/sched_info.hh" #include "com/centreon/engine/events/timed_event.hh" -#include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/macros.hh" #include "test/unittest.hh" diff --git a/centreon-engine/test/events/handle_timed_event.cc b/centreon-engine/test/events/handle_timed_event.cc index d73f25516ef..f3a0ee19efc 100644 --- a/centreon-engine/test/events/handle_timed_event.cc +++ b/centreon-engine/test/events/handle_timed_event.cc @@ -19,8 +19,8 @@ #include #include "com/centreon/engine/broker.hh" -#include "com/centreon/engine/events/defines.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/events/defines.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/nebstructs.hh" #include "test/unittest.hh" diff --git a/centreon-engine/tests/CMakeLists.txt b/centreon-engine/tests/CMakeLists.txt index d37c38fab9b..f36d38a36f9 100755 --- a/centreon-engine/tests/CMakeLists.txt +++ b/centreon-engine/tests/CMakeLists.txt @@ -19,7 +19,10 @@ ## # Enable unit tests or not . +option(WITH_TESTING "Build unit tests." OFF) if (WITH_TESTING) + + find_package(GTest REQUIRED) include_directories(${GTest_INCLUDE_DIRS}) link_directories(${GTest_LIB_DIRS}) diff --git a/centreon-engine/tests/commands/connector.cc b/centreon-engine/tests/commands/connector.cc index 834224bddaf..a8007774bbb 100644 --- a/centreon-engine/tests/commands/connector.cc +++ b/centreon-engine/tests/commands/connector.cc @@ -44,7 +44,7 @@ class my_listener : public commands::command_listener { } void clear() { - _res.command_id = 0u; + _res.command_id = 0; _res.output = ""; } @@ -98,7 +98,7 @@ TEST_F(Connector, RunWithTimeout) { result res; cmd_connector.run("commande --timeout=on", macros, 1, res); - ASSERT_TRUE(res.command_id != 0u); + ASSERT_TRUE(res.command_id != 0); } TEST_F(Connector, RunConnectorAsync) { @@ -116,7 +116,7 @@ TEST_F(Connector, RunConnectorAsync) { ++timeout; } result res{lstnr->get_result()}; - ASSERT_NE(res.command_id, 0u); + ASSERT_NE(res.command_id, 0); ASSERT_EQ(res.output, "commande"); } @@ -157,7 +157,7 @@ TEST_F(Connector, RunConnectorSetCommandLine) { ++timeout; } result res{lstnr.get_result()}; - ASSERT_NE(res.command_id, 0u); + ASSERT_NE(res.command_id, 0); ASSERT_EQ(res.output, "commande1"); lstnr.clear(); @@ -172,6 +172,6 @@ TEST_F(Connector, RunConnectorSetCommandLine) { ++timeout; } res = lstnr.get_result(); - ASSERT_NE(res.command_id, 0u); + ASSERT_NE(res.command_id, 0); ASSERT_EQ(res.output, "commande2"); } diff --git a/centreon-engine/tests/configuration/applier/applier-anomalydetection.cc b/centreon-engine/tests/configuration/applier/applier-anomalydetection.cc index 2f74eb29559..2e4ad30d657 100644 --- a/centreon-engine/tests/configuration/applier/applier-anomalydetection.cc +++ b/centreon-engine/tests/configuration/applier/applier-anomalydetection.cc @@ -21,15 +21,15 @@ #include #include "../../test_engine.hh" #include "../../timeperiod/utils.hh" -#include "com/centreon/engine/anomalydetection.hh" -#include "com/centreon/engine/configuration/applier/anomalydetection.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/contactgroup.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/applier/service.hh" #include "com/centreon/engine/configuration/host.hh" +#include "com/centreon/engine/configuration/applier/anomalydetection.hh" #include "com/centreon/engine/exceptions/error.hh" +#include "com/centreon/engine/anomalydetection.hh" #include "helper.hh" using namespace com::centreon; @@ -39,16 +39,19 @@ using namespace com::centreon::engine::configuration::applier; class ApplierAnomalydetection : public TestEngine { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; // Given an AD configuration with a host not defined // Then the applier add_object throws an exception because it needs a service // command. -TEST_F(ApplierAnomalydetection, - NewAnomalydetectionWithHostNotDefinedFromConfig) { +TEST_F(ApplierAnomalydetection, NewAnomalydetectionWithHostNotDefinedFromConfig) { configuration::applier::anomalydetection ad_aply; configuration::anomalydetection ad; ASSERT_TRUE(ad.parse("host_name", "test_host")); @@ -105,8 +108,7 @@ TEST_F(ApplierAnomalydetection, NewADFromConfig) { ASSERT_TRUE(ad.parse("host_id", "12")); ASSERT_TRUE(ad.parse("host_name", "test_host")); ASSERT_TRUE(ad.parse("metric_name", "foo")); - ASSERT_TRUE( - ad.parse("thresholds_file", "/etc/centreon-broker/thresholds.json")); + ASSERT_TRUE(ad.parse("thresholds_file", "/etc/centreon-broker/thresholds.json")); // No need here to call ad_aply.expand_objects(*config) because the // configuration service is not stored in configuration::state. We just have diff --git a/centreon-engine/tests/configuration/applier/applier-connector.cc b/centreon-engine/tests/configuration/applier/applier-connector.cc index f30af876615..4e3b7e2f1ef 100644 --- a/centreon-engine/tests/configuration/applier/applier-connector.cc +++ b/centreon-engine/tests/configuration/applier/applier-connector.cc @@ -30,9 +30,13 @@ using namespace com::centreon::engine::configuration::applier; class ApplierConnector : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; // Given a connector applier diff --git a/centreon-engine/tests/configuration/applier/applier-contact.cc b/centreon-engine/tests/configuration/applier/applier-contact.cc index d64f0cfd1d3..12412b2ffb3 100644 --- a/centreon-engine/tests/configuration/applier/applier-contact.cc +++ b/centreon-engine/tests/configuration/applier/applier-contact.cc @@ -44,7 +44,9 @@ class ApplierContact : public ::testing::Test { init_config_state(); } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } configuration::contact valid_contact_config() const { // Add command. diff --git a/centreon-engine/tests/configuration/applier/applier-contactgroup.cc b/centreon-engine/tests/configuration/applier/applier-contactgroup.cc index 324875b8a73..f578456c177 100644 --- a/centreon-engine/tests/configuration/applier/applier-contactgroup.cc +++ b/centreon-engine/tests/configuration/applier/applier-contactgroup.cc @@ -41,7 +41,9 @@ class ApplierContactgroup : public ::testing::Test { init_config_state(); } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; // Given a contactgroup applier @@ -195,18 +197,15 @@ TEST_F(ApplierContactgroup, ContactRemove) { configuration::contact ctct2("test2"); aply.add_object(ctct2); + grp.parse("members", "test, test2"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); aply_grp.resolve_object(grp); - ASSERT_EQ( - engine::contactgroup::contactgroups["test_group"]->get_members().size(), - 2u); + ASSERT_EQ(engine::contactgroup::contactgroups["test_group"]->get_members().size(), 2u); aply.remove_object(ctct2); - ASSERT_EQ( - engine::contactgroup::contactgroups["test_group"]->get_members().size(), - 1u); + ASSERT_EQ(engine::contactgroup::contactgroups["test_group"]->get_members().size(), 1u); grp.parse("members", "test"); aply_grp.modify_object(grp); } diff --git a/centreon-engine/tests/configuration/applier/applier-host.cc b/centreon-engine/tests/configuration/applier/applier-host.cc index 4780d201335..4d0d75f1863 100644 --- a/centreon-engine/tests/configuration/applier/applier-host.cc +++ b/centreon-engine/tests/configuration/applier/applier-host.cc @@ -36,9 +36,13 @@ using namespace com::centreon::engine::configuration::applier; class ApplierHost : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; // Given host configuration without host_id diff --git a/centreon-engine/tests/configuration/applier/applier-hostescalation.cc b/centreon-engine/tests/configuration/applier/applier-hostescalation.cc index 69b820426c8..01ac328b5e4 100644 --- a/centreon-engine/tests/configuration/applier/applier-hostescalation.cc +++ b/centreon-engine/tests/configuration/applier/applier-hostescalation.cc @@ -17,12 +17,12 @@ * */ -#include #include #include #include #include #include +#include #include using namespace com::centreon; @@ -30,9 +30,13 @@ using namespace com::centreon::engine; class ApplierHostEscalation : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; TEST_F(ApplierHostEscalation, AddEscalation) { @@ -55,6 +59,7 @@ TEST_F(ApplierHostEscalation, AddEscalation) { ASSERT_EQ(hostescalation::hostescalations.size(), 2u); } + TEST_F(ApplierHostEscalation, RemoveEscalation) { configuration::applier::host hst_aply; configuration::host hst; diff --git a/centreon-engine/tests/configuration/applier/applier-hostgroup.cc b/centreon-engine/tests/configuration/applier/applier-hostgroup.cc index 4ee563d50f9..e66c45cf1b2 100644 --- a/centreon-engine/tests/configuration/applier/applier-hostgroup.cc +++ b/centreon-engine/tests/configuration/applier/applier-hostgroup.cc @@ -33,9 +33,13 @@ using namespace com::centreon::engine::configuration::applier; class ApplierHostGroup : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; // Given host configuration without host_id @@ -159,11 +163,12 @@ TEST_F(ApplierHostGroup, HostRemoved) { ASSERT_NO_THROW(hst_aply.resolve_object(hst_c)); ASSERT_NO_THROW(hg_aply.resolve_object(hg)); - engine::hostgroup* hg_obj{engine::hostgroup::hostgroups["temphg"].get()}; + engine::hostgroup *hg_obj{engine::hostgroup::hostgroups["temphg"].get()}; ASSERT_EQ(hg_obj->members.size(), 2u); ASSERT_NO_THROW(hst_aply.remove_object(hst_a)); ASSERT_EQ(hg_obj->members.size(), 1u); ASSERT_TRUE(hg.parse("members", "c")); ASSERT_NO_THROW(hg_aply.modify_object(hg)); + } diff --git a/centreon-engine/tests/configuration/applier/applier-service.cc b/centreon-engine/tests/configuration/applier/applier-service.cc index b026674c96e..91094b1f64f 100644 --- a/centreon-engine/tests/configuration/applier/applier-service.cc +++ b/centreon-engine/tests/configuration/applier/applier-service.cc @@ -39,9 +39,13 @@ using namespace com::centreon::engine::configuration::applier; class ApplierService : public TestEngine { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; // Given service configuration with an host not defined diff --git a/centreon-engine/tests/configuration/applier/applier-serviceescalation.cc b/centreon-engine/tests/configuration/applier/applier-serviceescalation.cc index 57eb814df70..b13bd9e2b0d 100644 --- a/centreon-engine/tests/configuration/applier/applier-serviceescalation.cc +++ b/centreon-engine/tests/configuration/applier/applier-serviceescalation.cc @@ -32,9 +32,13 @@ using namespace com::centreon::engine; class ApplierServiceEscalation : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; TEST_F(ApplierServiceEscalation, AddEscalation) { @@ -100,7 +104,7 @@ TEST_F(ApplierServiceEscalation, RemoveEscalation) { ASSERT_EQ(service::services.size(), 1u); configuration::applier::serviceescalation se_apply; - configuration::serviceescalation se1, se2; + configuration::serviceescalation se1,se2; ASSERT_TRUE(se1.parse("host_name", "test_host")); ASSERT_TRUE(se1.parse("service_description", "test_svc")); ASSERT_TRUE(se1.parse("first_notification", "4")); diff --git a/centreon-engine/tests/configuration/applier/applier-servicegroup.cc b/centreon-engine/tests/configuration/applier/applier-servicegroup.cc index 3399a230903..5eecfff51fd 100644 --- a/centreon-engine/tests/configuration/applier/applier-servicegroup.cc +++ b/centreon-engine/tests/configuration/applier/applier-servicegroup.cc @@ -43,7 +43,9 @@ class ApplierServicegroup : public ::testing::Test { init_config_state(); } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; // Given a servicegroup applier @@ -287,14 +289,14 @@ TEST_F(ApplierServicegroup, RemoveServiceFromGroup) { aply_svc.add_object(svc); ASSERT_TRUE(svc.parse("servicegroups", "test_group")); + grp.parse("members", "test_host,test,test_host,test2"); aply_grp.add_object(grp); aply_grp.expand_objects(*config); aply_grp.resolve_object(grp); ASSERT_TRUE(grp.members().size() == 2); - engine::servicegroup* sg{ - engine::servicegroup::servicegroups["test_group"].get()}; + engine::servicegroup *sg{engine::servicegroup::servicegroups["test_group"].get()}; ASSERT_EQ(sg->members.size(), 2u); aply_svc.remove_object(svc); ASSERT_EQ(sg->members.size(), 1u); diff --git a/centreon-engine/tests/configuration/contact.cc b/centreon-engine/tests/configuration/contact.cc index 7781f6957bf..4b67a0a6619 100644 --- a/centreon-engine/tests/configuration/contact.cc +++ b/centreon-engine/tests/configuration/contact.cc @@ -30,9 +30,13 @@ extern configuration::state* config; class ConfigContact : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; // When I create a configuration::contact with an empty name diff --git a/centreon-engine/tests/contacts/contactgroup-config.cc b/centreon-engine/tests/contacts/contactgroup-config.cc index 65b9b5ff5fd..e6f9a2c46d7 100644 --- a/centreon-engine/tests/contacts/contactgroup-config.cc +++ b/centreon-engine/tests/contacts/contactgroup-config.cc @@ -26,7 +26,12 @@ using namespace com::centreon::engine::configuration; class ContactgroupConfig : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; + diff --git a/centreon-engine/tests/contacts/simple-contactgroup.cc b/centreon-engine/tests/contacts/simple-contactgroup.cc index faa93351c27..1b97b777225 100644 --- a/centreon-engine/tests/contacts/simple-contactgroup.cc +++ b/centreon-engine/tests/contacts/simple-contactgroup.cc @@ -26,7 +26,11 @@ using namespace com::centreon::engine::configuration; class SimpleContactgroup : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; diff --git a/centreon-engine/tests/downtimes/downtime.cc b/centreon-engine/tests/downtimes/downtime.cc index 99908025b75..1323152d48d 100644 --- a/centreon-engine/tests/downtimes/downtime.cc +++ b/centreon-engine/tests/downtimes/downtime.cc @@ -31,7 +31,9 @@ using namespace com::centreon::engine::downtimes; class DowntimeExternalCommand : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } void TearDown() override { downtime_manager::instance().clear_scheduled_downtimes(); diff --git a/centreon-engine/tests/enginerpc/enginerpc.cc b/centreon-engine/tests/enginerpc/enginerpc.cc index 2d0fb9e1e26..204d1671a85 100644 --- a/centreon-engine/tests/enginerpc/enginerpc.cc +++ b/centreon-engine/tests/enginerpc/enginerpc.cc @@ -219,6 +219,7 @@ static void call_command_manager(std::unique_ptr& th, th.reset(new std::thread(fn)); } + TEST_F(EngineRpc, StartStop) { enginerpc erpc("0.0.0.0", 40001); ASSERT_NO_THROW(erpc.shutdown()); @@ -365,7 +366,8 @@ TEST_F(EngineRpc, GetWrongService) { "Host name: ", "Serv desc: ", "Service state: 0", - "Service period: "}; + "Service period: " + }; _svc->set_current_state(engine::service::state_critical); call_command_manager(th, &condvar, &mutex, &continuerunning); @@ -418,8 +420,8 @@ TEST_F(EngineRpc, GetWrongContact) { std::condition_variable condvar; std::mutex mutex; bool continuerunning = false; - std::vector vectests = {"GetContact rpc engine failed", - "GetContact", "", "", ""}; + std::vector vectests = {"GetContact rpc engine failed", "GetContact", "", "", + ""}; call_command_manager(th, &condvar, &mutex, &continuerunning); @@ -438,6 +440,7 @@ TEST_F(EngineRpc, GetWrongContact) { erpc.shutdown(); } + TEST_F(EngineRpc, GetHostsCount) { enginerpc erpc("0.0.0.0", 40001); std::unique_ptr th; @@ -1007,7 +1010,7 @@ TEST_F(EngineRpc, ScheduleWrongHostDowntime) { call_command_manager(th, &condvar, &mutex, &continuerunning); - // we fake a wrong test with an + // we fake a wrong test with an auto output = execute(oss.str()); ASSERT_EQ("ScheduleHostDowntime 0", output.back()); { @@ -1021,6 +1024,7 @@ TEST_F(EngineRpc, ScheduleWrongHostDowntime) { erpc.shutdown(); } + TEST_F(EngineRpc, ScheduleServiceDowntime) { enginerpc erpc("0.0.0.0", 40001); std::unique_ptr th; @@ -1099,6 +1103,8 @@ TEST_F(EngineRpc, ScheduleWrongServiceDowntime) { erpc.shutdown(); } + + TEST_F(EngineRpc, ScheduleHostServicesDowntime) { enginerpc erpc("0.0.0.0", 40001); std::unique_ptr th; @@ -1736,6 +1742,7 @@ TEST_F(EngineRpc, ChangeContactObjectCustomVar) { erpc.shutdown(); } + TEST_F(EngineRpc, ProcessServiceCheckResult) { enginerpc erpc("0.0.0.0", 40001); auto output = execute("ProcessServiceCheckResult test_host test_svc 0"); diff --git a/centreon-engine/tests/external_commands/host.cc b/centreon-engine/tests/external_commands/host.cc index d40ce021a16..921bc815ac7 100644 --- a/centreon-engine/tests/external_commands/host.cc +++ b/centreon-engine/tests/external_commands/host.cc @@ -30,9 +30,13 @@ using namespace com::centreon::engine; class HostExternalCommand : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } - void TearDown() override { deinit_config_state(); } + void TearDown() override { + deinit_config_state(); + } }; TEST_F(HostExternalCommand, AddHostDowntime) { diff --git a/centreon-engine/tests/external_commands/service.cc b/centreon-engine/tests/external_commands/service.cc index 14138d885e7..9b66370d841 100644 --- a/centreon-engine/tests/external_commands/service.cc +++ b/centreon-engine/tests/external_commands/service.cc @@ -20,12 +20,12 @@ #include "com/centreon/engine/configuration/applier/service.hh" #include #include "../timeperiod/utils.hh" +#include "com/centreon/process_manager.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/configuration/applier/command.hh" #include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/events/loop.hh" #include "com/centreon/engine/modules/external_commands/commands.hh" -#include "com/centreon/process_manager.hh" #include "helper.hh" using namespace com::centreon; @@ -33,7 +33,9 @@ using namespace com::centreon::engine; class ServiceExternalCommand : public ::testing::Test { public: - void SetUp() override { init_config_state(); } + void SetUp() override { + init_config_state(); + } void TearDown() override { deinit_config_state(); diff --git a/centreon-engine/tests/macros/macro_hostname.cc b/centreon-engine/tests/macros/macro_hostname.cc index 182c812d819..20fef9cd42b 100644 --- a/centreon-engine/tests/macros/macro_hostname.cc +++ b/centreon-engine/tests/macros/macro_hostname.cc @@ -17,33 +17,33 @@ * */ -#include #include #include -#include #include +#include +#include #include "com/centreon/engine/globals.hh" +#include "../helper.hh" +#include "../test_engine.hh" +#include "../timeperiod/utils.hh" +#include "com/centreon/engine/checks/checker.hh" #include -#include #include #include #include -#include +#include #include #include +#include +#include "com/centreon/engine/configuration/applier/contactgroup.hh" +#include "com/centreon/engine/configuration/applier/serviceescalation.hh" +#include "com/centreon/engine/modules/external_commands/commands.hh" #include #include -#include #include #include -#include "../helper.hh" -#include "../test_engine.hh" -#include "../timeperiod/utils.hh" -#include "com/centreon/engine/checks/checker.hh" -#include "com/centreon/engine/configuration/applier/contactgroup.hh" -#include "com/centreon/engine/configuration/applier/serviceescalation.hh" -#include "com/centreon/engine/modules/external_commands/commands.hh" +#include #include "com/centreon/engine/timeperiod.hh" using namespace com::centreon; @@ -53,7 +53,7 @@ class MacroHostname : public TestEngine { public: void SetUp() override { init_config_state(); - _tp = _creator.new_timeperiod(); + _tp = _creator.new_timeperiod(); for (int i(0); i < 7; ++i) _creator.new_timerange(0, 0, 24, 0, i); _now = strtotimet("2016-11-24 08:00:00"); @@ -67,9 +67,9 @@ class MacroHostname : public TestEngine { _svc.reset(); deinit_config_state(); } - - protected: - std::shared_ptr _host, _host2, _host3; + + protected: + std::shared_ptr _host, _host2,_host3; std::shared_ptr _svc; timeperiod_creator _creator; time_t _now; @@ -82,11 +82,11 @@ TEST_F(MacroHostname, HostProblemId) { next_problem_id = 1; set_time(50000); - // first host + //first host ASSERT_TRUE(hst.parse("host_name", "test_host")); ASSERT_TRUE(hst.parse("address", "127.0.0.1")); ASSERT_TRUE(hst.parse("_HOST_ID", "12")); - // second host + //second host ASSERT_TRUE(hst2.parse("host_name", "test_host2")); ASSERT_TRUE(hst2.parse("address", "127.0.0.1")); ASSERT_TRUE(hst2.parse("_HOST_ID", "13")); @@ -100,17 +100,18 @@ TEST_F(MacroHostname, HostProblemId) { _host->set_last_hard_state(engine::host::state_up); _host->set_last_hard_state_change(50000); _host->set_state_type(checkable::hard); - + _host2 = host::hosts.find("test_host2")->second; _host2->set_current_state(engine::host::state_up); _host2->set_last_hard_state(engine::host::state_up); _host2->set_last_hard_state_change(50000); _host2->set_state_type(checkable::hard); - auto fn = [](std::shared_ptr hst, std::string firstcheck, - std::string secondcheck) -> void { + auto fn = [] (std::shared_ptr hst, + std::string firstcheck, + std::string secondcheck) -> void { std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); for (int i = 0; i < 3; i++) { // When i == 0, the state_down is soft => no notification @@ -123,15 +124,13 @@ TEST_F(MacroHostname, HostProblemId) { hst->process_check_result_3x(engine::host::state_down, "The host is down", CHECK_OPTION_NONE, 0, true, 0); } - - process_macros_r(mac, fmt::format("$HOSTPROBLEMID:{}$", hst->get_name()), - out, 0); - ASSERT_EQ(out, firstcheck); - + + process_macros_r(mac,fmt::format("$HOSTPROBLEMID:{}$", hst->get_name()), out, 0); + ASSERT_EQ(out, firstcheck); + for (int i = 0; i < 2; i++) { - // When i == 0, the state_up is hard (return to up) => Recovery - // notification When i == 1, the state_up is still here (no change) => no - // notification + // When i == 0, the state_up is hard (return to up) => Recovery notification + // When i == 1, the state_up is still here (no change) => no notification set_time(52500 + i * 500); hst->set_last_state(hst->get_current_state()); if (notifier::hard == hst->get_state_type()) @@ -139,14 +138,14 @@ TEST_F(MacroHostname, HostProblemId) { hst->process_check_result_3x(engine::host::state_up, "The host is up", CHECK_OPTION_NONE, 0, true, 0); } - + process_macros_r(mac, "$HOSTPROBLEMID:test_host$", out, 0); ASSERT_EQ(out, secondcheck); }; - - fn(_host, "1", "0"); - fn(_host2, "2", "0"); - fn(_host, "3", "0"); + + fn(_host, "1", "0"); + fn(_host2, "2", "0"); + fn(_host, "3", "0"); } // Given host configuration without host_id @@ -162,7 +161,7 @@ TEST_F(MacroHostname, TotalHostOk) { ASSERT_EQ(1u, host::hosts.size()); init_macros(); - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); std::string out; host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); @@ -183,7 +182,7 @@ TEST_F(MacroHostname, TotalHostServicesCritical) { ASSERT_EQ(1u, host::hosts.size()); init_macros(); - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); std::string out; host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); @@ -202,8 +201,8 @@ TEST_F(MacroHostname, HostName) { ASSERT_EQ(1u, host::hosts.size()); std::string out; - nagios_macros* mac(get_global_macros()); - + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$HOSTNAME:test_host$", out, 0); ASSERT_EQ(out, "test_host"); } @@ -219,8 +218,8 @@ TEST_F(MacroHostname, HostAlias) { ASSERT_EQ(1u, host::hosts.size()); std::string out; - nagios_macros* mac(get_global_macros()); - + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$HOSTALIAS:test_host$", out, 0); ASSERT_EQ(out, "test_host"); } @@ -236,8 +235,8 @@ TEST_F(MacroHostname, HostAddress) { ASSERT_EQ(1u, host::hosts.size()); std::string out; - nagios_macros* mac(get_global_macros()); - + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$HOSTADDRESS:test_host$", out, 0); ASSERT_EQ(out, "127.0.0.1"); } @@ -256,7 +255,7 @@ TEST_F(MacroHostname, LastHostCheck) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$LASTHOSTCHECK:test_host$", out, 0); ASSERT_EQ(out, "0"); } @@ -275,7 +274,7 @@ TEST_F(MacroHostname, LastHostStateChange) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$LASTHOSTSTATECHANGE:test_host$", out, 0); ASSERT_EQ(out, "0"); } @@ -294,7 +293,7 @@ TEST_F(MacroHostname, HostOutput) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_plugin_output("foo bar!"); process_macros_r(mac, "$HOSTOUTPUT:test_host$", out, 0); ASSERT_EQ(out, "foo bar!"); @@ -314,7 +313,7 @@ TEST_F(MacroHostname, HostPerfData) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_perf_data("test"); process_macros_r(mac, "$HOSTPERFDATA:test_host$", out, 0); ASSERT_EQ(out, "test"); @@ -333,7 +332,7 @@ TEST_F(MacroHostname, HostState) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$HOSTSTATE:test_host$", out, 1); @@ -353,7 +352,7 @@ TEST_F(MacroHostname, HostStateID) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_down); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$HOSTSTATEID:test_host$", out, 1); @@ -373,7 +372,7 @@ TEST_F(MacroHostname, HostAttempt) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$HOSTATTEMPT:test_host$", out, 1); @@ -396,7 +395,7 @@ TEST_F(MacroHostname, HostExecutionTime) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_execution_time(10.0); process_macros_r(mac, "$HOSTEXECUTIONTIME:test_host$", out, 1); ASSERT_EQ(out, "10.000"); @@ -417,7 +416,7 @@ TEST_F(MacroHostname, HostLatency) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_latency(100); process_macros_r(mac, "$HOSTLATENCY:test_host$", out, 1); ASSERT_EQ(out, "100.000"); @@ -438,7 +437,7 @@ TEST_F(MacroHostname, HostDuration) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTDURATION:test_host$", out, 1); ASSERT_EQ(out, "5787d 0h 53m 20s"); } @@ -458,7 +457,7 @@ TEST_F(MacroHostname, HostDurationSec) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTDURATIONSEC:test_host$", out, 1); ASSERT_EQ(out, "500000000"); } @@ -477,7 +476,7 @@ TEST_F(MacroHostname, HostDownTime) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTDOWNTIME:test_host$", out, 1); ASSERT_EQ(out, "0"); } @@ -496,7 +495,7 @@ TEST_F(MacroHostname, HostStateType) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTSTATETYPE:test_host$", out, 1); ASSERT_EQ(out, "HARD"); } @@ -515,7 +514,7 @@ TEST_F(MacroHostname, HostPercentChange) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTPERCENTCHANGE:test_host$", out, 1); ASSERT_EQ(out, "0.00"); } @@ -555,7 +554,7 @@ TEST_F(MacroHostname, HostGroupName) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTGROUPNAME:a$", out, 1); ASSERT_EQ(out, "temphg"); } @@ -596,7 +595,7 @@ TEST_F(MacroHostname, HostGroupAlias) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTGROUPALIAS:temphg$", out, 1); ASSERT_EQ(out, "temphgal"); } @@ -616,8 +615,8 @@ TEST_F(MacroHostname, LastHostUP) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); - host::hosts["test_host"]->set_last_time_up(30); + nagios_macros *mac(get_global_macros()); +host::hosts["test_host"]->set_last_time_up(30); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$LASTHOSTUP:test_host$", out, 1); ASSERT_EQ(out, "30"); @@ -640,7 +639,7 @@ TEST_F(MacroHostname, LastHostDown) { host::hosts["test_host"]->set_last_time_down(40); host::hosts["test_host"]->set_has_been_checked(true); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$LASTHOSTDOWN:test_host$", out, 1); ASSERT_EQ(out, "40"); } @@ -660,7 +659,7 @@ TEST_F(MacroHostname, LastHostUnreachable) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_last_time_unreachable(50); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$LASTHOSTUNREACHABLE:test_host$", out, 1); @@ -674,7 +673,7 @@ TEST_F(MacroHostname, HostCheckCommand) { ASSERT_TRUE(hst.parse("host_name", "test_host")); ASSERT_TRUE(hst.parse("address", "127.0.0.1")); ASSERT_TRUE(hst.parse("_HOST_ID", "12")); - + configuration::command cmd("cmd"); cmd.parse("command_line", "echo 'output| metric=12;50;75'"); hst.parse("check_command", "cmd"); @@ -688,7 +687,7 @@ TEST_F(MacroHostname, HostCheckCommand) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTCHECKCOMMAND:test_host$", out, 1); ASSERT_EQ(out, "cmd"); } @@ -700,8 +699,7 @@ TEST_F(MacroHostname, HostPerDataFile) { std::remove("/tmp/test-config.cfg"); std::ofstream ofs("/tmp/test-config.cfg"); - ofs << "host_perfdata_file=/var/log/centreon-engine/host-perfdata.dat" - << std::endl; + ofs << "host_perfdata_file=/var/log/centreon-engine/host-perfdata.dat" << std::endl; ofs << "log_file=\"\"" << std::endl; ofs.close(); @@ -710,7 +708,7 @@ TEST_F(MacroHostname, HostPerDataFile) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTPERFDATAFILE:test_host$", out, 1); ASSERT_EQ(out, "/var/log/centreon-engine/host-perfdata.dat"); } @@ -730,7 +728,7 @@ TEST_F(MacroHostname, HostDisplayName) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTDISPLAYNAME:test_host$", out, 1); ASSERT_EQ(out, "test_host"); } @@ -751,7 +749,7 @@ TEST_F(MacroHostname, HostActionUrl) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTACTIONURL:test_host$", out, 1); ASSERT_EQ(out, "test_action_url"); } @@ -772,7 +770,7 @@ TEST_F(MacroHostname, HostNotesUrl) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTNOTESURL:test_host$", out, 1); ASSERT_EQ(out, "test_notes_url"); } @@ -793,7 +791,7 @@ TEST_F(MacroHostname, HostNotes) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTNOTES:test_host$", out, 1); ASSERT_EQ(out, "test_notes"); } @@ -814,7 +812,7 @@ TEST_F(MacroHostname, TotalHostsDown) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_down); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$TOTALHOSTSDOWN:test_host$", out, 1); @@ -837,7 +835,7 @@ TEST_F(MacroHostname, TotalHostsUnreachable) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_unreachable); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$TOTALHOSTSUNREACHABLE:test_host$", out, 1); @@ -860,7 +858,7 @@ TEST_F(MacroHostname, TotalHostsDownUnhandled) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$TOTALHOSTSDOWNUNHANDLED:test_host$", out, 1); ASSERT_EQ(out, "0"); } @@ -881,7 +879,7 @@ TEST_F(MacroHostname, TotalHostsunreachableunhandled) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$TOTALHOSTSUNREACHABLEUNHANDLED:test_host$", out, 1); ASSERT_EQ(out, "0"); } @@ -902,7 +900,7 @@ TEST_F(MacroHostname, TotalHostProblems) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$TOTALHOSTPROBLEMS:test_host$", out, 1); ASSERT_EQ(out, "0"); } @@ -923,7 +921,7 @@ TEST_F(MacroHostname, TotalHostProblemsUnhandled) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$TOTALHOSTPROBLEMSUNHANDLED:test_host$", out, 1); ASSERT_EQ(out, "0"); } @@ -945,7 +943,7 @@ TEST_F(MacroHostname, HostCheckType) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_unreachable); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$HOSTCHECKTYPE:test_host$", out, 0); @@ -969,7 +967,7 @@ TEST_F(MacroHostname, LongHostOutput) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$LONGHOSTOUTPUT:test_host$", out, 0); @@ -993,7 +991,7 @@ TEST_F(MacroHostname, HostNotificationNumber) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$HOSTNOTIFICATIONNUMBER:test_host$", out, 0); @@ -1017,7 +1015,7 @@ TEST_F(MacroHostname, HostNotificationID) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$HOSTNOTIFICATIONID:test_host$", out, 0); @@ -1041,7 +1039,7 @@ TEST_F(MacroHostname, HostEventID) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$HOSTEVENTID:test_host$", out, 0); @@ -1065,7 +1063,7 @@ TEST_F(MacroHostname, LastHostEventID) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$LASTHOSTEVENTID:test_host$", out, 0); @@ -1107,7 +1105,7 @@ TEST_F(MacroHostname, HostGroupNames) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTGROUPNAMES:a$", out, 0); ASSERT_EQ(out, "temphg"); } @@ -1129,7 +1127,7 @@ TEST_F(MacroHostname, MaxHostAttempts) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$MAXHOSTATTEMPTS:test_host$", out, 0); @@ -1153,7 +1151,7 @@ TEST_F(MacroHostname, TotalHostServices) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$TOTALHOSTSERVICES:test_host$", out, 0); @@ -1177,7 +1175,7 @@ TEST_F(MacroHostname, TotalHostServicesOK) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$TOTALHOSTSERVICESOK:test_host$", out, 0); @@ -1201,7 +1199,7 @@ TEST_F(MacroHostname, TotalHostServicesWarning) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$TOTALHOSTSERVICESWARNING:test_host$", out, 0); @@ -1225,7 +1223,7 @@ TEST_F(MacroHostname, TotalHostServicesUnknown) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$TOTALHOSTSERVICESUNKNOWN:test_host$", out, 0); @@ -1268,7 +1266,7 @@ TEST_F(MacroHostname, HostGroupNotes) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTGROUPNOTES:temphg$", out, 0); ASSERT_EQ(out, "test_note"); } @@ -1309,7 +1307,7 @@ TEST_F(MacroHostname, HostGroupNotesUrl) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTGROUPNOTESURL:temphg$", out, 0); ASSERT_EQ(out, "test_note_url"); } @@ -1350,7 +1348,7 @@ TEST_F(MacroHostname, HostGroupActionUrl) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTGROUPACTIONURL:temphg$", out, 0); ASSERT_EQ(out, "test_action_url"); } @@ -1391,7 +1389,7 @@ TEST_F(MacroHostname, HostGroupMembers) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTGROUPMEMBERS:temphg$", out, 0); ASSERT_EQ(out, "c,a"); } @@ -1413,7 +1411,7 @@ TEST_F(MacroHostname, LastHostProblemId) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$LASTHOSTPROBLEMID:test_host$", out, 0); @@ -1437,7 +1435,7 @@ TEST_F(MacroHostname, LastHostState) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$LASTHOSTSTATE:test_host$", out, 0); @@ -1461,7 +1459,7 @@ TEST_F(MacroHostname, LastHostStateID) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$LASTHOSTSTATEID:test_host$", out, 0); @@ -1485,7 +1483,7 @@ TEST_F(MacroHostname, HostParents) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$HOSTPARENTS:test_host$", out, 0); @@ -1534,7 +1532,7 @@ TEST_F(MacroHostname, HostChildren) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$HOSTCHILDREN:parent_host$", out, 0); ASSERT_EQ(out, "child_host"); } @@ -1556,7 +1554,7 @@ TEST_F(MacroHostname, HostID) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$HOSTID:test_host$", out, 0); @@ -1580,7 +1578,7 @@ TEST_F(MacroHostname, HostTimeZone) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_long_plugin_output("test_long_output"); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$HOSTTIMEZONE:test_host$", out, 0); diff --git a/centreon-engine/tests/macros/macro_service.cc b/centreon-engine/tests/macros/macro_service.cc index 3254d28ca88..99df67ce922 100644 --- a/centreon-engine/tests/macros/macro_service.cc +++ b/centreon-engine/tests/macros/macro_service.cc @@ -17,33 +17,33 @@ * */ -#include #include #include -#include #include +#include +#include #include "com/centreon/engine/globals.hh" +#include "../helper.hh" +#include "../test_engine.hh" +#include "../timeperiod/utils.hh" +#include "com/centreon/engine/checks/checker.hh" #include -#include #include #include #include -#include +#include #include #include +#include +#include "com/centreon/engine/configuration/applier/contactgroup.hh" +#include "com/centreon/engine/configuration/applier/serviceescalation.hh" +#include "com/centreon/engine/modules/external_commands/commands.hh" #include #include -#include #include #include -#include "../helper.hh" -#include "../test_engine.hh" -#include "../timeperiod/utils.hh" -#include "com/centreon/engine/checks/checker.hh" -#include "com/centreon/engine/configuration/applier/contactgroup.hh" -#include "com/centreon/engine/configuration/applier/serviceescalation.hh" -#include "com/centreon/engine/modules/external_commands/commands.hh" +#include #include "com/centreon/engine/timeperiod.hh" using namespace com::centreon; @@ -53,7 +53,7 @@ class MacroService : public TestEngine { public: void SetUp() override { init_config_state(); - _tp = _creator.new_timeperiod(); + _tp = _creator.new_timeperiod(); for (int i(0); i < 7; ++i) _creator.new_timerange(0, 0, 24, 0, i); _now = strtotimet("2016-11-24 08:00:00"); @@ -67,9 +67,9 @@ class MacroService : public TestEngine { _svc.reset(); deinit_config_state(); } - - protected: - std::shared_ptr _host, _host2, _host3; + + protected: + std::shared_ptr _host, _host2,_host3; std::shared_ptr _svc; timeperiod_creator _creator; time_t _now; @@ -80,7 +80,7 @@ class MacroService : public TestEngine { // Then the applier add_object throws an exception. TEST_F(MacroService, TotalServicesOkZero) { std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$TOTALSERVICESOK$", out, 0); ASSERT_EQ(out, "0"); } @@ -111,12 +111,11 @@ TEST_F(MacroService, ServiceMacro) { ASSERT_EQ(1u, service::services.size()); init_macros(); - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); std::string out; host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); - service::services[std::make_pair("test_host", "test_svc")]->set_plugin_output( - "foo bar!"); + service::services[std::make_pair("test_host", "test_svc")]->set_plugin_output("foo bar!"); process_macros_r(mac, "$SERVICEOUTPUT:test_host:test_svc$", out, 1); ASSERT_EQ(out, "foo bar!"); } @@ -148,8 +147,8 @@ TEST_F(MacroService, ServiceDesc) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); - + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$SERVICEDESC:test_host:test_svc$", out, 0); ASSERT_EQ(out, "test_svc"); } @@ -181,8 +180,8 @@ TEST_F(MacroService, ServiceState) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); - + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$SERVICESTATE:test_host:test_svc$", out, 0); ASSERT_EQ(out, "OK"); } @@ -214,8 +213,8 @@ TEST_F(MacroService, ServiceStateID) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); - + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$SERVICESTATEID:test_host:test_svc$", out, 0); ASSERT_EQ(out, "0"); } @@ -247,8 +246,8 @@ TEST_F(MacroService, ServiceAttempt) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); - + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$SERVICEATTEMPT:test_host:test_svc$", out, 0); ASSERT_EQ(out, "1"); } @@ -280,8 +279,8 @@ TEST_F(MacroService, ServiceisVolatile) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); - + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$SERVICEISVOLATILE:test_host:test_svc$", out, 0); ASSERT_EQ(out, "0"); } @@ -316,7 +315,7 @@ TEST_F(MacroService, LastServiceCheck) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$LASTSERVICECHECK:test_host:test_svc$", out, 0); @@ -353,7 +352,7 @@ TEST_F(MacroService, LastServiceStateChange) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); process_macros_r(mac, "$LASTSERVICESTATECHANGE:test_host:test_svc$", out, 0); @@ -390,11 +389,10 @@ TEST_F(MacroService, ServicePerfData) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); - service::services[std::make_pair("test_host", "test_svc")]->set_perf_data( - "foo"); + service::services[std::make_pair("test_host", "test_svc")]->set_perf_data("foo"); process_macros_r(mac, "$SERVICEPERFDATA:test_host:test_svc$", out, 0); ASSERT_EQ(out, "foo"); } @@ -417,7 +415,7 @@ TEST_F(MacroService, ServiceExecutionTime) { ASSERT_TRUE(hst.parse("address", "127.0.0.1")); ASSERT_TRUE(hst.parse("_HOST_ID", "12")); ASSERT_TRUE(hst.parse("contacts", "user")); - // ASSERT_TRUE(hst.parse("contact_name", "testeeeeee")); + //ASSERT_TRUE(hst.parse("contact_name", "testeeeeee")); ASSERT_NO_THROW(hst_aply.add_object(hst)); ASSERT_EQ(1u, host::hosts.size()); ASSERT_TRUE(svc.parse("description", "test_svc")); @@ -440,11 +438,10 @@ TEST_F(MacroService, ServiceExecutionTime) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); - service::services[std::make_pair("test_host", "test_svc")] - ->set_execution_time(20.00); + service::services[std::make_pair("test_host", "test_svc")]->set_execution_time(20.00); process_macros_r(mac, "$SERVICEEXECUTIONTIME:test_host:test_svc$", out, 1); ASSERT_EQ(out, "20.000"); } @@ -467,7 +464,7 @@ TEST_F(MacroService, ServiceLatency) { ASSERT_TRUE(hst.parse("address", "127.0.0.1")); ASSERT_TRUE(hst.parse("_HOST_ID", "12")); ASSERT_TRUE(hst.parse("contacts", "user")); - // ASSERT_TRUE(hst.parse("contact_name", "testeeeeee")); + //ASSERT_TRUE(hst.parse("contact_name", "testeeeeee")); ASSERT_NO_THROW(hst_aply.add_object(hst)); ASSERT_EQ(1u, host::hosts.size()); ASSERT_TRUE(svc.parse("description", "test_svc")); @@ -490,11 +487,10 @@ TEST_F(MacroService, ServiceLatency) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); - service::services[std::make_pair("test_host", "test_svc")]->set_latency( - 20.00); + service::services[std::make_pair("test_host", "test_svc")]->set_latency(20.00); process_macros_r(mac, "$SERVICELATENCY:test_host:test_svc$", out, 1); ASSERT_EQ(out, "20.000"); } @@ -517,7 +513,7 @@ TEST_F(MacroService, ServiceDuration) { ASSERT_TRUE(hst.parse("address", "127.0.0.1")); ASSERT_TRUE(hst.parse("_HOST_ID", "12")); ASSERT_TRUE(hst.parse("contacts", "user")); - // ASSERT_TRUE(hst.parse("contact_name", "testeeeeee")); + //ASSERT_TRUE(hst.parse("contact_name", "testeeeeee")); ASSERT_NO_THROW(hst_aply.add_object(hst)); ASSERT_EQ(1u, host::hosts.size()); ASSERT_TRUE(svc.parse("description", "test_svc")); @@ -540,11 +536,10 @@ TEST_F(MacroService, ServiceDuration) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); - service::services[std::make_pair("test_host", "test_svc")]->set_latency( - 20.00); + service::services[std::make_pair("test_host", "test_svc")]->set_latency(20.00); process_macros_r(mac, "$SERVICEDURATION:test_host:test_svc$", out, 1); ASSERT_EQ(out, "5787d 0h 53m 20s"); } @@ -589,11 +584,10 @@ TEST_F(MacroService, ServiceDurationSec) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); host::hosts["test_host"]->set_current_state(host::state_up); host::hosts["test_host"]->set_has_been_checked(true); - service::services[std::make_pair("test_host", "test_svc")]->set_latency( - 20.00); + service::services[std::make_pair("test_host", "test_svc")]->set_latency(20.00); process_macros_r(mac, "$SERVICEDURATIONSEC:test_host:test_svc$", out, 1); ASSERT_EQ(out, "500000000"); } @@ -628,7 +622,7 @@ TEST_F(MacroService, ServiceDownTime) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICEDOWNTIME:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -663,7 +657,7 @@ TEST_F(MacroService, ServiceStateType) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICESTATETYPE:test_host:test_svc$", out, 1); ASSERT_EQ(out, "HARD"); } @@ -698,7 +692,7 @@ TEST_F(MacroService, ServicePercentChange) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICEPERCENTCHANGE:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0.00"); } @@ -738,7 +732,7 @@ TEST_F(MacroService, ServiceGroupName) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICEGROUPNAME:test_host:test$", out, 1); ASSERT_EQ(out, "test_group"); } @@ -779,7 +773,7 @@ TEST_F(MacroService, ServiceGroupAlias) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICEGROUPALIAS:test_group$", out, 1); ASSERT_EQ(out, "test_group_alias"); } @@ -814,9 +808,8 @@ TEST_F(MacroService, LastServiceOK) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")]->set_last_time_ok( - 20); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_last_time_ok(20); process_macros_r(mac, "$LASTSERVICEOK:test_host:test_svc$", out, 1); ASSERT_EQ(out, "20"); } @@ -851,9 +844,8 @@ TEST_F(MacroService, LastServiceWarning) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_last_time_warning(30); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_last_time_warning(30); process_macros_r(mac, "$LASTSERVICEWARNING:test_host:test_svc$", out, 1); ASSERT_EQ(out, "30"); } @@ -888,9 +880,8 @@ TEST_F(MacroService, LastServiceUnknown) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_last_time_unknown(40); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_last_time_unknown(40); process_macros_r(mac, "$LASTSERVICEUNKNOWN:test_host:test_svc$", out, 1); ASSERT_EQ(out, "40"); } @@ -925,9 +916,8 @@ TEST_F(MacroService, LastServiceCritical) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_last_time_critical(50); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_last_time_critical(50); process_macros_r(mac, "$LASTSERVICECRITICAL:test_host:test_svc$", out, 1); ASSERT_EQ(out, "50"); } @@ -962,9 +952,8 @@ TEST_F(MacroService, ServiceCheckCommand) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_last_time_critical(50); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_last_time_critical(50); process_macros_r(mac, "$SERVICECHECKCOMMAND:test_host:test_svc$", out, 1); ASSERT_EQ(out, "cmd"); } @@ -976,8 +965,7 @@ TEST_F(MacroService, ServicePerfDataFile) { std::remove("/tmp/test-config.cfg"); std::ofstream ofs("/tmp/test-config.cfg"); - ofs << "service_perfdata_file=/var/log/centreon-engine/service-perfdata.dat" - << std::endl; + ofs << "service_perfdata_file=/var/log/centreon-engine/service-perfdata.dat" << std::endl; ofs << "log_file=\"\"" << std::endl; ofs.close(); @@ -986,7 +974,7 @@ TEST_F(MacroService, ServicePerfDataFile) { init_macros(); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICEPERFDATAFILE:test_host$", out, 1); ASSERT_EQ(out, "/var/log/centreon-engine/service-perfdata.dat"); } @@ -1021,9 +1009,8 @@ TEST_F(MacroService, ServiceDisplayName) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_last_time_critical(50); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_last_time_critical(50); process_macros_r(mac, "$SERVICEDISPLAYNAME:test_host:test_svc$", out, 1); ASSERT_EQ(out, "test_svc"); } @@ -1059,7 +1046,7 @@ TEST_F(MacroService, ServiceNotesUrl) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICENOTESURL:test_host:test_svc$", out, 1); ASSERT_EQ(out, "http://192.168.0.172/centreon/main.php"); } @@ -1095,7 +1082,7 @@ TEST_F(MacroService, ServiceNotes) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICENOTES:test_host:test_svc$", out, 1); ASSERT_EQ(out, "test_notes"); } @@ -1131,7 +1118,7 @@ TEST_F(MacroService, ServiceActionUrl) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICEACTIONURL:test_host:test_svc$", out, 1); ASSERT_EQ(out, "test_action_url"); } @@ -1167,7 +1154,7 @@ TEST_F(MacroService, TotalServicesWarning) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$TOTALSERVICESWARNING:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1203,7 +1190,7 @@ TEST_F(MacroService, TotalServicesCritical) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$TOTALSERVICESCRITICAL:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1239,7 +1226,7 @@ TEST_F(MacroService, TotalServicesUnknown) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$TOTALSERVICESUNKNOWN:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1275,9 +1262,8 @@ TEST_F(MacroService, TotalServicesWarningUnhandled) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - process_macros_r(mac, "$TOTALSERVICESWARNINGUNHANDLED:test_host:test_svc$", - out, 1); + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$TOTALSERVICESWARNINGUNHANDLED:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1312,9 +1298,8 @@ TEST_F(MacroService, TotalServicesCriticalUnhandled) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - process_macros_r(mac, "$TOTALSERVICESCRITICALUNHANDLED:test_host:test_svc$", - out, 1); + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$TOTALSERVICESCRITICALUNHANDLED:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1349,9 +1334,8 @@ TEST_F(MacroService, TotalServicesUnknownUnhandled) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - process_macros_r(mac, "$TOTALSERVICESUNKNOWNUNHANDLED:test_host:test_svc$", - out, 1); + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$TOTALSERVICESUNKNOWNUNHANDLED:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1386,7 +1370,7 @@ TEST_F(MacroService, TotalServiceProblems) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$TOTALSERVICEPROBLEMS:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1422,9 +1406,8 @@ TEST_F(MacroService, TotalServiceProblemsUnhandled) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - process_macros_r(mac, "$TOTALSERVICEPROBLEMSUNHANDLED:test_host:test_svc$", - out, 1); + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$TOTALSERVICEPROBLEMSUNHANDLED:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1459,7 +1442,7 @@ TEST_F(MacroService, ServiceCheckType) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICECHECKTYPE:test_host:test_svc$", out, 1); ASSERT_EQ(out, "ACTIVE"); } @@ -1495,9 +1478,8 @@ TEST_F(MacroService, LongServiceOutput) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$LONGSERVICEOUTPUT:test_host:test_svc$", out, 1); ASSERT_EQ(out, "test_long_output"); } @@ -1533,9 +1515,8 @@ TEST_F(MacroService, ServiceNotificationID) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$SERVICENOTIFICATIONID:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1571,9 +1552,8 @@ TEST_F(MacroService, ServiceEventID) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$SERVICEEVENTID:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1609,9 +1589,8 @@ TEST_F(MacroService, LastServiceEventID) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$LASTSERVICEEVENTID:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -1651,9 +1630,8 @@ TEST_F(MacroService, ServiceGroupNames) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$SERVICEGROUPNAMES:test_host:test$", out, 1); ASSERT_EQ(out, "test_group"); } @@ -1689,9 +1667,8 @@ TEST_F(MacroService, MaxServiceAttempts) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$MAXSERVICEATTEMPTS:test_host:test_svc$", out, 1); ASSERT_EQ(out, "3"); } @@ -1731,9 +1708,8 @@ TEST_F(MacroService, ServiceGroupNotes) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$SERVICEGROUPNOTES:test_group$", out, 1); ASSERT_EQ(out, "test_notes"); } @@ -1773,7 +1749,7 @@ TEST_F(MacroService, ServiceGroupNotesUrl) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICEGROUPNOTESURL:test_group$", out, 1); ASSERT_EQ(out, "test_notes_url"); } @@ -1813,7 +1789,7 @@ TEST_F(MacroService, ServiceGroupActionUrl) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICEGROUPACTIONURL:test_group$", out, 1); ASSERT_EQ(out, "test_notes_url"); } @@ -1853,7 +1829,7 @@ TEST_F(MacroService, ServiceGroupMembers) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICEGROUPMEMBERS:test_group$", out, 1); ASSERT_EQ(out, "test_host,test"); } @@ -1890,7 +1866,7 @@ TEST_F(MacroService, ServiceID) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); + nagios_macros *mac(get_global_macros()); process_macros_r(mac, "$SERVICEID:test_host:test_svc$", out, 0); ASSERT_EQ(out, "13"); } @@ -1927,9 +1903,8 @@ TEST_F(MacroService, ServiceTimeZone) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$SERVICETIMEZONE:test_host:test_svc$", out, 1); ASSERT_EQ(out, "test_time"); } @@ -1965,9 +1940,8 @@ TEST_F(MacroService, LastServiceState) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$LASTSERVICESTATE:test_host:test_svc$", out, 1); ASSERT_EQ(out, "OK"); } @@ -2003,9 +1977,8 @@ TEST_F(MacroService, LastServiceStateId) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$LASTSERVICESTATEID:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } @@ -2016,8 +1989,7 @@ TEST_F(MacroService, ServiceProblemID) { configuration::applier::contact ct_aply; configuration::contact ctct{new_configuration_contact("admin", true)}; ct_aply.add_object(ctct); - configuration::contact ctct1{ - new_configuration_contact("admin1", false, "c,r")}; + configuration::contact ctct1{new_configuration_contact("admin1", false, "c,r")}; ct_aply.add_object(ctct1); ct_aply.expand_objects(*config); ct_aply.resolve_object(ctct); @@ -2073,9 +2045,10 @@ TEST_F(MacroService, ServiceProblemID) { std::string cmd{oss.str()}; process_external_command(cmd.c_str()); checks::checker::instance().reap(); + } - nagios_macros* mac(get_global_macros()); - process_macros_r(mac, "$SERVICEPROBLEMID:test_host:test_svc$", out, 0); + nagios_macros *mac(get_global_macros()); + process_macros_r(mac, "$SERVICEPROBLEMID:test_host:test_svc$", out, 0); ASSERT_EQ(out, "4"); } @@ -2110,9 +2083,8 @@ TEST_F(MacroService, LastServiceProblemID) { set_time(now); std::string out; - nagios_macros* mac(get_global_macros()); - service::services[std::make_pair("test_host", "test_svc")] - ->set_long_plugin_output("test_long_output"); + nagios_macros *mac(get_global_macros()); + service::services[std::make_pair("test_host", "test_svc")]->set_long_plugin_output("test_long_output"); process_macros_r(mac, "$LASTSERVICEPROBLEMID:test_host:test_svc$", out, 1); ASSERT_EQ(out, "0"); } \ No newline at end of file diff --git a/centreon-engine/tests/main.cc b/centreon-engine/tests/main.cc index 58d5f1d4602..d874e78ffab 100644 --- a/centreon-engine/tests/main.cc +++ b/centreon-engine/tests/main.cc @@ -27,7 +27,9 @@ class CentreonEngineEnvironment : public testing::Environment { return; } - void TearDown() override { return; } + void TearDown() override { + return; + } }; /** diff --git a/centreon-engine/tests/notifications/host_downtime_notification.cc b/centreon-engine/tests/notifications/host_downtime_notification.cc index 7abbd04f112..72cc51f06e8 100644 --- a/centreon-engine/tests/notifications/host_downtime_notification.cc +++ b/centreon-engine/tests/notifications/host_downtime_notification.cc @@ -20,19 +20,19 @@ #include #include -#include #include "../test_engine.hh" #include "../timeperiod/utils.hh" #include "com/centreon/engine/checks/checker.hh" #include "com/centreon/engine/configuration/applier/contact.hh" #include "com/centreon/engine/configuration/applier/contactgroup.hh" -#include "com/centreon/engine/configuration/applier/host.hh" +#include #include "com/centreon/engine/configuration/applier/hostescalation.hh" +#include "com/centreon/engine/configuration/applier/host.hh" #include "com/centreon/engine/configuration/host.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/hostescalation.hh" -#include "com/centreon/engine/modules/external_commands/commands.hh" #include "com/centreon/engine/timeperiod.hh" +#include "com/centreon/engine/modules/external_commands/commands.hh" #include "helper.hh" using namespace com::centreon; @@ -185,8 +185,7 @@ TEST_F(HostDowntimeNotification, SimpleHostDowntimeNotifyContactExitingUp) { std::cout << "NOW = " << now << std::endl; set_time(now); std::ostringstream oss; - oss << '[' << now << ']' - << " PROCESS_HOST_CHECK_RESULT;test_host;1;Down host"; + oss << '[' << now << ']' << " PROCESS_HOST_CHECK_RESULT;test_host;1;Down host"; std::string cmd{oss.str()}; process_external_command(cmd.c_str()); checks::checker::instance().reap(); @@ -217,8 +216,9 @@ TEST_F(HostDowntimeNotification, SimpleHostDowntimeNotifyContactExitingUp) { std::cout << out << std::endl; size_t step1{out.find("NOW = 50300")}; ASSERT_NE(step1, std::string::npos); - size_t step2{out.find("HOST NOTIFICATION: admin;test_host;DOWN;cmd;Down host", - step1 + 1)}; + size_t step2{ + out.find("HOST NOTIFICATION: admin;test_host;DOWN;cmd;Down host", + step1 + 1)}; ASSERT_NE(step2, std::string::npos); size_t step3{out.find("NOW = 50600", step2 + 1)}; ASSERT_NE(step3, std::string::npos); diff --git a/centreon-engine/tests/notifications/host_flapping_notification.cc b/centreon-engine/tests/notifications/host_flapping_notification.cc index d6d75e70cd4..94705561d1c 100644 --- a/centreon-engine/tests/notifications/host_flapping_notification.cc +++ b/centreon-engine/tests/notifications/host_flapping_notification.cc @@ -248,8 +248,7 @@ TEST_F(HostFlappingNotification, CheckFlapping) { CHECK_OPTION_NONE, 0, true, 0); } - // This loop is to store many UP or DOWN in the state history to start - // flapping. + // This loop is to store many UP or DOWN in the state history to start flapping. testing::internal::CaptureStdout(); for (int i = 1; i < 12; i++) { std::cout << "Step " << i << ":"; @@ -313,8 +312,7 @@ TEST_F(HostFlappingNotification, CheckFlappingWithHostParentDown) { CHECK_OPTION_NONE, 0, true, 0); } - // This loop is to store many UP or DOWN in the state history to start - // flapping. + // This loop is to store many UP or DOWN in the state history to start flapping. testing::internal::CaptureStdout(); for (int i = 1; i < 12; i++) { std::cout << "Step " << i << ":"; diff --git a/centreon-engine/tests/notifications/service_flapping_notification.cc b/centreon-engine/tests/notifications/service_flapping_notification.cc index fd53861c857..ebc978da956 100644 --- a/centreon-engine/tests/notifications/service_flapping_notification.cc +++ b/centreon-engine/tests/notifications/service_flapping_notification.cc @@ -288,8 +288,7 @@ TEST_F(ServiceFlappingNotification, CheckFlapping) { } testing::internal::CaptureStdout(); - // This loop is to store many CRITICAL or OK in the state history to start the - // flapping. + // This loop is to store many CRITICAL or OK in the state history to start the flapping. for (int i = 1; i < 8; i++) { now += 300; std::cout << "NOW = " << now << std::endl; @@ -308,8 +307,7 @@ TEST_F(ServiceFlappingNotification, CheckFlapping) { checks::checker::instance().reap(); } - // This loop is to store many CRITICAL in the state history to stop the - // flapping. + // This loop is to store many CRITICAL in the state history to stop the flapping. for (int i = 1; i < 18; i++) { std::cout << "Step " << i << ":"; now += 300; @@ -382,8 +380,7 @@ TEST_F(ServiceFlappingNotification, CheckFlappingWithHostDown) { } testing::internal::CaptureStdout(); - // This loop is to store many CRITICAL or OK in the state history to start the - // flapping. + // This loop is to store many CRITICAL or OK in the state history to start the flapping. for (int i = 1; i < 8; i++) { now += 300; std::cout << "NOW = " << now << std::endl; @@ -402,8 +399,7 @@ TEST_F(ServiceFlappingNotification, CheckFlappingWithHostDown) { checks::checker::instance().reap(); } - // This loop is to store many CRITICAL in the state history to stop the - // flapping. + // This loop is to store many CRITICAL in the state history to stop the flapping. for (int i = 1; i < 18; i++) { std::cout << "Step " << i << ":"; now += 300; @@ -470,8 +466,7 @@ TEST_F(ServiceFlappingNotification, RetentionFlappingNotification) { checks::checker::instance().reap(); } - // This loop is to store many CRITICAL or OK in the state history to start the - // flapping. + // This loop is to store many CRITICAL or OK in the state history to start the flapping. for (int i = 1; i < 8; i++) { now += 300; std::cout << "NOW = " << now << std::endl; @@ -489,9 +484,8 @@ TEST_F(ServiceFlappingNotification, RetentionFlappingNotification) { process_external_command(cmd.c_str()); checks::checker::instance().reap(); } - - // This loop is to store many CRITICAL in the state history to stop the - // flapping. + + // This loop is to store many CRITICAL in the state history to stop the flapping. for (int i = 1; i < 18; i++) { std::cout << "Step " << i << ":"; now += 300; diff --git a/centreon-engine/tests/notifications/service_timeperiod_notification.cc b/centreon-engine/tests/notifications/service_timeperiod_notification.cc index 9ccbd27db2f..06db78af0f3 100644 --- a/centreon-engine/tests/notifications/service_timeperiod_notification.cc +++ b/centreon-engine/tests/notifications/service_timeperiod_notification.cc @@ -227,6 +227,7 @@ TEST_F(ServiceTimePeriodNotification, NoTimePeriodOk) { } TEST_F(ServiceTimePeriodNotification, NoTimePeriodKo) { + init_macros(); std::unique_ptr tperiod{ new engine::timeperiod("tperiod", "alias")}; diff --git a/centreon-engine/tests/retention/dump.cc b/centreon-engine/tests/retention/dump.cc index 034095dc132..fef793702a1 100644 --- a/centreon-engine/tests/retention/dump.cc +++ b/centreon-engine/tests/retention/dump.cc @@ -28,15 +28,19 @@ using namespace com::centreon::engine::retention; class RetentionDumpTest : public ::testing::Test { public: - void SetUp() { init_config_state(); } + void SetUp() { + init_config_state(); + } - void TearDown() { deinit_config_state(); } + void TearDown() { + deinit_config_state(); + } }; TEST_F(RetentionDumpTest, DumpComment) { comment cmt(comment::host, comment::flapping, 12, 0, time(nullptr), - "Test comment", "test comment", false, comment::internal, false, - 0); + "Test comment", "test comment", false, + comment::internal, false, 0); std::ostringstream oss; dump::comments(oss); std::string str(oss.str()); diff --git a/centreon-engine/tests/timeperiod/get_next_valid_time/generic_month_date.cc b/centreon-engine/tests/timeperiod/get_next_valid_time/generic_month_date.cc index 9a2e6244e4d..fc2ceb1450b 100644 --- a/centreon-engine/tests/timeperiod/get_next_valid_time/generic_month_date.cc +++ b/centreon-engine/tests/timeperiod/get_next_valid_time/generic_month_date.cc @@ -29,6 +29,7 @@ using namespace com::centreon::engine; class GetNextValidTimeGenericMonthDateTest : public ::testing::Test { public: + void default_data_set() { _creator.new_timeperiod(); daterange* dr(NULL); diff --git a/centreon-engine/tests/timeperiod/get_next_valid_time/normal_weekday.cc b/centreon-engine/tests/timeperiod/get_next_valid_time/normal_weekday.cc index 9e630517cdf..249a69af282 100644 --- a/centreon-engine/tests/timeperiod/get_next_valid_time/normal_weekday.cc +++ b/centreon-engine/tests/timeperiod/get_next_valid_time/normal_weekday.cc @@ -29,6 +29,7 @@ using namespace com::centreon::engine; class GetNextValidTimeNormalWeekdayTest : public ::testing::Test { public: + void default_data_set() { _creator.new_timeperiod(); // tuesday 10:30-11:45,18:30-23:30 diff --git a/centreon-engine/tests/timeperiod/get_next_valid_time/offset_weekday_of_generic_month.cc b/centreon-engine/tests/timeperiod/get_next_valid_time/offset_weekday_of_generic_month.cc index d32f5ba9b66..3868fc4145e 100644 --- a/centreon-engine/tests/timeperiod/get_next_valid_time/offset_weekday_of_generic_month.cc +++ b/centreon-engine/tests/timeperiod/get_next_valid_time/offset_weekday_of_generic_month.cc @@ -29,6 +29,7 @@ using namespace com::centreon::engine; class GetNextValidTimeOffsetWeekdayOfGenericMonthTest : public ::testing::Test { public: + void default_data_set() { _creator.new_timeperiod(); daterange* dr(NULL); diff --git a/centreon-engine/tests/timeperiod/get_next_valid_time/offset_weekday_of_specific_month.cc b/centreon-engine/tests/timeperiod/get_next_valid_time/offset_weekday_of_specific_month.cc index 50adbadda19..80dbf123b8b 100644 --- a/centreon-engine/tests/timeperiod/get_next_valid_time/offset_weekday_of_specific_month.cc +++ b/centreon-engine/tests/timeperiod/get_next_valid_time/offset_weekday_of_specific_month.cc @@ -30,6 +30,7 @@ using namespace com::centreon::engine; class GetNextValidTimeOffsetWeekdayOfSpecificMonthTest : public ::testing::Test { public: + void default_data_set() { _creator.new_timeperiod(); daterange* dr(NULL); diff --git a/centreon-engine/tests/timeperiod/get_next_valid_time/specific_month_date.cc b/centreon-engine/tests/timeperiod/get_next_valid_time/specific_month_date.cc index 4e44ac9209e..ac1c9e79ccc 100644 --- a/centreon-engine/tests/timeperiod/get_next_valid_time/specific_month_date.cc +++ b/centreon-engine/tests/timeperiod/get_next_valid_time/specific_month_date.cc @@ -29,6 +29,7 @@ using namespace com::centreon::engine; class GetNextValidTimeSpecificMonthDateTest : public ::testing::Test { public: + void default_data_set() { _creator.new_timeperiod(); daterange* dr(NULL); diff --git a/centreon-engine/tests/timeperiod/utils.cc b/centreon-engine/tests/timeperiod/utils.cc index df443df2229..8f52ad26946 100644 --- a/centreon-engine/tests/timeperiod/utils.cc +++ b/centreon-engine/tests/timeperiod/utils.cc @@ -319,7 +319,7 @@ extern "C" time_t time(time_t* t) __THROW { return (gl_now); } -extern "C" int gettimeofday(struct timeval* tv, struct timezone* tz) __THROW { +extern "C" int gettimeofday(struct timeval* tv, struct timezone *tz) __THROW { if (tv) { tv->tv_sec = gl_now; tv->tv_usec = 0; diff --git a/centreon-tests/.eslintignore b/centreon-tests/.eslintignore new file mode 100644 index 00000000000..cae7fb018e4 --- /dev/null +++ b/centreon-tests/.eslintignore @@ -0,0 +1,5 @@ +### +apps/ +logs/ +./build/ +licenses/ diff --git a/centreon-tests/.eslintrc.js b/centreon-tests/.eslintrc.js new file mode 100644 index 00000000000..46fe26d5b5d --- /dev/null +++ b/centreon-tests/.eslintrc.js @@ -0,0 +1,8 @@ +module.exports = { + extends: + './node_modules/@centreon/frontend-core/eslint/node/typescript.eslintrc.js', + rules: { + 'import/extensions': ['off'], + 'no-console': 'off', + }, +}; diff --git a/centreon-tests/broker-database/networkFailure.robot b/centreon-tests/broker-database/networkFailure.robot index 01e051cc3aa..0c78be1a443 100644 --- a/centreon-tests/broker-database/networkFailure.robot +++ b/centreon-tests/broker-database/networkFailure.robot @@ -1,196 +1,64 @@ *** Settings *** -Resource ../resources/resources.robot -Suite Setup Clean Before Suite -Suite Teardown Clean After Suite -Test Setup Stop Processes +Resource ../resources/resources.robot +Suite Setup Clean Before Suite +Suite Teardown Clean After Suite +Test Setup Stop Processes -Documentation Centreon Broker database connection failure -Library Process -Library DateTime -Library OperatingSystem -Library ../resources/Common.py -Library ../resources/Broker.py -Library ../resources/Engine.py +Documentation Centreon Broker database connection failure +Library Process +Library DateTime +Library OperatingSystem +Library ../resources/BrokerDatabase.py +Library ../resources/Common.py +Library ../resources/Broker.py +Library ../resources/Engine.py *** Test Cases *** NetworkDbFail1 - [Documentation] network failure test between broker and database (shutting down connection for 100ms) - [Tags] Broker Database Network - Network Failure interval=100ms - + [Documentation] network failure test between broker and database (shutting down connection for 100ms) + [Tags] Broker Database Network + Network Failure interval=100ms NetworkDbFail2 - [Documentation] network failure test between broker and database (shutting down connection for 1s) - [Tags] Broker Database Network - Network Failure interval=1s - + [Documentation] network failure test between broker and database (shutting down connection for 1s) + [Tags] Broker Database Network + Network Failure interval=1s NetworkDbFail3 - [Documentation] network failure test between broker and database (shutting down connection for 10s) - [Tags] Broker Database Network - Network Failure interval=10s - + [Documentation] network failure test between broker and database (shutting down connection for 10s) + [Tags] Broker Database Network + Network Failure interval=10s NetworkDbFail4 - [Documentation] network failure test between broker and database (shutting down connection for 30s) - [Tags] Broker Database Network - Network Failure interval=30s - + [Documentation] network failure test between broker and database (shutting down connection for 30s) + [Tags] Broker Database Network + Network Failure interval=30s NetworkDbFail5 - [Documentation] network failure test between broker and database (shutting down connection for 60s) - [Tags] Broker Database Network - Network Failure interval=1m - -NetworkDBFail6 - [Documentation] network failure test between broker and database: we wait for the connection to be established and then we shut down the connection for 60s - [Tags] Broker Database Network - Config Engine ${1} - Config Broker central - Broker Config Output Set central central-broker-master-sql db_host 127.0.0.1 - Broker Config Output set central central-broker-master-sql connections_count 5 - Broker Config Output Set central central-broker-master-perfdata db_host 127.0.0.1 - Broker Config Output set central central-broker-master-perfdata connections_count 5 - Broker Config Log central sql trace - Config Broker rrd - Config Broker module - ${start}= Get Current Date - Start Broker - Start Engine - ${result}= Check Connections - Should Be True ${result} msg=Broker and Engine are not connected - ${content}= Create List run query: SELECT - ${result}= Find In Log With Timeout ${logCbd} ${start} ${content} 40 - Should Be True ${result} msg=No SELECT done by broker in the DB - Disable Eth Connection On Port port=3306 - Sleep 1m - Reset Eth Connection - ${content}= Create List 0 events acknowledged - ${result}= Find In Log With Timeout ${logCbd} ${start} ${content} 40 - Stop Engine - Stop Broker - -NetworkDBFailU6 - [Documentation] network failure test between broker and database: we wait for the connection to be established and then we shut down the connection for 60s (with unified_sql) - [Tags] Broker Database Network unified_sql - Reset Eth Connection - Config Engine ${1} - Config Broker central - Config Broker Sql Output central unified_sql - Broker Config Output Set central central-broker-unified-sql db_host 127.0.0.1 - Broker Config Output set central central-broker-unified-sql connections_count 5 - Broker Config Log central sql trace - Config Broker rrd - Config Broker module - ${start}= Get Current Date - Start Broker - Start Engine - ${result}= Check Connections - Should Be True ${result} msg=Broker and Engine are not connected - ${content}= Create List run query: SELECT - ${result}= Find In Log With Timeout ${logCbd} ${start} ${content} 40 - Should Be True ${result} msg=No SELECT done by broker in the DB - Disable Eth Connection On Port port=3306 - Sleep 1m - Reset Eth Connection - ${content}= Create List 0 events acknowledged - ${result}= Find In Log With Timeout ${logCbd} ${start} ${content} 40 - Stop Engine - Stop Broker - -NetworkDBFail7 - [Documentation] network failure test between broker and database: we wait for the connection to be established and then we shut down the connection for 60s - [Tags] Broker Database Network - Config Engine ${1} - Config Broker central - Reset Eth Connection - Broker Config Output Set central central-broker-master-sql db_host 127.0.0.1 - Broker Config Output set central central-broker-master-sql connections_count 5 - Broker Config Output Set central central-broker-master-perfdata db_host 127.0.0.1 - Broker Config Output set central central-broker-master-perfdata connections_count 5 - Broker Config Log central sql trace - Config Broker rrd - Config Broker module - ${start}= Get Current Date - Start Broker - Start Engine - ${result}= Check Connections - Should Be True ${result} msg=Broker and Engine are not connected - ${content}= Create List run query: SELECT - ${result}= Find In Log With Timeout ${logCbd} ${start} ${content} 40 - Should Be True ${result} msg=No SELECT done by broker in the DB - FOR ${i} IN 0 5 - Disable Eth Connection On Port port=3306 - Sleep 10s - Reset Eth Connection - Sleep 10s - END - ${content}= Create List 0 events acknowledged - ${result}= Find In Log With Timeout ${logCbd} ${start} ${content} 60 - Should Be True ${result} msg=There are still events in the queue. - Stop Engine - Stop Broker - -NetworkDBFailU7 - [Documentation] network failure test between broker and database: we wait for the connection to be established and then we shut down the connection for 60s (with unified_sql) - [Tags] Broker Database Network unified_sql - Reset Eth Connection - Config Engine ${1} - Config Broker central - Config Broker Sql Output central unified_sql - Broker Config Output Set central central-broker-unified-sql db_host 127.0.0.1 - Broker Config Output set central central-broker-unified-sql connections_count 5 - Broker Config Log central sql trace - Config Broker rrd - Config Broker module - ${start}= Get Current Date - Start Broker - Start Engine - ${result}= Check Connections - Should Be True ${result} msg=Broker and Engine are not connected - ${content}= Create List run query: SELECT - ${result}= Find In Log With Timeout ${logCbd} ${start} ${content} 40 - Should Be True ${result} msg=No SELECT done by broker in the DB - FOR ${i} IN 0 5 - Disable Eth Connection On Port port=3306 - Sleep 10s - Reset Eth Connection - Sleep 10s - END - ${content}= Create List 0 events acknowledged - ${result}= Find In Log With Timeout ${logCbd} ${start} ${content} 60 - Should Be True ${result} msg=There are still events in the queue. - Stop Engine - Stop Broker + [Documentation] network failure test between broker and database (shutting down connection for 60s) + [Tags] Broker Database Network + Network Failure interval=1m *** Keywords *** Disable Sleep Enable [Arguments] ${interval} Disable Eth Connection On Port port=3306 - Sleep ${interval} + Sleep ${interval} Reset Eth Connection - Network Failure - [Arguments] ${interval} - Reset Eth Connection + [Arguments] ${interval} Config Engine ${1} - Config Broker module - Config Broker rrd - Config Broker central - Broker Config Output Set central central-broker-master-sql db_host 127.0.0.1 - Broker Config Output set central central-broker-master-sql connections_count 5 - Broker Config Output Set central central-broker-master-perfdata db_host 127.0.0.1 - Broker Config Output set central central-broker-master-perfdata connections_count 5 - Broker Config Log central sql trace - ${start}= Get Current Date - Start Broker + Config Broker central + Broker Config Output Set central central-broker-master-sql db_host 127.0.0.1 + Broker Config Log central sql trace + ${start}= Get Current Date + Start mysql + Start Broker Start Engine - ${content}= Create List SQL: performing mysql_ping - ${result}= Find In Log With Timeout ${logCbd} ${start} ${content} 50 - Should Be True ${result} msg=We should have a call to mysql_ping every 30s on inactive connections. - Disable Sleep Enable ${interval} - ${end}= Get Current Date - ${content}= Create List mysql_connection: commit - ${result}= Find In Log With Timeout ${logCbd} ${end} ${content} 80 - Should Be True ${result} msg=timeout after network to be restablished (network failure duration : ${interval}) + ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log + ${content}= Set Variable SQL: performing mysql_ping. + ${result}= Do When Catch In Log ${log} ${start} ${content} Disable Sleep Enable ${interval} + ${end}= Get Current Date + ${content}= Set Variable mysql_connection: commit + Should Not Be Equal ${result} False msg=timeout after 5 minutes (network failure duration : ${interval}) + ${result}= Catch In Log ${log} ${end} ${content} + Should Be True ${result} msg=timeout after 5 minutes (mysql_ping may be hanging) Stop Broker Stop Engine - -*** Variables *** -${logCbd} ${BROKER_LOG}/central-broker-master.log + Stop Mysql \ No newline at end of file diff --git a/centreon-tests/broker-engine/hostgroups.robot b/centreon-tests/broker-engine/hostgroups.robot index e7bc5f5259c..c02dfa0e872 100644 --- a/centreon-tests/broker-engine/hostgroups.robot +++ b/centreon-tests/broker-engine/hostgroups.robot @@ -46,35 +46,3 @@ EBNHG1 Stop Engine Stop Broker -EBNHGU1 - [Documentation] New host group with several pollers and connections to DB with broker configured with unified_sql - [Tags] Broker Engine New host group unified_sql - Config Engine ${3} - Config Broker rrd - Config Broker central - Config Broker module - - Broker Config Log central sql info - Config Broker Sql Output central unified_sql - Broker Config Output Set central central-broker-unified-sql connections_count 5 - ${start}= Get Current Date - Start Broker - Start Engine - ${result}= Check Connections - Should Be True ${result} msg=Engine and Broker not connected - Add Host Group ${0} ["host_1", "host_2", "host_3"] - - Reload Broker - Reload Engine - - ${result}= Check Connections - Should Be True ${result} msg=Engine and Broker not connected - - ${content}= Create List enabling membership of host 3 to host group 1 on instance 1 enabling membership of host 2 to host group 1 on instance 1 enabling membership of host 1 to host group 1 on instance 1 - - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log - ${result}= Find In Log With Timeout ${log} ${start} ${content} 45 - Should Be True ${result} msg=One of the new host groups not found in logs. - Stop Engine - Stop Broker - diff --git a/centreon-tests/broker-engine/retention-duplicates.robot b/centreon-tests/broker-engine/retention-duplicates.robot index dd371e58b3d..a51efe9b733 100644 --- a/centreon-tests/broker-engine/retention-duplicates.robot +++ b/centreon-tests/broker-engine/retention-duplicates.robot @@ -1,7 +1,7 @@ *** Settings *** Resource ../resources/resources.robot Suite Setup Clean Before Suite -Suite Teardown Clean After Suite +Suite Teardown Clean After Suite Test Setup Stop Processes Documentation Centreon Broker tests on dublicated data that could come from retention when centengine or cbd are restarted @@ -19,207 +19,34 @@ BERD1 [Tags] Broker Engine start-stop duplicate retention Config Engine ${1} Config Broker central - Broker Config Clear Outputs Except central ["ipv4"] - Broker Config Add Lua Output central test-doubles ${SCRIPTS}test-doubles-c.lua + Broker Config Clear Outputs Except central ["ipv4"] + Broker Config Add Lua Output central test-doubles ${SCRIPTS}test-doubles-c.lua Broker Config Log central lua debug Config Broker module - Broker Config Add Lua Output module test-doubles ${SCRIPTS}test-doubles.lua + Broker Config Add Lua Output module test-doubles ${SCRIPTS}test-doubles.lua Broker Config Log module lua debug Config Broker rrd - Clear Retention + Clear Retention ${start}= Get Current Date Start Broker Start Engine ${content}= Create List lua: starting internal thread. + ${logCbd}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log + ${logModule}= Catenate SEPARATOR= ${BROKER_LOG} /central-module-master.log ${result}= Find In Log with timeout ${logCbd} ${start} ${content} 30 Should Be True ${result} msg=Lua not started in cbd ${result}= Find In Log with timeout ${logModule} ${start} ${content} 30 Should Be True ${result} msg=Lua not started in centengine ${result}= Check Connections Should Be True ${result} msg=Engine and Broker not connected. - Sleep 5s + Sleep 5s Stop Broker - Sleep 5s - Clear Cache - Start Broker - Sleep 25s - Stop Engine - Stop Broker - ${result}= Files Contains Same Md5 /tmp/lua-engine.log /tmp/lua.log - Should Be True ${result} msg=Contents of /tmp/lua.log and /tmp/lua-engine.log do not match. - ${result}= Check Multiplicity When Broker Restarted /tmp/lua-engine.log /tmp/lua.log - Should Be True ${result} msg=There are events sent several times, see /tmp/lua-engine.log and /tmp/lua.log - -BERD2 - [Documentation] Starting/stopping Engine does not create duplicated events. - [Tags] Broker Engine start-stop duplicate retention - Config Engine ${1} - Config Broker central - Broker Config Clear Outputs Except central ["ipv4"] - Broker Config Add Lua Output central test-doubles ${SCRIPTS}test-doubles-c.lua - Broker Config Log central lua debug - Config Broker module - Broker Config Add Lua Output module test-doubles ${SCRIPTS}test-doubles.lua - Broker Config Log module lua debug - Config Broker rrd - Clear Retention - ${start}= Get Current Date - Start Broker - Start Engine - ${content}= Create List lua: starting internal thread. - ${result}= Find In Log with timeout ${logCbd} ${start} ${content} 30 - Should Be True ${result} msg=Lua not started in cbd - ${result}= Find In Log with timeout ${logModule} ${start} ${content} 30 - Should Be True ${result} msg=Lua not started in centengine - ${result}= Check Connections - Should Be True ${result} msg=Engine and Broker not connected. - Sleep 5s - Stop Engine - Sleep 5s - Clear Cache - Start Engine - Sleep 25s - Stop Engine - Stop Broker - ${result}= Files Contains Same Md5 /tmp/lua-engine.log /tmp/lua.log - Should Be True ${result} msg=Contents of /tmp/lua.log and /tmp/lua-engine.log do not match. - ${result}= Check Multiplicity When Engine Restarted /tmp/lua-engine.log /tmp/lua.log - Should Be True ${result} msg=There are events sent several times, see /tmp/lua-engine.log and /tmp/lua.log - -BERDUC1 - [Documentation] Starting/stopping Broker does not create duplicated events in usual cases - [Tags] Broker Engine start-stop duplicate retention - Config Engine ${1} - Config Broker central - Broker Config Add Lua Output central test-doubles ${SCRIPTS}test-doubles-c.lua - Broker Config Log central lua debug - Config Broker module - Broker Config Add Lua Output module test-doubles ${SCRIPTS}test-doubles.lua - Broker Config Log module lua debug - Config Broker rrd - Clear Retention - ${start}= Get Current Date - Start Broker - Start Engine - ${content}= Create List lua: starting internal thread. - ${result}= Find In Log with timeout ${logCbd} ${start} ${content} 30 - Should Be True ${result} msg=Lua not started in cbd - ${result}= Find In Log with timeout ${logModule} ${start} ${content} 30 - Should Be True ${result} msg=Lua not started in centengine - ${result}= Check Connections - Should Be True ${result} msg=Engine and Broker not connected. - Sleep 5s - Stop Broker - Sleep 5s - Clear Cache - Start Broker - Sleep 25s - Stop Engine - Stop Broker - ${result}= Check Multiplicity When Broker Restarted /tmp/lua-engine.log /tmp/lua.log - Should Be True ${result} msg=There are events sent several times, see /tmp/lua-engine.log and /tmp/lua.log - -BERDUCU1 - [Documentation] Starting/stopping Broker does not create duplicated events in usual cases with unified_sql - [Tags] Broker Engine start-stop duplicate retention - Config Engine ${1} - Config Broker central - Broker Config Add Lua Output central test-doubles ${SCRIPTS}test-doubles-c.lua - Broker Config Log central lua debug - Config Broker Sql Output central unified_sql - Config Broker module - Broker Config Add Lua Output module test-doubles ${SCRIPTS}test-doubles.lua - Broker Config Log module lua debug - Config Broker rrd - Clear Retention - ${start}= Get Current Date - Start Broker - Start Engine - ${content}= Create List lua: starting internal thread. - ${result}= Find In Log with timeout ${logCbd} ${start} ${content} 30 - Should Be True ${result} msg=Lua not started in cbd - ${result}= Find In Log with timeout ${logModule} ${start} ${content} 30 - Should Be True ${result} msg=Lua not started in centengine - ${result}= Check Connections - Should Be True ${result} msg=Engine and Broker not connected. - Sleep 5s - Stop Broker - Sleep 5s - Clear Cache - Start Broker - Sleep 25s - Stop Engine - Stop Broker - ${result}= Check Multiplicity When Broker Restarted /tmp/lua-engine.log /tmp/lua.log - Should Be True ${result} msg=There are events sent several times, see /tmp/lua-engine.log and /tmp/lua.log - -BERDUC2 - [Documentation] Starting/stopping Engine does not create duplicated events in usual cases - [Tags] Broker Engine start-stop duplicate retention - Clear Retention - Config Engine ${1} - Config Broker central - Broker Config Add Lua Output central test-doubles ${SCRIPTS}test-doubles-c.lua - Broker Config Log central lua debug - Config Broker module - Broker Config Add Lua Output module test-doubles ${SCRIPTS}test-doubles.lua - Broker Config Log module lua debug - Config Broker rrd - ${start}= Get Current Date - Start Broker - Start Engine - ${content}= Create List lua: starting internal thread. - ${result}= Find In Log with timeout ${logCbd} ${start} ${content} 30 - Should Be True ${result} msg=Lua not started in cbd - ${result}= Find In Log with timeout ${logModule} ${start} ${content} 30 - Should Be True ${result} msg=Lua not started in centengine - ${result}= Check Connections - Should Be True ${result} msg=Engine and Broker not connected. - Sleep 5s - Stop Engine - Sleep 5s - Clear Cache - Start Engine - Sleep 25s - Stop Engine - Stop Broker - ${result}= Check Multiplicity When Engine Restarted /tmp/lua-engine.log /tmp/lua.log - Should Be True ${result} msg=There are events sent several times, see /tmp/lua-engine.log and /tmp/lua.log - -BERDUCU2 - [Documentation] Starting/stopping Engine does not create duplicated events in usual cases with unified_sql - [Tags] Broker Engine start-stop duplicate retention - Clear Retention - Config Engine ${1} - Config Broker central - Config Broker Sql Output central unified_sql - Broker Config Add Lua Output central test-doubles ${SCRIPTS}test-doubles-c.lua - Broker Config Log central lua debug - Config Broker module - Broker Config Add Lua Output module test-doubles ${SCRIPTS}test-doubles.lua - Broker Config Log module lua debug - Config Broker rrd - ${start}= Get Current Date - Start Broker - Start Engine - ${content}= Create List lua: starting internal thread. - ${result}= Find In Log with timeout ${logCbd} ${start} ${content} 30 - Should Be True ${result} msg=Lua not started in cbd - ${result}= Find In Log with timeout ${logModule} ${start} ${content} 30 - Should Be True ${result} msg=Lua not started in centengine - ${result}= Check Connections - Should Be True ${result} msg=Engine and Broker not connected. - Sleep 5s + Sleep 5s + Clear Cache + Start Broker + Sleep 25s Stop Engine - Sleep 5s - Clear Cache - Start Engine - Sleep 25s - Stop Engine - Stop Broker - ${result}= Check Multiplicity When Engine Restarted /tmp/lua-engine.log /tmp/lua.log - Should Be True ${result} msg=There are events sent several times, see /tmp/lua-engine.log and /tmp/lua.log + Stop Broker + ${result}= Compare Md5 /tmp/lua-engine.log /tmp/lua.log + Should Be True ${result} msg=Contents of /tmp/lua.log and /tmp/lua-engine.log do not match. -*** Variables *** -${logCbd} ${BROKER_LOG}/central-broker-master.log -${logModule} ${BROKER_LOG}/central-module-master.log diff --git a/centreon-tests/broker-engine/rrd.robot b/centreon-tests/broker-engine/rrd.robot index d3ad8d6d2e4..4554f3f98a5 100644 --- a/centreon-tests/broker-engine/rrd.robot +++ b/centreon-tests/broker-engine/rrd.robot @@ -5,7 +5,7 @@ Suite Teardown Clean After Suite Test Setup Stop Processes Documentation Centreon Broker RRD metric deletion -Library DatabaseLibrary +Library DatabaseLibrary Library Process Library OperatingSystem Library DateTime @@ -16,7 +16,6 @@ Library ../resources/Common.py *** Test Cases *** BRRDDM1 - Start Mysql [Documentation] RRD metric deletion on table metric [Tags] RRD metric deletion on table metric Config Engine ${1} @@ -39,7 +38,7 @@ BRRDDM1 Execute Sql String UPDATE metrics SET to_delete=1 WHERE metric_id=${metric} Reload Broker - Sleep 6m + Sleep 6m Stop Broker Stop Engine @@ -74,7 +73,7 @@ BRRDDID1 Execute Sql String UPDATE index_data i LEFT JOIN metrics m ON i.id=m.index_id SET i.to_delete=1 WHERE m.metric_id=${metric} Reload Broker - Sleep 6m + Sleep 6m Stop Broker Stop Engine @@ -109,117 +108,7 @@ BRRDDMID1 Execute Sql String UPDATE index_data i LEFT JOIN metrics m ON i.id=m.index_id SET i.to_delete=1, m.to_delete=1 WHERE m.metric_id=${metric} Reload Broker - Sleep 6m - - Stop Broker - Stop Engine - - ${content1}= Create List remove graph request for metric ${metric} - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-rrd-master.log - ${result}= Find In Log ${log} ${start} ${content1} - Should Be True ${result} - File Should Not Exist /var/lib/centreon/metrics/${metric}.rrd - -BRRDDMU1 - [Documentation] RRD metric deletion on table metric with unified sql output - [Tags] RRD metric deletion index_data unified_sql - Config Engine ${1} - Config Broker rrd - Config Broker central - Config Broker Sql Output central unified_sql - Config Broker module - Broker Config Log rrd rrd debug - Broker Config Log rrd core error - - Log To Console start - ${start}= Get Current Date - Start Broker - Start Engine - Log To Console after start - ${result}= Check Connections - Should Be True ${result} msg=Engine and Broker not connected - Log To Console after Check - ${metric}= Get Metric To Delete - Log To Console metric to delete ${metric} - - Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} - Log To Console after connection - Execute Sql String UPDATE metrics SET to_delete=1 WHERE metric_id=${metric} - - Reload Broker - Sleep 6m - - Stop Broker - Stop Engine - - ${content1}= Create List remove graph request for metric ${metric} - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-rrd-master.log - ${result}= Find In Log ${log} ${start} ${content1} - Should Be True ${result} - File Should Not Exist /var/lib/centreon/metrics/${metric}.rrd - -BRRDDIDU1 - [Documentation] RRD metric deletion on table index_data with unified sql output - [Tags] RRD metric deletion index_data unified_sql - Config Engine ${1} - Config Broker rrd - Config Broker central - Config Broker Sql Output central unified_sql - Config Broker module - Broker Config Log rrd rrd debug - Broker Config Log rrd core error - - ${start}= Get Current Date - Start Broker - Start Engine - ${result}= Check Connections - Should Be True ${result} msg=Engine and Broker not connected - - ${metric}= Get Metric To Delete - Log To Console metric to delete ${metric} - - Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} - Log To Console after connection - Execute Sql String UPDATE index_data i LEFT JOIN metrics m ON i.id=m.index_id SET i.to_delete=1 WHERE m.metric_id=${metric} - - Reload Broker - Sleep 6m - - Stop Broker - Stop Engine - - ${content1}= Create List remove graph request for metric ${metric} - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-rrd-master.log - ${result}= Find In Log ${log} ${start} ${content1} - Should Be True ${result} - File Should Not Exist /var/lib/centreon/metrics/${metric}.rrd - -BRRDDMIDU1 - [Documentation] RRD metric deletion on table metric and index_data with unified sql output - [Tags] RRD metric deletion metric index_data unified_sql - Config Engine ${1} - Config Broker rrd - Config Broker central - Config Broker Sql Output central unified_sql - Config Broker module - Broker Config Log rrd rrd debug - Broker Config Log rrd core error - - ${start}= Get Current Date - Start Broker - Start Engine - ${result}= Check Connections - Should Be True ${result} msg=Engine and Broker not connected - - ${metric}= Get Metric To Delete - Log To Console metric to delete ${metric} - - Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} - Log To Console after connection - Execute Sql String UPDATE index_data i LEFT JOIN metrics m ON i.id=m.index_id SET i.to_delete=1, m.to_delete=1 WHERE m.metric_id=${metric} - - Reload Broker - Sleep 6m + Sleep 6m Stop Broker Stop Engine diff --git a/centreon-tests/broker/sql.robot b/centreon-tests/broker/sql.robot index d83a8b2ac10..7b38d7759f0 100644 --- a/centreon-tests/broker/sql.robot +++ b/centreon-tests/broker/sql.robot @@ -21,13 +21,13 @@ BDB1 Config Broker module Broker Config Output set central central-broker-master-sql db_name centreon FOR ${i} IN RANGE 0 5 - ${start}= Get Current Date - Start Broker - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log - ${content}= Create List Table 'centreon.instances' doesn't exist - ${result}= Find In Log with timeout ${log} ${start} ${content} 30 - Should Be True ${result} - Stop Broker + ${start}= Get Current Date + Start Broker + ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log + ${content}= Create List Table 'centreon.instances' doesn't exist + ${result}= Find In Log with timeout ${log} ${start} ${content} 30 + Should Be True ${result} + Stop Broker END BDB2 @@ -201,7 +201,7 @@ BEDB2 BDBM1 [Documentation] start broker/engine and then start MariaDB => connection is established [Tags] Broker sql start-stop - @{lst}= Create List 1 6 + @{lst}= Create List 1 6 FOR ${c} IN @{lst} Config Broker central Broker Config Output set central central-broker-master-sql connections_count ${c} @@ -224,119 +224,3 @@ BDBM1 Stop Engine END -BDBU1 - [Documentation] Access denied when database name exists but is not the good one for unified sql output - [Tags] Broker sql unified_sql - Config Broker central - Config Broker Sql Output central unified_sql - Config Broker rrd - Config Broker module - Broker Config Output set central central-broker-unified-sql db_name centreon - FOR ${i} IN RANGE 0 5 - ${start}= Get Current Date - Start Broker - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log - ${content}= Create List Table 'centreon.instances' doesn't exist - ${result}= Find In Log with timeout ${log} ${start} ${content} 30 - Should Be True ${result} - Stop Broker - END - -BDBU3 - [Documentation] Access denied when database name does not exist for unified sql output - [Tags] Broker sql unified_sql - Config Broker central - Config Broker Sql Output central unified_sql - Config Broker rrd - Config Broker module - Broker Config Output set central central-broker-unified-sql db_name centreon1 - FOR ${i} IN RANGE 0 5 - ${start}= Get Current Date - Start Broker - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log - ${content}= Create List global error: mysql_connection: error while starting connection - ${result}= Find In Log with timeout ${log} ${start} ${content} 30 - Should Be True ${result} - Stop Broker - END - -BDBU5 - [Documentation] cbd does not crash if the unified sql db_host is wrong - [Tags] Broker sql unified_sql - Config Broker central - Config Broker Sql Output central unified_sql - Config Broker rrd - Config Broker module - Broker Config Output set central central-broker-unified-sql db_host 1.2.3.4 - FOR ${i} IN RANGE 0 5 - ${start}= Get Current Date - Start Broker - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log - ${content}= Create List error while starting connection - ${result}= Find In Log with timeout ${log} ${start} ${content} 50 - Should Be True ${result} msg=Cannot find the message telling cbd is not connected to the database. - Stop Broker - END - -BDBU7 - [Documentation] Access denied when database user password is wrong for unified sql - [Tags] Broker sql unified_sql - Config Broker central - Config Broker Sql Output central unified_sql - Config Broker rrd - Config Broker module - Broker Config Output set central central-broker-unified-sql db_password centreon1 - ${start}= Get Current Date - Start Broker - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log - ${content}= Create List mysql_connection: error while starting connection - ${result}= Find In Log with timeout ${log} ${start} ${content} 20 - Should Be True ${result} msg=Error concerning cbd not connected to the database is missing. - Stop Broker - -BDBU10 - [Documentation] Connection should be established when user password is good for unified sql - [Tags] Broker sql unified_sql - Config Broker central - Config Broker Sql Output central unified_sql - Config Broker rrd - Config Broker module - Broker Config Log central sql debug - Broker Config Log module sql debug - ${start}= Get Current Date - Start Broker - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log - ${content}= Create List mysql_connection: commit - ${result}= Find In Log with timeout ${log} ${start} ${content} 40 - Should Be True ${result} msg=Log concerning a commit (connection ok) is missing. - Stop Broker - -BDBMU1 - [Documentation] start broker/engine with unified sql and then start MariaDB => connection is established - [Tags] Broker sql start-stop unified_sql - @{lst}= Create List 1 6 - FOR ${c} IN @{lst} - Config Broker central - Config Broker Sql Output central unified_sql - Broker Config Output set central central-broker-unified-sql connections_count ${c} - Broker Config Output set central central-broker-unified-sql retry_interval 5 - Config Broker rrd - Config Broker module - Config Engine ${1} - ${start}= Get Current Date - Stop Mysql - Start Broker - Start Engine - ${log}= Catenate SEPARATOR= ${BROKER_LOG} /central-broker-master.log - ${content}= Create List mysql_connection: error while starting connection - ${result}= Find In Log with timeout ${log} ${start} ${content} 20 - Should Be True ${result} msg=Broker does not see any issue with the db while it is switched off - Start Mysql - ${result}= Check Broker Stats exist central mysql manager waiting tasks in connection 0 80 - Should Be True ${result} msg=No stats on mysql manager found - ${result}= Get Broker Stats size central mysql manager ${60} - Should Be True ${result} >= ${c} + 1 msg=Broker mysql manager stats do not show the ${c} connections - Stop Broker - Stop Engine - END - diff --git a/centreon-tests/broker/start-stop.robot b/centreon-tests/broker/start-stop.robot index ef2cea609d5..5efa572bdd6 100644 --- a/centreon-tests/broker/start-stop.robot +++ b/centreon-tests/broker/start-stop.robot @@ -44,44 +44,6 @@ BSS5 Broker Config Output Remove central centreon-broker-master-rrd host Repeat Keyword 5 times Start Stop Instance 1s -BSSU1 - [Documentation] Start-Stop with unified_sql two instances of broker and no coredump - [Tags] Broker start-stop unified_sql - Config Broker central - Config Broker rrd - Config Broker Sql Output central unified_sql - Repeat Keyword 5 times Start Stop Service 0 - -BSSU2 - [Documentation] Start/Stop with unified_sql 10 times broker with 300ms interval and no coredump - [Tags] Broker start-stop unified_sql - Config Broker central - Config Broker Sql Output central unified_sql - Repeat Keyword 10 times Start Stop Instance 300ms - -BSSU3 - [Documentation] Start-Stop with unified_sql one instance of broker and no coredump - [Tags] Broker start-stop unified_sql - Config Broker central - Config Broker Sql Output central unified_sql - Repeat Keyword 5 times Start Stop Instance 0 - -BSSU4 - [Documentation] Start/Stop with unified_sql 10 times broker with 1sec interval and no coredump - [Tags] Broker start-stop unified_sql - Config Broker central - Config Broker Sql Output central unified_sql - Repeat Keyword 10 times Start Stop Instance 1s - -BSSU5 - [Documentation] Start-Stop with unified_sql with reversed connection on TCP acceptor with only one instance and no deadlock - [Tags] Broker start-stop unified_sql - Config Broker central - Config Broker Sql Output central unified_sql - Broker Config Output Set central centreon-broker-master-rrd one_peer_retention_mode yes - Broker Config Output Remove central centreon-broker-master-rrd host - Repeat Keyword 5 times Start Stop Instance 1s - *** Keywords *** Start Stop Service [Arguments] ${interval} diff --git a/centreon-tests/resources/BrokerDatabase.py b/centreon-tests/resources/BrokerDatabase.py new file mode 100644 index 00000000000..ce951411ace --- /dev/null +++ b/centreon-tests/resources/BrokerDatabase.py @@ -0,0 +1,23 @@ +from robot.libraries.BuiltIn import BuiltIn +from Common import find_in_log +import time + +def do_when_catch_in_log(log: str, date, content, func, arg): + start = time.time() + while True: + time.sleep(1) + if time.time() - start >= 5 * 60: + break + if find_in_log(log, date, content): + return BuiltIn().run_keyword(func, arg) + return False + +def catch_in_log(log: str, date, content): + start = time.time() + while True: + time.sleep(1) + if time.time() - start >= 5 * 60: + break + if find_in_log(log, date, content): + return True + return False \ No newline at end of file diff --git a/centreon-tests/resources/Common.py b/centreon-tests/resources/Common.py index d6dd7787c7f..eaea588d7d8 100644 --- a/centreon-tests/resources/Common.py +++ b/centreon-tests/resources/Common.py @@ -42,7 +42,7 @@ def get_date(d: str): def find_in_log_with_timeout(log: str, date, content, timeout: int): - limit = time.time() + timeout + limit = time.time() + TIMEOUT while time.time() < limit: if find_in_log(log, date, content): return True @@ -118,12 +118,12 @@ def stop_mysql(): def kill_broker(): - getoutput("kill -SIGKILL $(ps aux | grep '/usr/sbin/cbwd' | grep -v grep | awk '{print $2}')") - getoutput("kill -SIGKILL $(ps aux | grep '/usr/sbin/cbd' | grep -v grep | awk '{print $2}')") + getoutput("kill -SIGTERM $(ps aux | grep '/usr/sbin/cbwd' | grep -v grep | awk '{print $2}')") + getoutput("kill -SIGTERM $(ps aux | grep '/usr/sbin/cbd' | grep -v grep | awk '{print $2}')") def kill_engine(): - getoutput("kill -SIGKILL $(ps aux | grep '/usr/sbin/centengine' | grep -v grep | awk '{print $2}')") + getoutput("kill -SIGTERM $(ps aux | grep '/usr/sbin/centengine' | grep -v grep | awk '{print $2}')") def clear_retention(): diff --git a/centreon-tests/resources/Engine.py b/centreon-tests/resources/Engine.py index 4037cd9bda2..4c64e9eb150 100755 --- a/centreon-tests/resources/Engine.py +++ b/centreon-tests/resources/Engine.py @@ -116,7 +116,7 @@ def create_host(self): retval = { "config": "define host {{\n" "host_name host_{0}\n alias " "host_{0}\n address {1}.{2}.{3}.{4}\n check_command " - " checkh{0}\n check_period 24x7\n register 1\n " + " check\n check_period 24x7\n register 1\n " "_KEY{0} VAL{0}\n _SNMPCOMMUNITY public\n " "_SNMPVERSION 2c\n _HOST_ID {0}\n}}\n".format( hid, a, b, c, d), @@ -211,12 +211,6 @@ def build_configs(self, hosts: int, services_by_host: int, debug_level=0): f = open(config_dir + "/commands.cfg", "w") for i in range(inst * self.commands_count + 1, (inst + 1) * self.commands_count + 1): f.write(self.create_command(i)) - for i in range(self.last_host_id): - f.write("""define command {{ - command_name checkh{1} - command_line {0}/check.pl 0 {1} -}} -""".format(ENGINE_HOME, i + 1)) f.write("""define command {{ command_name notif command_line {0}/notif.pl @@ -225,6 +219,10 @@ def build_configs(self, hosts: int, services_by_host: int, debug_level=0): command_name test-notif command_line {0}/notif.pl }} +define command {{ + command_name check + command_line {0}/check.pl 0 +}} """.format(ENGINE_HOME)) f.close() f = open(config_dir + "/connectors.cfg", "w") diff --git a/centreon-tests/resources/resources.robot b/centreon-tests/resources/resources.robot index e9c9dbf8509..56e0f4f0e3c 100644 --- a/centreon-tests/resources/resources.robot +++ b/centreon-tests/resources/resources.robot @@ -32,9 +32,9 @@ Reload Broker Send Signal To Process SIGHUP b2 Stop Broker - ${result}= Terminate Process b1 kill=False + ${result}= Terminate Process b1 Should Be Equal As Integers ${result.rc} 0 - ${result}= Terminate Process b2 kill=False + ${result}= Terminate Process b2 Should Be Equal As Integers ${result.rc} 0 Stop Processes @@ -84,7 +84,7 @@ Check Connections [Return] ${retval} Disable Eth Connection On Port - [Arguments] ${port} + [Arguments] ${port} RUN iptables -A INPUT -p tcp --dport ${port} -j DROP RUN iptables -A OUTPUT -p tcp --dport ${port} -j DROP RUN iptables -A FORWARD -p tcp --dport ${port} -j DROP diff --git a/centreon-tests/resources/specific-duplication.py b/centreon-tests/resources/specific-duplication.py index 55ff6f28612..47b879c528f 100644 --- a/centreon-tests/resources/specific-duplication.py +++ b/centreon-tests/resources/specific-duplication.py @@ -1,23 +1,15 @@ from robot.api import logger from subprocess import getoutput import re -import json import time from dateutil import parser from datetime import datetime -## -# @brief Given two files with md5 as rows, this function checks the first list -# contains the same md5 as the second list. There are exceptions in these files -# that's why we need a function to make this test. -# -# @param str The first file name -# @param str The second file name -# -# @return A boolean True on success -def files_contains_same_md5(file_e: str, file_b: str): +def compare_md5(file_e: str, file_b: str): + logger.console("file1 = " + file_e) + logger.console("file2 = " + file_b) getoutput("awk '{{print $8}}' {0} > {0}.md5".format(file_e)) getoutput("awk '{{print $8}}' {0} > {0}.md5".format(file_b)) @@ -46,86 +38,10 @@ def files_contains_same_md5(file_e: str, file_b: str): idx2 += 1 else: return False - return idx1 == len(content1) and idx2 == len(content2) + if idx1 == len(content1) and idx2 == len(content2): + return True + return False -## -# @brief Given two files generated by a stream connector, this function checks -# that no events except special ones are sent / replayed twice. -# -# @param str The first file name -# @param str The second file name -# -# @return A boolean True on success -def check_multiplicity_when_broker_restarted(file1: str, file2: str): - f1 = open(file1) - content1 = f1.readlines() - f2 = open(file2) - content2 = f2.readlines() - - r = re.compile(r".* INFO: ([0-9]+)\s+([0-9a-f]+)\s(.*)$") - - def create_md5_list(content): - lst = dict() - for l in content: - m = r.match(l) - if m: - type, md5, js = int(m.group(1)), m.group(2), m.group(3) - if type != 65544 and type != 4294901762 and type != 196613: - if md5 in lst: - lst[md5] += 1 - else: - lst[md5] = 1 - return lst - - lst1 = create_md5_list(content1) - lst2 = create_md5_list(content2) - - res1 = set(lst1.values()) - res2 = set(lst2.values()) - if len(res1) > 1: - logger.console("Engine sends duplicates") - if len(res2) > 1: - logger.console("Broker sends duplicates") - return len(res1) == 1 and len(res2) == 1 - -## -# @brief Given two files generated by a stream connector, this function checks -# that no events except special ones are sent / replayed twice. -# -# @param str The first file name -# @param str The second file name -# -# @return A boolean True on success -def check_multiplicity_when_engine_restarted(file1: str, file2: str): - f1 = open(file1) - content1 = f1.readlines() - f2 = open(file2) - content2 = f2.readlines() - - r = re.compile(r".* INFO: ([0-9]+)\s+([0-9a-f]+)\s(.*)$") - - def create_md5_list(content): - lst = dict() - for l in content: - m = r.match(l) - if m: - type, md5, js = int(m.group(1)), m.group(2), m.group(3) - """ - Are removed: - * instance configurations - * modules - * host checks (they can be done several times - """ - if type != 65544 and type != 4294901762 and type != 65554 and type != 65561: - if md5 in lst: - lst[md5] += 1 - else: - lst[md5] = 1 - return lst - - lst1 = create_md5_list(content1) - lst2 = create_md5_list(content2) - - res1 = set(lst1.values()) - res2 = set(lst2.values()) - return len(res1) == 1 and len(res2) == 1 +def check_multiplicity(file1: str, file2: str): + getoutput("sort {}.md5 | uniq -c > sort-e.md5".format(file1)) + getoutput("sort {}.md5 | uniq -c > sort-e.md5".format(file2)) \ No newline at end of file diff --git a/ci/debian/centreon-clib-dev.install b/ci/debian/centreon-clib-dev.install index 4fa79187fdc..120092301a2 100644 --- a/ci/debian/centreon-clib-dev.install +++ b/ci/debian/centreon-clib-dev.install @@ -1 +1 @@ -debian/tmp-centreon-collect/usr/include/centreon-clib/com/centreon/* usr/include/com/centreon +debian/tmp-centreon-collect/usr/include/com/centreon/* usr/include/com/centreon diff --git a/ci/debian/centreon-clib.install b/ci/debian/centreon-clib.install index f78a375785d..f7b2e8baf15 100644 --- a/ci/debian/centreon-clib.install +++ b/ci/debian/centreon-clib.install @@ -1 +1,2 @@ -debian/tmp-centreon-collect/usr/lib/x86_64-linux-gnu/libcentreon_clib.so usr/lib64 +debian/tmp-centreon-collect/usr/lib/libcentreon_clib.so usr/lib +debian/tmp-centreon-collect/usr/lib/pkgconfig/centreon-clib.pc usr/lib/pkgconfig diff --git a/ci/debian/centreon-connector-perl.install b/ci/debian/centreon-connector-perl.install index 11cceab2207..29dc2d5e386 100644 --- a/ci/debian/centreon-connector-perl.install +++ b/ci/debian/centreon-connector-perl.install @@ -1 +1 @@ -debian/tmp-centreon-collect/usr/lib64/centreon-connector/centreon_connector_perl usr/lib/centreon-connector +debian/tmp-centreon-collect/usr/lib64/centreon-connector/centreon_connector_perl usr/bin diff --git a/ci/debian/centreon-connector-ssh.install b/ci/debian/centreon-connector-ssh.install index 2191335946d..9b06bec5569 100644 --- a/ci/debian/centreon-connector-ssh.install +++ b/ci/debian/centreon-connector-ssh.install @@ -1 +1 @@ -debian/tmp-centreon-collect/usr/lib64/centreon-connector/centreon_connector_ssh usr/lib64/centreon-connector +debian/tmp-centreon-collect/usr/lib64/centreon-connector/centreon_connector_ssh usr/bin diff --git a/ci/debian/centreon-engine-dev.install b/ci/debian/centreon-engine-dev.install index 9b9fb023e58..479947e2b08 100644 --- a/ci/debian/centreon-engine-dev.install +++ b/ci/debian/centreon-engine-dev.install @@ -1 +1,3 @@ +debian/tmp-centreon-collect/usr/include/centreon-engine/compatibility/* usr/include/centreon-engine/compatibility debian/tmp-centreon-collect/usr/include/centreon-engine/com/centreon/engine/* usr/include/centreon-engine/com/centreon/engine +debian/tmp-centreon-collect/usr/lib64/centreon-engine/pkgconfig/centengine.pc usr/lib64/pkgconfig diff --git a/ci/debian/centreon-engine.install b/ci/debian/centreon-engine.install index 1fbc82d2aa5..f490b83267a 100644 --- a/ci/debian/centreon-engine.install +++ b/ci/debian/centreon-engine.install @@ -1,4 +1,4 @@ -debian/extra/centreon-engine/centengine.service lib/systemd/system -debian/tmp-centreon-collect/etc/centreon-engine/* etc/centreon-engine -debian/tmp-centreon-collect/usr/sbin/centengine usr/sbin -debian/tmp-centreon-collect/usr/sbin/centenginestats usr/sbin +debian/extra/centreon-engine/centengine.service lib/systemd/system +debian/tmp-centreon-collect/etc/centreon-engine/* etc/centreon-engine +debian/tmp-centreon-collect/usr/sbin/centengine usr/sbin +debian/tmp-centreon-collect/usr/sbin/centenginestats usr/sbin diff --git a/ci/debian/rules b/ci/debian/rules index 5fd62ce11db..e4e0b5c3395 100755 --- a/ci/debian/rules +++ b/ci/debian/rules @@ -11,12 +11,28 @@ override_dh_auto_configure: conan install .. -s compiler.libcxx=libstdc++11 --build=missing && \ CXXFLAGS="-Wall -Wextra" cmake \ -DCMAKE_EXPORT_COMPILE_COMMANDS=On \ + -DWITH_CENTREON_CLIB_INCLUDE_DIR=../centreon-clib/inc/ \ + -DWITH_CENTREON_CLIB_LIBRARIES=centreon-clib/libcentreon_clib.so \ -DCMAKE_BUILD_TYPE=RelWithDebInfo \ - -DCMAKE_INSTALL_PREFIX=/usr \ + -DWITH_PREFIX=/usr \ + -DWITH_PREFIX_BIN=/usr/sbin \ + -DWITH_USER_BROKER=centreon-broker \ + -DWITH_USER_ENGINE=centreon-engine \ + -DWITH_GROUP_BROKER=centreon-broker \ + -DWITH_GROUP_ENGINE=centreon-engine \ -DWITH_TESTING=0 \ + -DWITH_PREFIX_MODULES=/usr/share/centreon/lib/centreon-broker \ + -DWITH_PREFIX_CONF_BROKER=/etc/centreon-broker \ + -DWITH_PREFIX_LIB_BROKER=/usr/lib64/nagios \ + -DWITH_PREFIX_CONF_ENGINE=/etc/centreon-engine \ + -DWITH_PREFIX_LIB_ENGINE=/usr/lib64/centreon-engine \ + -DWITH_PREFIX_LIB_CLIB=/usr/lib/ \ + -DWITH_RW_DIR=/var/lib/centreon-engine/rw \ + -DWITH_VAR_DIR=/var/log/centreon-engine \ -DWITH_MODULE_SIMU=On \ -DWITH_BENCH=On \ -DWITH_CREATE_FILES=OFF \ + -DWITH_PREFIX_BINARY=/usr/lib64/centreon-connector/ \ .. override_dh_auto_build: diff --git a/ci/scripts/collect-deb-package.sh b/ci/scripts/collect-deb-package.sh index d94949da2f1..39f857942ed 100755 --- a/ci/scripts/collect-deb-package.sh +++ b/ci/scripts/collect-deb-package.sh @@ -17,20 +17,13 @@ fi # mkdir -p centreon-collect # cp -rv * centreon-collect -if [ -d centreon-collect/debian ] ; then - rm -rf centreon-collect/debian -fi -if [ -d centreon-collect/build ] ; then - rm -rf centreon-collect/build -fi -tar czpf centreon-collect-$VERSION.tar.gz centreon-collect +rm -rf centreon-collect/debian +rm -rf centreon-collect/build +tar czpvf centreon-collect-$VERSION.tar.gz centreon-collect cd centreon-collect/ -cp -rf ci/debian . +mv ci/debian . debmake -f "${AUTHOR}" -e "${AUTHOR_EMAIL}" -u "$VERSION" -r "$RELEASE" debuild-pbuilder cd ../ -if [ -d "$DISTRIB" ] ; then - rm -rf "$DISTRIB" -fi mkdir $DISTRIB -mv *.deb $DISTRIB/ +mv *.deb $DISTRIB/ \ No newline at end of file diff --git a/ci/scripts/collect-rpm-package.sh b/ci/scripts/collect-rpm-package.sh index c60d71b0fa0..4d4add86374 100755 --- a/ci/scripts/collect-rpm-package.sh +++ b/ci/scripts/collect-rpm-package.sh @@ -6,23 +6,69 @@ if [ -z "$VERSION" -o -z "$RELEASE" -o -z "$DISTRIB" ] ; then exit 1 fi -echo "########################### BUILDING COLLECT ############################" - +echo "################################################## BUILDING BROKER ##################################################" # generate rpm broker if [ ! -d /root/rpmbuild/SOURCES ] ; then mkdir -p /root/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} fi -tar czf /root/rpmbuild/SOURCES/centreon-collect-$VERSION.tar.gz \ - --exclude './build' \ - --exclude './.git' \ - --transform "s,^\.,centreon-collect-$VERSION," . +mkdir centreon-broker-$VERSION +cp -r centreon-broker/* centreon-broker-$VERSION +cp conanfile.txt centreon-broker-$VERSION +tar -czf centreon-broker-$VERSION.tar.gz centreon-broker-$VERSION cmake.sh +mv centreon-broker-$VERSION.tar.gz /root/rpmbuild/SOURCES/ +rm -rf centreon-broker-$VERSION +rpmbuild -ba centreon-broker/packaging/rpm/centreon-broker.spectemplate -D "VERSION $VERSION" -D "RELEASE $RELEASE" + + +# echo "################################################## BUILDING CLIB ##################################################" + +# generate rpm clib +mkdir centreon-clib-$VERSION +cp -r centreon-clib/* centreon-clib-$VERSION +cp conanfile.txt centreon-clib-$VERSION +tar -czf centreon-clib-$VERSION.tar.gz centreon-clib-$VERSION cmake.sh +mv centreon-clib-$VERSION.tar.gz /root/rpmbuild/SOURCES/ +rm -rf centreon-clib-$VERSION +rpmbuild -ba centreon-clib/packaging/rpm/centreon-clib.spectemplate -D "VERSION $VERSION" -D "RELEASE $RELEASE" + +# echo "################################################## INSTALL CLIB ##################################################" + +if [ "$DISTRIB" = "el7" ] ; then + rpm -i /root/rpmbuild/RPMS/x86_64/centreon-clib-$VERSION-$RELEASE.el7.x86_64.rpm + rpm -i /root/rpmbuild/RPMS/x86_64/centreon-clib-debuginfo-$VERSION-$RELEASE.el7.x86_64.rpm + rpm -i /root/rpmbuild/RPMS/x86_64/centreon-clib-devel-$VERSION-$RELEASE.el7.x86_64.rpm +else + rpm -i /root/rpmbuild/RPMS/x86_64/centreon-clib-$VERSION-$RELEASE.el8.x86_64.rpm + rpm -i /root/rpmbuild/RPMS/x86_64/centreon-clib-debuginfo-$VERSION-$RELEASE.el8.x86_64.rpm + rpm -i /root/rpmbuild/RPMS/x86_64/centreon-clib-devel-$VERSION-$RELEASE.el8.x86_64.rpm +fi + +# echo "################################################## BUILDING ENGINE ##################################################" + +# generate rpm engine +mkdir centreon-engine-$VERSION +cp -r centreon-engine/* centreon-engine-$VERSION +cp conanfile.txt centreon-engine-$VERSION +tar -czf centreon-engine-$VERSION.tar.gz centreon-engine-$VERSION cmake.sh +mv centreon-engine-$VERSION.tar.gz /root/rpmbuild/SOURCES/ +rm -rf centreon-engine-$VERSION + +cp centreon-engine/packaging/rpm/centreonengine_integrate_centreon_engine2centreon.sh /root/rpmbuild/SOURCES/ +rpmbuild -ba centreon-engine/packaging/rpm/centreon-engine.spectemplate -D "VERSION $VERSION" -D "RELEASE $RELEASE" + -cp packaging/rpm/centreonengine_integrate_centreon_engine2centreon.sh /root/rpmbuild/SOURCES/ +# echo "################################################## BUILDING CONNECTOR ##################################################" -echo -e "%_topdir %(echo $HOME)/rpmbuild\n%_smp_mflags -j9\n" > $HOME/rpmbuild/.rpmmacros +# generate rpm connector +mkdir centreon-connector-$VERSION +cp -r centreon-connector/* centreon-connector-$VERSION +cp conanfile.txt centreon-connector-$VERSION +tar -czf centreon-connector-$VERSION.tar.gz centreon-connector-$VERSION cmake.sh +mv centreon-connector-$VERSION.tar.gz /root/rpmbuild/SOURCES/ +rm -rf centreon-connector-$VERSION -rpmbuild -ba packaging/rpm/centreon-collect.spec -D "VERSION $VERSION" -D "RELEASE $RELEASE" +rpmbuild -ba centreon-connector/packaging/rpm/centreon-connector.spectemplate -D "VERSION $VERSION" -D "RELEASE $RELEASE" # cleaning and according permissions to slave to delivery rpms rm -rf *.rpm diff --git a/ci/scripts/collect-sources-delivery.sh b/ci/scripts/collect-sources-delivery.sh index 47d0f2827d8..c34453dc889 100755 --- a/ci/scripts/collect-sources-delivery.sh +++ b/ci/scripts/collect-sources-delivery.sh @@ -46,4 +46,4 @@ RELEASE=$RELEASE COMMIT=$COMMIT COMMITTER=$COMMITTER MAJOR=$MAJOR -EOF +EOF \ No newline at end of file diff --git a/ci/scripts/collect-unit-tests.sh b/ci/scripts/collect-unit-tests.sh index fec67aa2b53..ef142c37aac 100755 --- a/ci/scripts/collect-unit-tests.sh +++ b/ci/scripts/collect-unit-tests.sh @@ -17,7 +17,7 @@ else fi #Build -make -j9 +make -j9 make -j9 install #Test diff --git a/cmake.sh b/cmake.sh index fd231770018..8246814577a 100755 --- a/cmake.sh +++ b/cmake.sh @@ -88,6 +88,18 @@ if [ -r /etc/centos-release ] ; then source /opt/rh/devtoolset-9/enable fi + if [ $maj = "centos7" ] ; then + curl https://downloads.mariadb.com/MariaDB/mariadb-10.5.8/yum/centos7-amd64/rpms/MariaDB-shared-10.5.8-1.el7.centos.x86_64.rpm --output MariaDB-shared-10.5.8-1.el7.centos.x86_64.rpm + curl https://downloads.mariadb.com/MariaDB/mariadb-10.5.8/yum/centos7-amd64/rpms/MariaDB-common-10.5.8-1.el7.centos.x86_64.rpm --output MariaDB-common-10.5.8-1.el7.centos.x86_64.rpm + curl https://downloads.mariadb.com/MariaDB/mariadb-10.5.8/yum/centos7-amd64/rpms/MariaDB-compat-10.5.8-1.el7.centos.x86_64.rpm --output MariaDB-compat-10.5.8-1.el7.centos.x86_64.rpm + yum install -y MariaDB*.rpm + else + curl https://downloads.mariadb.com/MariaDB/mariadb-10.5.8/yum/centos8-amd64/rpms/MariaDB-shared-10.5.8-1.el8.x86_64.rpm --output MariaDB-shared-10.5.8-1.el8.x86_64.rpm + curl https://downloads.mariadb.com/MariaDB/mariadb-10.5.8/yum/centos8-amd64/rpms/MariaDB-common-10.5.8-1.el8.x86_64.rpm --output MariaDB-common-10.5.8-1.el8.x86_64.rpm + curl https://downloads.mariadb.com/MariaDB/mariadb-10.5.8/yum/centos8-amd64/rpms/MariaDB-compat-10.5.8-1.el8.x86_64.rpm --output MariaDB-compat-10.5.8-1.el8.x86_64.rpm + dnf install -y MariaDB-*.rpm + fi + pkgs=( ninja-build rrdtool-devel @@ -249,9 +261,9 @@ else fi if [ $maj = "Raspbian" ] ; then - CXXFLAGS="-Wall -Wextra" $cmake -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DWITH_TESTING=On -DWITH_MODULE_SIMU=On -DWITH_BENCH=On -DWITH_CREATE_FILES=OFF $* .. + CXXFLAGS="-Wall -Wextra" $cmake -DWITH_CENTREON_CLIB_INCLUDE_DIR=../centreon-clib/inc/ -DWITH_CENTREON_CLIB_LIBRARIES=centreon-clib/libcentreon_clib.so -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DWITH_PREFIX=/usr -DWITH_PREFIX_BIN=/usr/sbin -DWITH_USER_BROKER=centreon-broker -DWITH_USER_ENGINE=centreon-engine -DWITH_GROUP_BROKER=centreon-broker -DWITH_GROUP_ENGINE=centreon-engine -DWITH_TESTING=On -DWITH_PREFIX_MODULES=/usr/share/centreon/lib/centreon-broker -DWITH_PREFIX_CONF_BROKER=/etc/centreon-broker -DWITH_PREFIX_LIB_BROKER=/usr/lib64/nagios -DWITH_PREFIX_CONF_ENGINE=/etc/centreon-engine -DWITH_PREFIX_LIB_ENGINE=/usr/lib64/centreon-engine -DWITH_PREFIX_LIB_CLIB=/usr/lib/ -DWITH_RW_DIR=/var/lib/centreon-engine/rw -DWITH_VAR_DIR=/var/log/centreon-engine -DWITH_MODULE_SIMU=On -DWITH_BENCH=On -DWITH_CREATE_FILES=OFF -DWITH_PREFIX_BINARY=/usr/lib64/centreon-connector/ $* .. elif [ $maj = "Debian" ] ; then - CXXFLAGS="-Wall -Wextra" $cmake -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DWITH_USER_BROKER=centreon-broker -DWITH_USER_ENGINE=centreon-engine -DWITH_GROUP_BROKER=centreon-broker -DWITH_GROUP_ENGINE=centreon-engine -DWITH_TESTING=On -DWITH_PREFIX_LIB_CLIB=/usr/lib64/ -DWITH_MODULE_SIMU=On -DWITH_BENCH=On -DWITH_CREATE_FILES=OFF $* .. + CXXFLAGS="-Wall -Wextra" $cmake -DWITH_CENTREON_CLIB_INCLUDE_DIR=../centreon-clib/inc/ -DWITH_CENTREON_CLIB_LIBRARIES=centreon-clib/libcentreon_clib.so -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DWITH_PREFIX=/usr -DWITH_PREFIX_BIN=/usr/sbin -DWITH_USER_BROKER=centreon-broker -DWITH_USER_ENGINE=centreon-engine -DWITH_GROUP_BROKER=centreon-broker -DWITH_GROUP_ENGINE=centreon-engine -DWITH_TESTING=On -DWITH_PREFIX_MODULES=/usr/share/centreon/lib/centreon-broker -DWITH_PREFIX_CONF_BROKER=/etc/centreon-broker -DWITH_PREFIX_LIB_BROKER=/usr/lib64/nagios -DWITH_PREFIX_CONF_ENGINE=/etc/centreon-engine -DWITH_PREFIX_LIB_ENGINE=/usr/lib64/centreon-engine -DWITH_PREFIX_LIB_CLIB=/usr/lib64/ -DWITH_RW_DIR=/var/lib/centreon-engine/rw -DWITH_VAR_DIR=/var/log/centreon-engine -DWITH_MODULE_SIMU=On -DWITH_BENCH=On -DWITH_CREATE_FILES=OFF -DWITH_PREFIX_BINARY=/usr/lib64/centreon-connector/ $* .. else - CXXFLAGS="-Wall -Wextra" $cmake -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DWITH_USER_BROKER=centreon-broker -DWITH_USER_ENGINE=centreon-engine -DWITH_GROUP_BROKER=centreon-broker -DWITH_GROUP_ENGINE=centreon-engine -DWITH_TESTING=On -DWITH_PREFIX_LIB_CLIB=/usr/lib64/ -DWITH_MODULE_SIMU=On -DWITH_BENCH=On -DWITH_CREATE_FILES=OFF $* .. -fi + CXXFLAGS="-Wall -Wextra" $cmake -DWITH_CENTREON_CLIB_INCLUDE_DIR=../centreon-clib/inc/ -DWITH_CENTREON_CLIB_LIBRARIES=centreon-clib/libcentreon_clib.so -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DWITH_PREFIX=/usr -DWITH_PREFIX_BIN=/usr/sbin -DWITH_USER_BROKER=centreon-broker -DWITH_USER_ENGINE=centreon-engine -DWITH_GROUP_BROKER=centreon-broker -DWITH_GROUP_ENGINE=centreon-engine -DWITH_TESTING=On -DWITH_PREFIX_MODULES=/usr/share/centreon/lib/centreon-broker -DWITH_PREFIX_CONF_BROKER=/etc/centreon-broker -DWITH_PREFIX_LIB_BROKER=/usr/lib64/nagios -DWITH_PREFIX_CONF_ENGINE=/etc/centreon-engine -DWITH_PREFIX_LIB_ENGINE=/usr/lib64/centreon-engine -DWITH_PREFIX_LIB_CLIB=/usr/lib64/ -DWITH_RW_DIR=/var/lib/centreon-engine/rw -DWITH_VAR_DIR=/var/log/centreon-engine -DWITH_MODULE_SIMU=On -DWITH_BENCH=On -DWITH_CREATE_FILES=OFF -DWITH_PREFIX_BINARY=/usr/lib64/centreon-connector/ $* .. +fi \ No newline at end of file diff --git a/new_centreon_collect.sh b/new_centreon_collect.sh new file mode 100755 index 00000000000..34bb9cae0e7 --- /dev/null +++ b/new_centreon_collect.sh @@ -0,0 +1,316 @@ +#!/bin/bash +RACINE_SOURCE="/opt" + + +# dossier racine du nouveau centreon collect +if [ ! -d $RACINE_SOURCE/centreon-collect ] ; then + mkdir $RACINE_SOURCE/centreon-collect + cd $RACINE_SOURCE/centreon-collect/ + git init +else + rm -rf $RACINE_SOURCE/centreon-collect + mkdir $RACINE_SOURCE/centreon-collect + cd $RACINE_SOURCE/centreon-collect/ + git init +fi + + + +# preparation des different repo pour le deplacement +cd $RACINE_SOURCE/centreon-broker/ +mkdir centreon-broker +git mv * -k centreon-broker/ +git rm .gitignore +git commit -m "move to collect" + +cd $RACINE_SOURCE/centreon-engine/ +mkdir centreon-engine +git mv * -k centreon-engine/ +git rm .gitignore +git rm CHANGELOG.md +git commit -m "move to collect" + +cd $RACINE_SOURCE/centreon-clib/ +mkdir centreon-clib +git mv * -k centreon-clib/ +git rm .gitignore +git rm CHANGELOG.md +git commit -m "move to collect" + +cd $RACINE_SOURCE/centreon-connectors/ +mkdir centreon-connector +git mv * -k centreon-connector/ +git rm .gitignore +# git rm CHANGELOG.md +git commit -m "move to collect" + +cd $RACINE_SOURCE/centreon-tests/ +mkdir centreon-tests +git mv * -k centreon-tests/ +git rm .gitignore +git rm CHANGELOG.md +git commit -m "move to collect" + +cd $RACINE_SOURCE/centreon-build/ +mkdir centreon-build +git mv * -k centreon-build/ +git rm .gitignore +git rm CHANGELOG.md +git commit -m "move to collect" + +# recuperation des source et historique dans centreon-collect +cd $RACINE_SOURCE/centreon-collect/ +git remote add centreon-broker $RACINE_SOURCE/centreon-broker/ +git pull centreon-broker MON-4724-Road-to-collect +git commit + +git remote add centreon-engine $RACINE_SOURCE/centreon-engine/ +git pull centreon-engine develop +git commit + +git remote add centreon-clib $RACINE_SOURCE/centreon-clib/ +git pull centreon-clib develop +git commit + +git remote add centreon-connector $RACINE_SOURCE/centreon-connectors/ +git pull centreon-connector develop +git commit + +git remote add centreon-tests $RACINE_SOURCE/centreon-tests/ +git pull centreon-tests master +git commit + +git remote add centreon-build $RACINE_SOURCE/centreon-build/ +git pull centreon-build master +git commit + +# modification des CMakeLists +sed -i 's/WITH_PREFIX_CONF/WITH_PREFIX_CONF_BROKER/' centreon-broker/CMakeLists.txt +sed -i 's/WITH_PREFIX_LIB/WITH_PREFIX_LIB_BROKER/' centreon-broker/CMakeLists.txt +sed -i 's/WITH_USER/WITH_USER_BROKER/' centreon-broker/CMakeLists.txt +sed -i 's/WITH_GROUP/WITH_GROUP_BROKER/' centreon-broker/CMakeLists.txt + +sed -i 's/WITH_PREFIX_LIB/WITH_PREFIX_LIB_CLIB/' centreon-clib/CMakeLists.txt +sed -i 's/CMAKE_SOURCE_DIR/PROJECT_SOURCE_DIR/' centreon-clib/test/CMakeLists.txt + +sed -i 's/CMAKE_SOURCE_DIR/PROJECT_SOURCE_DIR/' centreon-connector/CMakeLists.txt +sed -i 's/add_executable(ut/add_executable(ut_connector/' centreon-connector/CMakeLists.txt +sed -i 's/target_link_libraries(ut/target_link_libraries(ut_connector/' centreon-connector/CMakeLists.txt +sed -i 's/ssh)/ssh)\nlink_directories(${CMAKE_SOURCE_DIR}\/build\/centreon-clib\/)/' centreon-connector/CMakeLists.txt +sed -i 's/LIBSSH2_LIBRARIES})/LIBSSH2_LIBRARIES})\nadd_dependencies(ut_connector centreon_clib_shared)/' centreon-connector/CMakeLists.txt +sed -i 's/${CLIB_LIBRARIES}/centreon_clib/' centreon-connector/CMakeLists.txt +sed -i 's/CMAKE_SOURCE_DIR/PROJECT_SOURCE_DIR/' centreon-connector/perl/CMakeLists.txt +sed -i 's/\/perl\/inc\/)/\/perl\/inc\/)\nlink_directories(${CMAKE_SOURCE_DIR}\/build\/centreon-clib\/)/' centreon-connector/perl/CMakeLists.txt +sed -i 's/pthread)/pthread)\nadd_dependencies(centreon_connector_perl centreon_clib_shared)/' centreon-connector/perl/CMakeLists.txt +sed -i 's/${CLIB_LIBRARIES}/centreon_clib/' centreon-connector/perl/CMakeLists.txt +sed -i 's/CMAKE_SOURCE_DIR/PROJECT_SOURCE_DIR/' centreon-connector/ssh/CMakeLists.txt +sed -i 's/\/ssh\/inc)/\/ssh\/inc)\nlink_directories(${CMAKE_SOURCE_DIR}\/build\/centreon-clib\/)/' centreon-connector/ssh/CMakeLists.txt +sed -i 's/pthread)/pthread)\nadd_dependencies(centreon_connector_ssh centreon_clib_shared)/' centreon-connector/ssh/CMakeLists.txt +sed -i 's/${CLIB_LIBRARIES}/centreon_clib/' centreon-connector/ssh/CMakeLists.txt +sed -i 's/\/perl\/centreon_connector_perl/\/centreon-connector\/perl\/centreon_connector_perl/' centreon-connector/perl/test/connector.cc +sed -i 's/\/..\/perl\/test\/timeout_kill.pl/\/..\/centreon-connector\/perl\/test\/timeout_kill.pl/' centreon-connector/perl/test/connector.cc +sed -i 's/\/..\/perl\/test\/timeout_term.pl/\/..\/centreon-connector\/perl\/test\/timeout_term.pl/' centreon-connector/perl/test/connector.cc + +sed -i 's/WITH_PREFIX_CONF/WITH_PREFIX_CONF_ENGINE/' centreon-engine/CMakeLists.txt +sed -i 's/WITH_PREFIX_LIB/WITH_PREFIX_LIB_ENGINE/' centreon-engine/CMakeLists.txt +sed -i 's/WITH_USER/WITH_USER_ENGINE/' centreon-engine/CMakeLists.txt +sed -i 's/WITH_GROUP/WITH_GROUP_ENGINE/' centreon-engine/CMakeLists.txt +sed -i 's/engine_rpc)/engine_rpc)\nadd_dependencies(cce_core centreon_clib_shared)/' centreon-engine/CMakeLists.txt +sed -i 's/${CLIB_LIBRARIES}/centreon_clib/' centreon-engine/CMakeLists.txt +sed -i 's/"1")/"1")\nadd_dependencies(centengine centreon_clib_shared)/' centreon-engine/CMakeLists.txt +sed -i 's/nlohmann_json_LIB_DIRS})/nlohmann_json_LIB_DIRS})\nlink_directories(${CMAKE_SOURCE_DIR}\/build\/centreon-clib\/)/' centreon-engine/CMakeLists.txt +sed -i 's/centenginestats.cc")/centenginestats.cc")\nadd_dependencies("centenginestats" centreon_clib_shared)/' centreon-engine/CMakeLists.txt +sed -i 's/add_executable(rpc_client/add_executable(rpc_client_engine/' centreon-engine/tests/CMakeLists.txt +sed -i 's/target_link_libraries(rpc_client/target_link_libraries(rpc_client_engine/' centreon-engine/tests/CMakeLists.txt +sed -i 's/add_executable(ut/add_executable(ut_engine/' centreon-engine/tests/CMakeLists.txt +sed -i 's/COMMAND ut/COMMAND ut_engine/' centreon-engine/tests/CMakeLists.txt +sed -i 's/EXECUTABLE ut/EXECUTABLE ut_engine/' centreon-engine/tests/CMakeLists.txt +sed -i 's/DEPENDENCIES ut/DEPENDENCIES ut_engine/' centreon-engine/tests/CMakeLists.txt +sed -i 's/target_link_libraries(ut/target_link_libraries(ut_engine/' centreon-engine/tests/CMakeLists.txt +sed -i 's/paths.hh\")/paths.hh\")\nlink_directories(${CMAKE_SOURCE_DIR}\/build\/centreon-clib\/)/' centreon-engine/modules/bench/CMakeLists.txt +sed -i 's/main.cc")/main.cc")\nadd_dependencies("centengine_bench_passive" centreon_clib_shared)/' centreon-engine/modules/bench/CMakeLists.txt +sed -i 's/"${CLIB_LIBRARIES}"/centreon_clib/' centreon-engine/modules/bench/CMakeLists.txt +sed -i 's/inc")/inc")\nlink_directories(${CMAKE_SOURCE_DIR}\/build\/centreon-clib\/)/' centreon-engine/modules/external_commands/CMakeLists.txt +sed -i 's/with libraries./add_dependencies(externalcmd centreon_clib_shared)/' centreon-engine/modules/external_commands/CMakeLists.txt +sed -i 's/"${CLIB_LIBRARIES}"/centreon_clib/' centreon-engine/modules/external_commands/CMakeLists.txt +sed -i 's/PREFIX "")/PREFIX "")\nlink_directories(${CMAKE_SOURCE_DIR}\/build\/centreon-clib\/)/' centreon-engine/src/simumod/CMakeLists.txt +sed -i 's/PARENT_SCOPE)/PARENT_SCOPE)\nadd_dependencies("${SIMUMOD}" centreon_clib_shared)/' centreon-engine/src/simumod/CMakeLists.txt +sed -i 's/"${CLIB_LIBRARIES}"/centreon_clib/' centreon-engine/src/simumod/CMakeLists.txt +sed -i 's/commands")/commands")\nlink_directories(${CMAKE_SOURCE_DIR}\/build\/centreon-clib\/)/' centreon-engine/test/commands/CMakeLists.txt +sed -i 's/connector_test_run.cc")/connector_test_run.cc")\nadd_dependencies("bin_connector_test_run" centreon_clib_shared)/' centreon-engine/test/commands/CMakeLists.txt +sed -i 's/bin_test_run.cc")/bin_test_run.cc")\nadd_dependencies("bin_test_run" centreon_clib_shared)/' centreon-engine/test/commands/CMakeLists.txt +sed -i 's/${CLIB_LIBRARIES}/centreon_clib/' centreon-engine/test/commands/CMakeLists.txt +sed -i 's/tests\/rpc_client/tests\/rpc_client_engine/' centreon-engine/tests/enginerpc/enginerpc.cc + +# deplacement des fichier centreon build +# broker +mkdir -p centreon-broker/packaging/rpm +mkdir -p centreon-broker/packaging/script +mkdir -p centreon-broker/packaging/docker +mkdir -p centreon-broker/packaging/jenkins +mv centreon-build/packaging/broker/debian centreon-broker/packaging/rpm/ +mv centreon-build/packaging/broker/rpm/21.10/centreon-broker.spectemplate centreon-broker/packaging/rpm/ + + + +#engine +mkdir -p centreon-engine/packaging/rpm +mkdir -p centreon-engine/packaging/script +mkdir -p centreon-engine/packaging/docker +mkdir -p centreon-engine/packaging/jenkins +mv centreon-build/packaging/engine/21.10/centreon-engine.spectemplate centreon-engine/packaging/rpm/ +mv centreon-build/packaging/engine/debian centreon-engine/packaging/rpm/ +mv centreon-build/packaging/engine/centreonengine_integrate_centreon_engine2centreon.sh centreon-engine/packaging/rpm/ + + + +# clib +mkdir -p centreon-clib/packaging/rpm +mkdir -p centreon-clib/packaging/script +mkdir -p centreon-clib/packaging/docker +mkdir -p centreon-clib/packaging/jenkins +mv centreon-build/packaging/clib/debian centreon-clib/packaging/rpm/ +mv centreon-build/packaging/clib/centreon-clib.spectemplate centreon-clib/packaging/rpm/ + + + +# connector +mkdir -p centreon-connector/packaging/rpm +mkdir -p centreon-connector/packaging/script +mkdir -p centreon-connector/packaging/docker +mkdir -p centreon-connector/packaging/jenkins +mv centreon-build/packaging/connector/21.10/centreon-connector.spectemplate centreon-connector/packaging/rpm/centreon-connector.spectemplate + + + +# modification des fichier de packaging + +sed -i 's/DWITH_PREFIX_CONF/DWITH_PREFIX_CONF_BROKER/' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/DWITH_PREFIX_LIB/DWITH_PREFIX_LIB_BROKER/' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/DWITH_USER/DWITH_USER_BROKER/' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/DWITH_GROUP/DWITH_GROUP_BROKER/' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/@VERSION@/%{VERSION}/' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/@RELEASE@/%{RELEASE}/' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/%build/%build\npip3 install conan --upgrade/' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/libstdc++11/libstdc++11 --build=missing/' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/%if 0%{?el7}//' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/%define cmake \/usr\/bin\/cmake3//' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/%define cmake \/usr\/bin\/cmake//' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/cmake >= 2.8/cmake3 >= 3.15/' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/"-DNDEBUG -O2 -g -std=c++11" %{cmake}/"-DNDEBUG -O2 -g -std=c++11" cmake3 -j9/' centreon-broker/packaging/rpm/centreon-broker.spectemplate +sed -i 's/%{__make} %{?_smp_mflags}/%{__make} -j9 %{?_smp_mflags}/' centreon-broker/packaging/rpm/centreon-broker.spectemplate + +sed -i 's/DWITH_PREFIX_LIB/DWITH_PREFIX_LIB_CLIB/' centreon-clib/packaging/rpm/centreon-clib.spectemplate +sed -i 's/@VERSION@/%{VERSION}/' centreon-clib/packaging/rpm/centreon-clib.spectemplate +sed -i 's/@RELEASE@/%{RELEASE}/' centreon-clib/packaging/rpm/centreon-clib.spectemplate +sed -i 's/%build/%build\npip3 install conan --upgrade\ncpp11=$(gcc --version | awk "\/gcc\/ \&\& ($3+0)>5.0{print 1}")\nif [ $cpp11 -eq 1 ] ; then\n conan install . -s compiler.libcxx=libstdc++11 --build=missing\nelse\n conan install . -s compiler.libcxx=libstdc++\nfi\n/' centreon-clib/packaging/rpm/centreon-clib.spectemplate +sed -i 's/%if 0%{centos} > 7//' centreon-clib/packaging/rpm/centreon-clib.spectemplate +sed -i 's/%define cmake \/usr\/bin\/cmake3//' centreon-clib/packaging/rpm/centreon-clib.spectemplate +sed -i 's/%define cmake \/usr\/bin\/cmake//' centreon-clib/packaging/rpm/centreon-clib.spectemplate +sed -i 's/cmake >= 2.8/cmake3 >= 3.15/' centreon-clib/packaging/rpm/centreon-clib.spectemplate +sed -i 's/"-DNDEBUG -g -O2 -Wno-long-long" %{cmake}/"-DNDEBUG -g -O2 -Wno-long-long" cmake3 -j9/' centreon-clib/packaging/rpm/centreon-clib.spectemplate + + +sed -i 's/@VERSION@/%{VERSION}/' centreon-connector/packaging/rpm/centreon-connector.spectemplate +sed -i 's/@RELEASE@/%{RELEASE}/' centreon-connector/packaging/rpm/centreon-connector.spectemplate +sed -i 's/%build/%build\npip3 install conan --upgrade/' centreon-connector/packaging/rpm/centreon-connector.spectemplate +sed -i 's/libstdc++11/libstdc++11 --build=missing/' centreon-connector/packaging/rpm/centreon-connector.spectemplate +sed -i 's/%if 0%{?el7}//' centreon-connector/packaging/rpm/centreon-connector.spectemplate +sed -i 's/%define cmake \/usr\/bin\/cmake3//' centreon-connector/packaging/rpm/centreon-connector.spectemplate +sed -i 's/%define cmake \/usr\/bin\/cmake//' centreon-connector/packaging/rpm/centreon-connector.spectemplate +sed -i 's/cmake >= 2.8/cmake3 >= 3.15/' centreon-connector/packaging/rpm/centreon-connector.spectemplate +sed -i 's/"-DNDEBUG -g -O2 -std=c++11 -Wno-long-long" %{cmake}/"-DNDEBUG -g -O2 -std=c++11 -Wno-long-long" cmake3 -j9/' centreon-connector/packaging/rpm/centreon-connector.spectemplate + +sed -i 's/@VERSION@/%{VERSION}/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/@RELEASE@/%{RELEASE}/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/DWITH_GROUP/DWITH_GROUP_ENGINE/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/DWITH_PREFIX_CONF/DWITH_PREFIX_CONF_ENGINE/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/DWITH_PREFIX_LIB/DWITH_PREFIX_LIB_ENGINE/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/DWITH_USER_ENGINE/DWITH_USER_ENGINE/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/%build/%build\npip3 install conan --upgrade/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/libstdc++11/libstdc++11 --build=missing/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/%if 0%{?el7}//' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's#%define cmake \/usr\/bin\/cmake3//' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/%define cmake \/usr\/bin\/cmake//' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/cmake >= 2.8/cmake3 >= 3.15/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/"-DNDEBUG -g -O2 -Wno-long-long" %{cmake}/"-DNDEBUG -g -O2 -Wno-long-long" cmake3/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +sed -i 's/%{__make} install DESTDIR/%{__make} -j9 install DESTDIR/' centreon-engine/packaging/rpm/centreon-engine.spectemplate +# supression dossier centreon build +rm -rf centreon-build + +# copie des fichier collect +cp -r centreon-broker/collect/* . +cp centreon-broker/collect/.gitignore . +chmod 775 rpmbuild.sh +cp rpmbuild.sh centreon-broker/packaging/script/ +cp rpmbuild.sh centreon-engine/packaging/script/ +cp rpmbuild.sh centreon-clib/packaging/script/ +cp rpmbuild.sh centreon-connector/packaging/script/ +rm -rf rpmbuild.sh +sed -i 's/broker/engine/' centreon-engine/packaging/script/rpmbuild.sh +sed -i 's/broker/engine/' centreon-engine/packaging/script/rpmbuild.sh +sed -i 's/rpmbuild -ba/cp centreon-engine\/packaging\/rpm\/centreonengine_integrate_centreon_engine2centreon.sh \/root\/rpmbuild\/SOURCES\/\nrpmbuild -ba/' centreon-engine/packaging/script/rpmbuild.sh + + +sed -i 's/broker/clib/' centreon-clib/packaging/script/rpmbuild.sh +sed -i 's/broker/clib/' centreon-clib/packaging/script/rpmbuild.sh +sed -i 's/broker/connector/' centreon-connector/packaging/script/rpmbuild.sh +sed -i 's/broker/connector/' centreon-connector/packaging/script/rpmbuild.sh + +chmod 775 cmake.sh +./cmake.sh + +# clean des repo +cd $RACINE_SOURCE/centreon-broker/ +git reset --hard HEAD~1 +rm -rf centreon-broker + +cd $RACINE_SOURCE/centreon-engine/ +git reset --hard HEAD~1 +rm -rf centreon-engine + +cd $RACINE_SOURCE/centreon-clib/ +git reset --hard HEAD~1 +rm -rf centreon-clib + +cd $RACINE_SOURCE/centreon-connectors/ +git reset --hard HEAD~1 +rm -rf centreon-connector + +cd $RACINE_SOURCE/centreon-tests/ +git reset --hard HEAD~1 +rm -rf centreon-tests + +cd $RACINE_SOURCE/centreon-build/ +git reset --hard HEAD~1 +rm -rf centreon-build + +# suppression des remote +cd $RACINE_SOURCE/centreon-collect/ +git remote rm centreon-broker +git remote rm centreon-clib +git remote rm centreon-connector +git remote rm centreon-engine +git remote rm centreon-tests +git remote rm centreon-build + + + + +echo "" +echo "" +echo "" +echo "**********************************************************************************" +echo "ne surtout pas oublier d'enlever les else et endif dans les spec template" +echo "**********************************************************************************" +echo "" +#push dans centreon-collect distant +# git add -A +# git commit -m "road to collect" +# git remote add origin https://github.com/centreon/centreon-collect.git +# git checkout -b develop +# git push origin develop + + + + diff --git a/packaging/rpm/centreon-collect.spec b/packaging/rpm/centreon-collect.spec deleted file mode 100644 index cdaa3df25c2..00000000000 --- a/packaging/rpm/centreon-collect.spec +++ /dev/null @@ -1,464 +0,0 @@ -## -## Copyright 2021 Centreon -## - -Summary: Centreon collect's softwares collection -Name: centreon-collect -Version: %{VERSION} -Release: %{RELEASE}%{?dist} -License: ASL 2.0 -Source: %{name}-%{version}.tar.gz -Source1: centreonengine_integrate_centreon_engine2centreon.sh - -%define thismajor 22.04.0 -%define nextmajor 22.05.0 - -Group: Applications/Communications -URL: https://github.com/centreon/centreon-collect.git -Packager: David Boucher -Vendor: Centreon Entreprise Server (CES) Repository, http://yum.centreon.com/standard/ - -%description -Centreon Collect is a software collection containing centreon-broker, -centreon-engine, centreon-clib and centreon-connectors. - -BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root - -BuildRequires: cmake3 >= 3.15 -BuildRequires: gcc -BuildRequires: gcc-c++ -BuildRequires: gnutls-devel >= 3.3.29 -BuildRequires: libgcrypt-devel -BuildRequires: lua-devel -BuildRequires: make -BuildRequires: perl -BuildRequires: perl-ExtUtils-Embed -BuildRequires: perl-devel -BuildRequires: rrdtool-devel -BuildRequires: systemd -Requires: centreon-clib = %{version}-%{release} -Requires: centreon-broker-core = %{version}-%{release} -Requires: centreon-engine = %{version}-%{release} -Requires: centreon-connector = %{version}-%{release} - -%package -n centreon-clib -Summary: Centreon core library. -Group: Development/Libraries - -%description -n centreon-clib -Centreon Clib is a common library for all Centreon -products written in C/C++. - -%package -n centreon-clib-devel -Summary: Provide include files for Centreon Clib. -Group: Development/Libraries - -%description -n centreon-clib-devel -Centreon Clib devel provide include files to build -Centreon products written in C/C++. - - -%package -n centreon-engine -Summary: Centreon Engine monitoring core. -Group: Applications/System -Requires: centreon-engine-daemon = %{version}-%{release} -Requires: centreon-engine-extcommands = %{version}-%{release} - -%description -n centreon-engine -Centreon Engine is a monitoring engine, compatible with Nagios -configuration, designed to monitor hosts and services on your network. - - -%package -n centreon-engine-daemon -Summary: Centreon Engine Daemon is the daemon to schedule checks. -Group: Application/System -Requires: centreon-clib = %{version}-%{release} -%{?systemd_requires} - -%description -n centreon-engine-daemon -Centreon Engine is a monitoring engine that schedule checks on your -network services and hosts. - - -%package -n centreon-engine-extcommands -Summary: Centreon Engine External Commands allow to other applications to send command into the daemon. -Group: Application/System -Requires: centreon-engine-daemon = %{version}-%{release} - -%description -n centreon-engine-extcommands -Centreon Engine External Commands allow to other applications to send -command into the daemon. External applications can submit commands by -writing to the command file, which is periodically processed by the -engine daemon. - - -%package -n centreon-engine-devel -Summary: Provide include files for Centreon Engine. -Group: Application/System -Requires: centreon-clib-devel = %{version}-%{release} - -%description -n centreon-engine-devel -Centreon Engine devel provide include files to develop Centreon Engine -Modules or Centreon Engine Connector. - - -%package -n centreon-engine-bench -Summary: Centreon Engine benchmarking tools. -Group: Application/System -Requires: centreon-clib = %{version}-%{release} - -%description -n centreon-engine-bench -Some Centreon Engine benchmarking tools. - - -%package -n centreon-connector -Summary: Centreon Connector provide some tools for Centreon Engine to monitoring and management system. -Group: Application/System -Requires: centreon-connector-perl = %{version}-%{release} -Requires: centreon-connector-ssh = %{version}-%{release} - -%description -n centreon-connector -Centreon Connector provide a monitoring tools, compatible with -Centreon-Engine configuration, designed to monitor and manage system. - - -%package -n centreon-connector-perl -Summary: Centreon Connector Perl provide embedded perl for Centreon-Engine. -Group: Application/System -Requires: centreon-clib = %{version}-%{release} -Requires: perl - -%description -n centreon-connector-perl -Centreon Connector Perl provide embedded perl for Centreon Engine -a monitoring engine. - - -%package -n centreon-connector-ssh -Summary: Centreon Connector SSH provide persistante connection between checks. -Group: Application/System -Requires: centreon-clib = %{version}-%{release} -Requires: libssh2 >= 1.4 -Requires: libgcrypt - -%description -n centreon-connector-ssh -Centreon Connector SSH provide persistante connection between checks. - - -%package -n centreon-broker -Summary: Store Centreon Engine/Nagios events in a database. -Group: Applications/Communications -Requires: centreon-common >= %{thismajor} -Requires: centreon-common < %{nextmajor} -Requires: coreutils - -%description -n centreon-broker -Centreon Broker is a Centreon Engine/Nagios module that report events in -one or multiple databases. - - -%package -n centreon-broker-core -Summary: Centreon Broker's shared library. -Group: Applications/Communications -Requires: gnutls >= 3.3.29 -Requires: lua -Requires: centreon-broker = %{version}-%{release} -Requires: centreon-broker-storage = %{version}-%{release} - -%description -n centreon-broker-core -Centreon core holds Centreon Broker's default modules; - - -%package -n centreon-broker-storage -Summary: Centreon Broker's shared library for prefdata storage. -Group: Applications/Communications -Requires: centreon-broker-core = %{version}-%{release} - -%description -n centreon-broker-storage -storage holds Centreon Broker's prefdata storage. - - -%package -n centreon-broker-graphite -Summary: Write Centreon performance data to Graphite. -Group: Applications/Communications -Requires: centreon-broker-core = %{version}-%{release} - -%description -n centreon-broker-graphite -This module of Centreon Broker allows you to write performance data -generated by plugins (run themselves by Centreon Engine) to a Graphite -database. - - -%package -n centreon-broker-influxdb -Summary: Write Centreon performance data to InfluxDB. -Group: Applications/Communications -Requires: centreon-broker-core = %{version}-%{release} - -%description -n centreon-broker-influxdb -This module of Centreon Broker allows you to write performance data -generated by plugins (run themselves by Centreon Engine) to a Graphite -database. - - -%package -n centreon-broker-cbd -Summary: Centreon Broker daemon. -Group: System Environment/Daemons -Requires: centreon-broker-core = %{version}-%{release} -%{?systemd_requires} - -%description -n centreon-broker-cbd -The Centreon Broker daemon can aggregates output of multiple cbmod and store -events in a DB from a single point. - -%package -n centreon-broker-cbmod -Summary: Centreon Broker as Centreon Engine 2 module. -Group: Applications/Communications -Requires: centreon-broker-core = %{version}-%{release} -Requires: centreon-engine = %{version}-%{release} - -%description -n centreon-broker-cbmod -This module can be loaded by Centreon Engine. - - -%package -n centreon-broker-devel -Summary: Centreon Broker devel libraries. -Group: Applications/Communications - -%description -n centreon-broker-devel -Include files needed to develop a module Centreon Broker. - - -%prep -%setup -q -n %{name}-%{version} - -%build -pip3 install conan --upgrade -conan install . -s compiler.libcxx=libstdc++11 --build=missing - -cmake3 \ - -DWITH_TESTING=0 \ - -DWITH_BENCH=1 \ - -DCMAKE_INSTALL_PREFIX=/usr \ - -DWITH_ENGINE_LOGROTATE_SCRIPT=1 \ - -DWITH_STARTUP_DIR=%{_unitdir} \ - -DWITH_STARTUP_SCRIPT=systemd \ - -DWITH_USER_BROKER=centreon-broker \ - -DWITH_GROUP_BROKER=centreon-broker \ - -DWITH_DAEMONS='central-rrd;central-broker' \ - -DWITH_CONFIG_FILES=y \ - -DCMAKE_BUILD_TYPE=RelWithDebInfo \ - . -%{__make} %{?_smp_mflags} - -%install -%{__rm} -rf $RPM_BUILD_ROOT -%{__install} -d $RPM_BUILD_ROOT%{_sbindir} -%{__install} -d -m 0775 $RPM_BUILD_ROOT%{_localstatedir}/log/centreon-broker -%{__install} -d -m 0775 $RPM_BUILD_ROOT%{_localstatedir}/lib/centreon-broker -%{__install} -d -m 0775 $RPM_BUILD_ROOT%{_sysconfdir}/centreon-broker -%{__install} -d $RPM_BUILD_ROOT%{_unitdir} -%{__install} -d $RPM_BUILD_ROOT%{_sysconfdir}/logrotate.d -%{__install} -d $RPM_BUILD_ROOT%{_sysconfdir}/centreon-engine/conf.d -%{__install} -d $RPM_BUILD_ROOT%{_datadir}/doc/centreon-broker -%{__install} -d $RPM_BUILD_ROOT%{_datadir}/centreon-broker/lua -%{__install} -m 644 centreon-broker/script/centreon-broker.logrotate $RPM_BUILD_ROOT%{_sysconfdir}/logrotate.d/cbd -%{__install} -d $RPM_BUILD_ROOT%{_localstatedir}/log/centreon-engine -%{__install} -d $RPM_BUILD_ROOT%{_localstatedir}/log/centreon-engine/archives -%{__install} -d $RPM_BUILD_ROOT%{_localstatedir}/lib/centreon-engine -%{__install} -d $RPM_BUILD_ROOT%{_localstatedir}/lib/centreon-engine/rw -touch $RPM_BUILD_ROOT%{_localstatedir}/log/centreon-engine/centengine.debug -%{__install} -d $RPM_BUILD_ROOT%{_datadir}/centreon-engine/extra -%{__cp} %SOURCE1 $RPM_BUILD_ROOT%{_datadir}/centreon-engine/extra/integrate_centreon_engine2centreon.sh -%{__make} install DESTDIR="$RPM_BUILD_ROOT" - -%clean -%{__rm} -rf $RPM_BUILD_ROOT - -%pre -%{_bindir}/getent group centreon-broker &>/dev/null || %{_sbindir}/groupadd -r centreon-broker 2> /dev/null || : -%{_bindir}/getent passwd centreon-broker &>/dev/null || %{_sbindir}/useradd -m -g centreon-broker -d %{_localstatedir}/lib/centreon-broker -r centreon-broker 2> /dev/null || : -if id centreon &>/dev/null; then - %{_sbindir}/usermod -a -G centreon-broker centreon -fi -if id centreon-gorgone &>/dev/null; then - %{_sbindir}/usermod -a -G centreon-gorgone centreon-broker -fi -if id centreon-engine &>/dev/null; then - %{_sbindir}/usermod -a -G centreon-broker centreon-engine - %{_sbindir}/usermod -a -G centreon-engine centreon-broker -fi -if id nagios &>/dev/null; then - %{_sbindir}/usermod -a -G centreon-broker nagios -fi - -%pre -n centreon-engine-daemon -if ! id centreon-engine &>/dev/null; then - %{_sbindir}/useradd -d %{_localstatedir}/lib/centreon-engine -r centreon-engine &>/dev/null -fi -if id centreon-broker &>/dev/null; then - %{_sbindir}/usermod -a -G centreon-engine centreon-broker -fi -if id centreon-gorgone &>/dev/null; then - %{_sbindir}/usermod -a -G centreon-gorgone centreon-engine -fi -%define httpgroup apache -if id -g %{httpgroup} &>/dev/null; then - %{_sbindir}/usermod -a -G centreon-engine %{httpgroup} -fi -if id -g nagios &>/dev/null; then - %{_sbindir}/usermod -a -G centreon-engine nagios -fi - -%post -n centreon-engine-daemon -%systemd_post centengine.service || : - -%preun -n centreon-engine-daemon -%systemd_preun centengine.service || : - - -%post -n centreon-broker -chown -R centreon-broker:centreon-broker /var/lib/centreon-broker -chmod -R g+w /var/lib/centreon-broker -chown -R centreon-broker:centreon-broker /var/log/centreon-broker -chmod -R g+w /var/log/centreon-broker - -%post -n centreon-broker-cbd -%systemd_post cbd.service || : - -%pre -n centreon-broker-cbd -# Stop cbd daemons for compatibility -if [ -f /etc/init.d/cbd-central-broker ]; then - /etc/init.d/cbd-central-broker stop &>/dev/null || : -fi - -%preun -n centreon-broker-cbd -%systemd_preun cbd.service || : - -%files -n centreon-clib -%defattr(-,root,root,-) -%{_libdir}/libcentreon_clib.so -%doc centreon-clib/LICENSE - -%files -n centreon-clib-devel -%defattr(-,root,root,-) -%{_includedir}/centreon-clib -%doc centreon-clib/LICENSE - -%files -n centreon-engine-daemon -%defattr(-,centreon-engine,centreon-engine,-) -%attr(0664,centreon-engine,centreon-engine) %config(noreplace) %{_sysconfdir}/centreon-engine/centengine.cfg -%attr(0664,centreon-engine,centreon-engine) %config(noreplace) %{_sysconfdir}/centreon-engine/resource.cfg -%attr(0664,centreon-engine,centreon-engine) %config(noreplace) %{_sysconfdir}/centreon-engine/objects/*.cfg - -%defattr(-,root,root,-) -%config(noreplace) %{_sysconfdir}/logrotate.d/centengine -%attr(755, root, root) %{_unitdir}/centengine.service - -%{_sbindir}/centengine -%{_sbindir}/centenginestats -%attr(0775,root,root) %{_datadir}/centreon-engine/extra/integrate_centreon_engine2centreon.sh -%attr(0755,centreon-engine,centreon-engine) %{_localstatedir}/log/centreon-engine/ -%attr(0755,centreon-engine,centreon-engine) %dir %{_localstatedir}/lib/centreon-engine/ -%doc centreon-engine/license.txt - -%files -n centreon-engine-extcommands -%defattr(-,root,root,-) -%{_libdir}/centreon-engine/externalcmd.so -%attr(0775,centreon-engine,centreon-engine) %{_localstatedir}/lib/centreon-engine/rw -%doc centreon-engine/license.txt - -%files -n centreon-engine-devel -%defattr(-,root,root,-) -%{_includedir}/centreon-engine -%doc centreon-engine/license.txt - -%files -n centreon-engine-bench -%defattr(-,root,root,-) -%{_libdir}/centreon-engine/bench_passive_module.so -%{_sbindir}/centengine_bench_passive - -%files -n centreon-connector-perl -%attr(0775,root,root) %{_libdir}/centreon-connector/centreon_connector_perl - -%files -n centreon-connector-ssh -%attr(0775,root,root) %{_libdir}/centreon-connector/centreon_connector_ssh - -%files -n centreon-broker -%defattr(-,centreon-broker,centreon-broker,-) -%{_localstatedir}/log/centreon-broker -%{_localstatedir}/lib/centreon-broker -%dir %{_sysconfdir}/centreon-broker - -%files -n centreon-broker-storage -%defattr(-,root,root,-) -%{_datadir}/centreon/lib/centreon-broker/20-storage.so -%{_datadir}/centreon/lib/centreon-broker/20-unified_sql.so -%{_datadir}/centreon/lib/centreon-broker/70-rrd.so - -%files -n centreon-broker-graphite -%defattr(-,root,root,-) -%{_datadir}/centreon/lib/centreon-broker/70-graphite.so - -%files -n centreon-broker-influxdb -%defattr(-,root,root,-) -%{_datadir}/centreon/lib/centreon-broker/70-influxdb.so - -%files -n centreon-broker-cbd -%defattr(664,centreon-broker,centreon-broker,-) -%config(noreplace) %{_sysconfdir}/centreon-broker/central-broker.json -%config(noreplace) %{_sysconfdir}/centreon-broker/central-rrd.json -%config(noreplace) %{_sysconfdir}/centreon-broker/watchdog.json -%defattr(-,root,root,-) -%{_sbindir}/cbd -%{_sbindir}/cbwd -#%{_sysconfdir}/centreon-broker/central-broker.json -#%{_sysconfdir}/centreon-broker/central-rrd.json -#%{_sysconfdir}/centreon-broker/watchdog.json - -%defattr(-,root,root,-) -%{_datadir}/doc/centreon-broker/ - -%attr(755, root, root) %{_unitdir}/cbd.service - -%files -n centreon-broker-core -%defattr(-,root,root,-) -%{_datadir}/centreon/lib/centreon-broker/10-neb.so -%{_datadir}/centreon/lib/centreon-broker/15-stats.so -%{_datadir}/centreon/lib/centreon-broker/20-bam.so -%{_datadir}/centreon/lib/centreon-broker/50-tcp.so -%{_datadir}/centreon/lib/centreon-broker/60-tls.so -%{_datadir}/centreon/lib/centreon-broker/70-lua.so -%{_datadir}/centreon/lib/centreon-broker/80-sql.so -%{_sysconfdir}/logrotate.d/cbd -#%defattr(0775,centreon-broker,centreon-broker,-) -#%{_datadir}/centreon-broker -#%{_datadir}/centreon-broker/lua - -%files -n centreon-broker-cbmod -%defattr(664,centreon-broker,centreon-broker,-) -%config(noreplace) %{_sysconfdir}/centreon-broker/poller-module.json -%defattr(-,root,root,-) -%{_libdir}/nagios/cbmod.so -#%{_sysconfdir}/centreon-broker/poller-module.json - -%post -n centreon-broker-cbmod -%{_bindir}/getent passwd centreon-engine &>/dev/null && %{_sbindir}/usermod -a -G centreon-broker centreon-engine -%{_bindir}/getent group centreon-engine &>/dev/null && %{_sbindir}/usermod -a -G centreon-engine centreon-broker - -%files -n centreon-broker-devel -%defattr(-,root,root,-) -%{_prefix}/include/centreon-broker -%doc centreon-broker/LICENSE -%{_includedir}/centreon-broker - -%files -%{_exec_prefix}/lib/systemd/system/cbd.service -%{_exec_prefix}/lib/systemd/system/centengine.service -%{_localstatedir}/log/centreon-engine/centengine.debug -%{_localstatedir}/log/centreon-engine/centengine.log -%{_localstatedir}/log/centreon-engine/retention.dat -%{_localstatedir}/log/centreon-engine/status.dat - - -%changelog -* Fri Dec 3 2021 David Boucher 22.04.0-1 -- First version of this spec file. diff --git a/packaging/script/rpmbuild.sh b/packaging/script/rpmbuild.sh deleted file mode 100755 index cfa5fc4da92..00000000000 --- a/packaging/script/rpmbuild.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash - -show_help() { -cat << EOF -Usage: ${0##*/} version release - -This program build Centreon-collect -EOF -exit 2 -} - -VERSION=$1 -RELEASE=$2 - -if [ -z $VERSION ] || [ -z $RELEASE ] ; then - echo "Some or all of the parameters are empty"; - echo $VERSION; - echo $RELEASE; - show_help -fi - -# root dir of the new centreon collect -if [ ! -d /root/rpmbuild/SOURCES ] ; then - mkdir -p /root/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} -fi - -cd ../.. - -tar czf /root/rpmbuild/SOURCES/centreon-collect-$VERSION.tar.gz \ - --exclude './build' \ - --exclude './.git' \ - --transform "s,^\.,centreon-collect-$VERSION," . - -cp packaging/rpm/centreonengine_integrate_centreon_engine2centreon.sh /root/rpmbuild/SOURCES/ - -echo -e "%_topdir %(echo $HOME)/rpmbuild\n%_smp_mflags -j5\n" > $HOME/rpmbuild/.rpmmacros - -cd .. - -rpmbuild -ba centreon-collect/packaging/rpm/centreon-collect.spec -D "VERSION $VERSION" -D "RELEASE $RELEASE" -