pax_global_header00006660000000000000000000000064140715364450014523gustar00rootroot0000000000000052 comment=7525f6f31f36a17893c69b51bf8c1a1a2613e9c4 centreon-clib-21.04.2/000077500000000000000000000000001407153644500144155ustar00rootroot00000000000000centreon-clib-21.04.2/.clang-format000066400000000000000000000002121407153644500167630ustar00rootroot00000000000000# Defines the Chromium style for automatic reformatting. # http://clang.llvm.org/docs/ClangFormatStyleOptions.html BasedOnStyle: Chromium centreon-clib-21.04.2/.gitignore000066400000000000000000000000511407153644500164010ustar00rootroot00000000000000build/* inc/com/centreon/clib/version.hh centreon-clib-21.04.2/CHANGELOG.md000066400000000000000000000006221407153644500162260ustar00rootroot00000000000000# Changelog ## 21.04.2 *Libraries loading* Libraries are loaded lazily now. This allows not to check all link issues during the load. ## 21.04.1 *Compilation in C++14 with conan-center* bintray has stopped. We had to switch to the conan-center. And then our conan dependencies had to upgrade and then we had to switch to C++14. So here is the corresponding compilation. ## 21.04.0 New release. centreon-clib-21.04.2/CMakeLists.txt000066400000000000000000000204131407153644500171550ustar00rootroot00000000000000## ## 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. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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. cmake_minimum_required(VERSION 2.8) project("Centreon Clib" C CXX) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") add_definitions("-D_GLIBCXX_USE_CXX11_ABI=1") # Set directories. set(INCLUDE_DIR "${PROJECT_SOURCE_DIR}/inc") set(INC_DIR "${INCLUDE_DIR}/com/centreon") set(SRC_DIR "${PROJECT_SOURCE_DIR}/src") set(SCRIPT_DIR "${PROJECT_SOURCE_DIR}/script") # Version. set(CLIB_MAJOR 21) set(CLIB_MINOR 04) set(CLIB_PATCH 2) set(CLIB_VERSION "${CLIB_MAJOR}.${CLIB_MINOR}.${CLIB_PATCH}") # Include module to check existing libraries. include(CheckLibraryExists) # Include module CTest if necessary. if (WITH_TESTING) include(CTest) endif () # Code coverage on unit tests option(WITH_COVERAGE "Add code coverage on unit tests." OFF) if (WITH_TESTING AND WITH_COVERAGE) set(CMAKE_BUILD_TYPE "Debug") include(cmake/CodeCoverage.cmake) APPEND_COVERAGE_COMPILER_FLAGS() endif () set(CMAKE_THREAD_PREFER_PTHREAD) include(FindThreads) if (NOT CMAKE_USE_PTHREADS_INIT) message(FATAL_ERROR "Could not find pthreads library.") endif () if (CMAKE_SYSTEM_NAME STREQUAL "OpenBSD" AND CMAKE_COMPILER_IS_GNUCXX) set(LIB_THREAD "-pthread -lpthread") else () set(LIB_THREAD "${CMAKE_THREAD_LIBS_INIT}") endif () # Find real time library. if (CMAKE_SYSTEM_NAME STREQUAL "OpenBSD" OR CMAKE_SYSTEM_NAME STREQUAL "Windows") set(LIB_RT "") else () set(LIB_RT "rt") endif () check_library_exists( "${LIB_RT}" "clock_gettime" "${CMAKE_LIBRARY_PATH}" FIND_LIB_RT ) if (NOT FIND_LIB_RT) message(FATAL_ERROR "Could not find real time library.") endif () # Find dynamic linking library. if (CMAKE_SYSTEM_NAME STREQUAL "Linux") set(LIB_DL "dl") elseif (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" OR CMAKE_SYSTEM_NAME STREQUAL "NetBSD" OR CMAKE_SYSTEM_NAME STREQUAL "OpenBSD") set(LIB_DL "c") else () set(LIB_DL "") endif () check_library_exists( "${LIB_DL}" "dlopen" "${CMAKE_LIBRARY_PATH}" FIND_LIB_DL ) if (NOT FIND_LIB_DL) message(FATAL_ERROR "Could not find dynamic linking library.") 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) set(PREFIX_LIB "${WITH_PREFIX_LIB}") 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. set(UNIT_TEST "No") if (WITH_TESTING) set(UNIT_TEST "Yes") endif () set(DEB_PACKAGE "No") if (CPACK_BINARY_DEB) set(DEB_PACKAGE "Yes") endif () set(RPM_PACKAGE "No") 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) if (HAVE_SPAWN_H) add_definitions(-DHAVE_SPAWN_H) else () message(WARNING "Your plateform does not have spawn.h. Some features might " "be disabled.") endif () # Set sources. set( SOURCES "${SRC_DIR}/library.cc" "${SRC_DIR}/process_manager.cc" "${SRC_DIR}/process.cc" "${SRC_DIR}/handle_manager.cc" "${SRC_DIR}/handle_action.cc" "${SRC_DIR}/task_manager.cc" "${SRC_DIR}/timestamp.cc" ) # Set headers. set( HEADERS ${SPECIFIC_HEADERS} "${INC_DIR}/clib.hh" "${INC_DIR}/handle.hh" "${INC_DIR}/handle_action.hh" "${INC_DIR}/handle_listener.hh" "${INC_DIR}/handle_manager.hh" "${INC_DIR}/hash.hh" "${INC_DIR}/library.hh" "${INC_DIR}/namespace.hh" "${INC_DIR}/process_manager.hh" "${INC_DIR}/process.hh" "${INC_DIR}/task.hh" "${INC_DIR}/task_manager.hh" "${INC_DIR}/timestamp.hh" "${INC_DIR}/unique_array_ptr.hh" "${INC_DIR}/unordered_hash.hh" ) # Include directories. include_directories("${INCLUDE_DIR}") # Add subdirectories. add_subdirectory(src/clib) add_subdirectory(src/exceptions) add_subdirectory(src/logging) add_subdirectory(src/misc) add_subdirectory(src/io) if (WITH_TESTING) add_subdirectory(test) endif () 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 "${PREFIX_INC}" COMPONENT "development" FILES_MATCHING PATTERN "*.hh" ) # Include build package. include(cmake/package.cmake) # Print summary. message(STATUS "") message(STATUS "Configuration Summary") message(STATUS "---------------------") 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}") message(STATUS " - Version ${CMAKE_SYSTEM_VERSION}") message(STATUS " - Processor ${CMAKE_SYSTEM_PROCESSOR}") message(STATUS "") message(STATUS " Build") message(STATUS " - Compiler ${CMAKE_CXX_COMPILER} " "(${CMAKE_CXX_COMPILER_ID})") message(STATUS " - Extra compilation flags ${CMAKE_CXX_FLAGS}") message(STATUS " - Build unit tests ${UNIT_TEST}") message(STATUS "") message(STATUS " Installation") 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 "") centreon-clib-21.04.2/Jenkinsfile000066400000000000000000000057221407153644500166070ustar00rootroot00000000000000import groovy.json.JsonSlurper /* ** Variables. */ def serie = '21.04' def maintenanceBranch = "${serie}.x" if (env.BRANCH_NAME.startsWith('release-')) { env.BUILD = 'RELEASE' } else if ((env.BRANCH_NAME == 'master') || (env.BRANCH_NAME == maintenanceBranch)) { env.BUILD = 'REFERENCE' } else { env.BUILD = 'CI' } /* ** Pipeline code. */ stage('Source') { node { sh 'setup_centreon_build.sh' dir('centreon-clib') { checkout scm } sh "./centreon-build/jobs/clib/${serie}/mon-clib-source.sh" source = readProperties file: 'source.properties' env.VERSION = "${source.VERSION}" env.RELEASE = "${source.RELEASE}" publishHTML([ allowMissing: false, keepAll: true, reportDir: 'summary', reportFiles: 'index.html', reportName: 'Centreon Clib Build Artifacts', reportTitles: '' ]) withSonarQubeEnv('SonarQubeDev') { sh "./centreon-build/jobs/clib/${serie}/mon-clib-analysis.sh" } } } try { // sonarQube step to get qualityGate result stage('Quality gate') { node { sleep 120 def qualityGate = waitForQualityGate() if (qualityGate.status != 'OK') { currentBuild.result = 'FAIL' } if ((currentBuild.result ?: 'SUCCESS') != 'SUCCESS') { error("Quality gate failure: ${qualityGate.status}."); } } } stage('Package') { parallel 'centos7': { node { sh 'setup_centreon_build.sh' sh "./centreon-build/jobs/clib/${serie}/mon-clib-package.sh centos7" } }, 'centos8': { node { sh 'setup_centreon_build.sh' sh "./centreon-build/jobs/clib/${serie}/mon-clib-package.sh centos8" } }, 'debian10': { node { sh 'setup_centreon_build.sh' sh "./centreon-build/jobs/clib/${serie}/mon-clib-package.sh debian10" } }, 'debian10-armhf': { node { sh 'setup_centreon_build.sh' sh "./centreon-build/jobs/clib/${serie}/mon-clib-package.sh debian10-armhf" } /* }, 'opensuse-leap': { node { sh 'setup_centreon_build.sh' sh "./centreon-build/jobs/clib/${serie}/mon-clib-package.sh opensuse-leap" } */ } if ((currentBuild.result ?: 'SUCCESS') != 'SUCCESS') { error('Package stage failure.'); } } if ((env.BUILD == 'RELEASE') || (env.BUILD == 'REFERENCE')) { stage('Delivery') { node { sh 'setup_centreon_build.sh' sh "./centreon-build/jobs/clib/${serie}/mon-clib-delivery.sh" } if ((currentBuild.result ?: 'SUCCESS') != 'SUCCESS') { error('Delivery stage failure.'); } } } } finally { buildStatus = currentBuild.result ?: 'SUCCESS'; if ((buildStatus != 'SUCCESS') && ((env.BUILD == 'RELEASE') || (env.BUILD == 'REFERENCE'))) { slackSend channel: '#monitoring-metrology', message: "@channel Centreon Clib build ${env.BUILD_NUMBER} of branch ${env.BRANCH_NAME} was broken by ${source.COMMITTER}. Please fix it ASAP." } } centreon-clib-21.04.2/LICENSE000066400000000000000000000261361407153644500154320ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. centreon-clib-21.04.2/README.md000066400000000000000000000101211407153644500156670ustar00rootroot00000000000000# Centreon Clib Centreon Clib is an open-source utility library used by some Centreon software. It is a low-level component of the [Centreon software suite](https://www.centreon.com). Centreon Clib is released under the General Public License version 2 and is endorsed by the [Centreon company](https://www.centreon.com). ## Documentation *Coming soon on https://docs.centreon.com* ## Installing from binaries > Centreon Clib is a low-level component of the Centreon > software suite. If this is your first installation you would probably > want to [install it entirely](https://docs.centreon.com/current/en/installation/installation-of-a-central-server/using-sources.html). Centreon ([the company behind the Centreon software suite](http://www.centreon.com)) provides binary packages for RedHat / CentOS. They are available either as part of the [Centreon Platform](https://www.centreon.com/en/platform/) or as individual packages on [our RPM repository](https://docs.centreon.com/current/en/installation/installation-of-a-poller/using-packages.html). Once the repository installed a simple command will be needed to install Centreon Clib. ```shell yum install centreon-clib ``` ## Fetching sources Beware that the repository hosts in-development sources and that it might not work at all. Stable releases are available as gziped tarballs on [Centreon's download site](https://download.centreon.com). ## Compilation This paragraph is only a quickstart guide for the compilation of Centreon Clib. ### CentOS / Debian / Raspbian Compilation of these distributions is pretty straightforward. You'll need to download the project and launch the *cmake.sh* script to prepare the compilation environment. Here are the command lines to launch: ```shell git clone https://github.com/centreon/centreon-clib cd centreon-clib ./cmake.sh cd build make make install ``` ### Other distributions If you are on another distribution, then follow the steps below. Check if you have these packages installed (Note that packages names come from CentOS distributions, so if some packages names don't match on your distribution try to find their equivalent names): git, make, cmake. Once the sources of Centreon Clib extracted, create the *build/* directory and from that directory launch the CMake command as proposed below: ```shell git clone https://github.com/centreon/centreon-clib mkdir -p centreon-clib/build cd centreon-clib/build cmake -DWITH_PREFIX=/usr -DCMAKE_BUILD_TYPE=Release -DWITH_PREFIX_LIB=/usr/lib64 -DWITH_TESTING=On .. ``` Now launch the compilation using the *make* command and then install the software by running *make install* as priviledged user: ```shell make make install ``` 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-clib/issues/). Please note that Centreon Clib follows the [same workflow as Centreon](https://github.com/centreon/centreon/issues/new/choose) to process issues. For a quick resolution of a bug your message should contain: - The problem description - Precise steps on how to reproduce the issue (if you're using Centreon web UI tell us where you click) - The expected behavior - The Centreon product**s** version**s** - The operating system you're using (name and version) - If possible configuration, log and debug files ## Contributing Contributions are much welcome! If possible provide them as pull-requests on GitHub. If not, patches will do but describe against which version/commit they apply. For any question or remark feel free to send a mail to the project maintainers:       centreon-clib-21.04.2/SECURITY.md000066400000000000000000000110441407153644500162060ustar00rootroot00000000000000# Security Policy Centreon takes the security of our software products seriously. If you believe you have found a security vulnerability, please report it to us as described below. ## Reporting a Vulnerability **Please do not report security vulnerabilities through public GitHub issues.** Send an email to security@centreon.com. If possible, encrypt your message with our PGP key below. You should receive a response within 48 hours. If for some reason you do not, please follow up via email to ensure we received your original message. To help us better understand the nature and scope of the possible issue, please describe as much as you can: * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) * Full paths of source file(s) related to the manifestation of the issue * The location of the affected source code (tag/branch/commit or direct URL) * Any special configuration required to reproduce the issue * Step-by-step instructions to reproduce the issue * Proof-of-concept or exploit code (if possible) * Impact of the issue, including how an attacker might exploit the issue ## PGP information ### Public key ``` -----BEGIN PGP PUBLIC KEY BLOCK----- mQINBF5Cei0BEADhmq8U5rvapCD4AtG0dMpdILACNXfDeU9egywe6eP23fia+RDZ umlCGqPeBny3zU+wcE4Kik6nsCmqy61rgHsgTVbWEEeu1AJoJfq0GneBBwWI5sWV QwAUTmJSEJgYB9oRyHErhhxuBdjfbLqHRV2fMZjyQOqTRQtZ1PuJHbbzB29Plj1q K0VYfO5q2RLWDol5TbtiBEDiF1Wl3UcPF2jmlgHWS/iCpmFKz2ABOkKgUBpn83Sa E+PYY/CMOL8YAd77oV47a0yA9kuLgEcQITviB7lU2Yq9URVSWG1I3SxFFU6/IEn6 HFj3vbs8zWEn/LN1mCW5MlDPH2VlHp8QTdUGrrKSM0mEv/xddkZx6QFZ7K0bVzNB 1fGRTcn8hxbw0YVsJyUAMpZORhnKJS5VLSyZAU7y+EGVy9Q7VurjZN51HBgtuArl ZorLscu8FS6XLFXzGiePKUyJ2RN+c8o78FsB+QZ6Zgxwx/F06zRYXpgZM1ONMTnu MTeg1ea5w7m8DQCQAElk5EQBTqtk+XCRoKz4Bb4BuqFrqbx1MoFHY6QXi+5ThNXI 4xIja2r6KpfKSFE6ewLU0ew521eBbA4i/ib+DMPRQ1xORiuTTJWgxqMX1jL7tnYi A78LF+3PfHwiMRM6c+csLE/aw9aVGlpyULj/9LVpyqdQeEYoBes0SiDcGwARAQAB tClDZW50cmVvbiBTZWN1cml0eSA8c2VjdXJpdHlAY2VudHJlb24uY29tPokCVAQT AQgAPhYhBMN36dUtXBN9PdVztb6vbr9jEQb5BQJeQnotAhsDBQkB4TOABQsJCAcC BhUKCQgLAgQWAgMBAh4BAheAAAoJEL6vbr9jEQb5frIP/1361JCYjrTG9zF5REar qXQ5pUtqlYgG3fXUm8HJoNrBPnxpVHNlul8B7TtmkIbjPWa444Ez5G/cS/oyYQD8 9mG92FP+GpQYHDANB3g2BGQwHaORxiBGkrGAtTozptlxqvIxoHty62aSQQ8GW4dA M0ce30scRarDbfliyVI1VmFytpIovNsax+dIAbHk21eKy7Ds85qToYoz50AVgNoJ IQmZdVhittrahqFLhlGLPNkngj7efk/2XOCOsGCa7pv2J9iJQ3gZkF5JPnQnLRv2 szMPThAVa/xZSCjoxqh4dzcewZVuj/Hxw+tdoJK00AqgHen+C23jEiDOK3cTrxVI wKTs/Og1LjLSLN0HUYjazE9jGvm9Mo+yQuKoJEyx6pOWh9APSInGoy2TJa/caQ73 sSlMpl84a6LiyP+yUAJYFjrjwUzbrCR4Y4GRDHay2YnHcGCdO5EXvN+retEl1cNb X7PKkEDby4CEsuAFUB/liAAbQILVjTJ9tKKtHER9VJwkLoR04N18N35tdbsHdDmW C+BjwwHCSXbWeWNaE2zmkzb46kMpjgtdPwdO5TsI+lpK5lcrrldygoV7srB4Sera 5k4Ci65K9vNQ6KTqds/riyiZj9ofFuHd81NYCoUvGx2DyJrtEnW0ay+3m3lzsdTZ eBEtw/3Gx7DSjgn4X9soJHsRuQINBF5CgfMBEADmxcDYgg+sI1f9SkdRZY/cVzWQ 0kmSRMQ5Q1wABc07uXeFQlpubZEWzeB13v0puI4A0WGjSNnWD0JBJZSxqFiKlytZ q+xJnO1eLjN3A4RlvIxFnjmtZXW2x3bGS/t9TbWIDvgFs4RfiyOsVimFRdvB3YEE UtrcLnb5cmxLznDQwpJTStevuWuoVhc8bfiGepiAzXhdOlJ85keH8Hq3Ujgqs/dx mBa68hokTTMt33SwQ9KAoTQvrKNu1B+fTSQBmN3yBzKiZEX3JzapK70TfR9mc1CJ JiLoJyKqDhyY0IaMCqd5mdA5Q2TdXtn/iwFrxiyUi+1QF5I4c19hUoZchn5I+exw anLabHP6EsM2kHeO8J1nHiNJ2b58lxVcUBTMkkoQLxN1shOozkYiapX33Cxv+Smy 57Pw8SpbZfZqDfmazUgF/aboJY9vcQ1+fK6VzmXK42GAYu968Z9Vvxi6+qNPIz1P cCC6t+Yzlrv3EadFUTAeXiHjpxjef3Lv7BWLZDr5psaCgvRzO0Ffn4hniUiKqTTb wHJxDA1iP9vfEAh61kpBQ8p+C6h4+hn5OWCbz6GBp+wEG1Rswrz734K7Aiywr8pH la1+oXYkRrAZop9Oagh9weimbR0ZZ76kD4duSq3blV6mhh7Cs94e4HINB6NzMfXg YYk4Dwr6aiW2Np5MLQARAQABiQI8BBgBCAAmFiEEw3fp1S1cE3091XO1vq9uv2MR BvkFAl5CgfMCGwwFCQHhM4AACgkQvq9uv2MRBvnkkw//UbXbzC0tcStxnSqRXmdL Lv11lFa2hFcAP3/aLoHyryF4qoiqhGc0K6nrd9ApE2tMia1PKV3jiBlhTlXWeR8m Y7/y3OJSqjSg8qu9L14AQhLzvYNEAc3TVhAAMNQoekDg/QapQSPxpqlPjhFyF91K jjvSXPHVuFWKmYvPqldceTX8J032fOGDrhAPmzaXo487CDPVuQe3Xg8V+yZdLcpw KBU800tQ/GkI5Zb2HrxIQ/qEPmcFHcpQQnbu7nuBe8OzfwWCIZ3clN55LYF9FgmQ MoefpoBeEpWxNAY23KT6MkjeX/VxtRF+gwGTPGAoRoiRrrywLSPAlzj0V4iglSs7 wPqugycY7sfOGZ2KzciLmUkM8pd2/Kv1AFF3zYznvSmov71el8hh46FCE4a2xo71 kmh+//+obMyASf6npTIeNwBKV0sSZ49AoEd/kA6agYXbEjRIPLgVyvCyEHGhmAOS U1UYTpy6qXTX2Xj0rCvOXlxDCWIMyesjjBxKyuoe4TYMPp+D9ZEBndN45lYNmfBG Vl95htR6juC4rRBtQZDgZFzD9y20shRsXFZ9t9GSpO5wmKOxuFwPq6c9pyiUM83T Y6odD3X30YsLpvwBEXlvs0pLXVjlJn3PZsKE5qEbOIy29elhjoMDuZ9F3kWD4ykv oWAyTvK/VwbB77CTz1yTUSE= =3kAj -----END PGP PUBLIC KEY BLOCK----- ``` | Tag | Value | | -- | -- | | ID | BEAF6EBF631106F9 | | Type | RSA | | Size | 4096 | | Created | 2020-02-11 | | Expires | 2021-02-10 | | Cipher |AES-256| | Fingerprint | C377 E9D5 2D5C 137D 3DD5 73B5 BEA F6EBF 6311 06F9 | ## Bug bounty We don't have a bug bounty program but this is something we are thinking about. centreon-clib-21.04.2/cmake.sh000077500000000000000000000101751407153644500160400ustar00rootroot00000000000000#!/bin/bash # Usage info show_help() { cat << EOF Usage: ${0##*/} -n=[yes|no] -v This program build Centreon-clib -f|--force : force rebuild -r|--release : Build on release mode -h|--help : help EOF } force=0 BUILD_TYPE="Debug" for i in "$@" do case $i in -f|--force) force=1 shift ;; -r|--release) BUILD_TYPE="Release" ;; -h|--help) show_help exit 2 ;; *) # unknown option ;; esac done # Am I root? my_id=$(id -u) if [ -r /etc/centos-release ] ; then maj="centos$(cat /etc/centos-release | awk '{print $4}' | cut -f1 -d'.')" v=$(cmake --version) if [[ $v =~ "version 3" ]] ; then cmake='cmake' else if rpm -q cmake3 ; then cmake='cmake3' elif [ $maj = "centos7" ] ; then yum -y install epel-release yum -y install cmake3 cmake='cmake3' else dnf -y install cmake cmake='cmake' fi fi if ! rpm -q gcc-c++ ; then yum -y install gcc-c++ fi pkgs=( ninja-build ) for i in "${pkgs[@]}"; do if ! rpm -q $i ; then if [ $maj = 'centos7' ] ; then yum install -y $i else dnf -y --enablerepo=PowerTools install $i fi fi done elif [ -r /etc/issue ] ; then maj=$(cat /etc/issue | awk '{print $1}') version=$(cat /etc/issue | awk '{print $3}') v=$(cmake --version) if [[ $v =~ "version 3" ]] ; then cmake='cmake' elif [ $maj = "Debian" ] ; then if [ $version = "9" ] ; then dpkg="dpkg" else dpkg="dpkg --no-pager" fi if $dpkg -l --no-pager cmake ; then echo "Bad version of cmake..." exit 1 else if [ $my_id -eq 0 ] ; then apt install -y cmake cmake='cmake' else echo -e "cmake is not installed, you could enter, as root:\n\tapt install -y cmake\n\n" exit 1 fi fi pkgs=( gcc g++ ninja-build pkg-config ) for i in "${pkgs[@]}"; do if ! $dpkg -l --no-pager $i | grep "^ii" ; then if [ $my_id -eq 0 ] ; then apt install -y $i else echo -e "The package \"$i\" is not installed, you can install it, as root, with the command:\n\tapt install -y $i\n\n" exit 1 fi fi done elif [ $maj = "Raspbian" ] ; then if [ $version = "9" ] ; then dpkg="dpkg" else dpkg="dpkg --no-pager" fi if $dpkg -l --no-pager cmake ; then echo "Bad version of cmake..." exit 1 else if [ $my_id -eq 0 ] ; then apt install -y cmake cmake='cmake' else echo -e "cmake is not installed, you could enter, as root:\n\tapt install -y cmake\n\n" exit 1 fi fi pkgs=( gcc g++ ninja-build pkg-config ) for i in "${pkgs[@]}"; do if ! $dpkg -l --no-pager $i | grep "^ii" ; then if [ $my_id -eq 0 ] ; then apt install -y $i else echo -e "The package \"$i\" is not installed, you can install it, as root, with the command:\n\tapt install -y $i\n\n" exit 1 fi fi done else echo "Bad version of cmake..." exit 1 fi fi if [ ! -d build ] ; then mkdir build fi if [ "$force" = "1" ] ; then rm -rf build mkdir build fi cd build if [ $maj = "Raspbian" ] ; then CXXFLAGS="-Wall -Wextra" $cmake -DWITH_PREFIX=/usr -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DWITH_PREFIX_LIB=/usr/lib -DWITH_TESTING=On -DUSE_CXX11_ABI=1 $* .. elif [ $maj = "Debian" ] ; then CXXFLAGS="-Wall -Wextra" $cmake -DWITH_PREFIX=/usr -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DWITH_PREFIX_LIB=/usr/lib64 -DWITH_TESTING=On -DUSE_CXX11_ABI=1 $* .. else CXXFLAGS="-Wall -Wextra" $cmake -DWITH_PREFIX=/usr -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DWITH_PREFIX_LIB=/usr/lib64 -DWITH_TESTING=On -DUSE_CXX11_ABI=0 $* .. fi #CXX=/usr/bin/clang++ CC=/usr/bin/clang CXXFLAGS="-Wall -Wextra" cmake -DWITH_PREFIX=/usr -DCMAKE_BUILD_TYPE=Debug -DWITH_PREFIX_LIB=/usr/lib64 -DWITH_TESTING=On $* .. #CXXFLAGS="-Wall -Wextra -O1 -fsanitize=address -fno-omit-frame-pointer" cmake -DWITH_PREFIX=/usr -DCMAKE_BUILD_TYPE=Debug -DWITH_PREFIX_LIB=/usr/lib64 -DWITH_TESTING=On $* .. centreon-clib-21.04.2/cmake/000077500000000000000000000000001407153644500154755ustar00rootroot00000000000000centreon-clib-21.04.2/cmake/CodeCoverage.cmake000066400000000000000000000211521407153644500210260ustar00rootroot00000000000000# Copyright (c) 2012 - 2017, Lars Bilke # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # CHANGES: # # 2012-01-31, Lars Bilke # - Enable Code Coverage # # 2013-09-17, Joakim Söderberg # - Added support for Clang. # - Some additional usage instructions. # # 2016-02-03, Lars Bilke # - Refactored functions to use named parameters # # 2017-06-02, Lars Bilke # - Merged with modified version from github.com/ufz/ogs # # # USAGE: # # 1. Copy this file into your cmake modules path. # # 2. Add the following line to your CMakeLists.txt: # include(CodeCoverage) # # 3. Append necessary compiler flags: # APPEND_COVERAGE_COMPILER_FLAGS() # # 4. If you need to exclude additional directories from the report, specify them # using the COVERAGE_EXCLUDES variable before calling SETUP_TARGET_FOR_COVERAGE. # Example: # set(COVERAGE_EXCLUDES 'dir1/*' 'dir2/*') # # 5. Use the functions described below to create a custom make target which # runs your test executable and produces a code coverage report. # # 6. Build a Debug build: # cmake -DCMAKE_BUILD_TYPE=Debug .. # make # make my_coverage_target # include(CMakeParseArguments) # Check prereqs find_program( GCOV_PATH gcov ) find_program( LCOV_PATH lcov ) find_program( GENHTML_PATH genhtml ) find_program( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/scripts/test) find_program( SIMPLE_PYTHON_EXECUTABLE python ) if(NOT GCOV_PATH) message(FATAL_ERROR "gcov not found! Aborting...") endif() # NOT GCOV_PATH if("${CMAKE_CXX_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang") if("${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS 3) message(FATAL_ERROR "Clang version must be 3.0.0 or greater! Aborting...") endif() elseif(NOT CMAKE_COMPILER_IS_GNUCXX) message(FATAL_ERROR "Compiler is not GNU gcc! Aborting...") endif() set(COVERAGE_COMPILER_FLAGS "-g -O0 --coverage -fprofile-arcs -ftest-coverage" CACHE INTERNAL "") set(CMAKE_CXX_FLAGS_COVERAGE ${COVERAGE_COMPILER_FLAGS} CACHE STRING "Flags used by the C++ compiler during coverage builds." FORCE ) set(CMAKE_C_FLAGS_COVERAGE ${COVERAGE_COMPILER_FLAGS} CACHE STRING "Flags used by the C compiler during coverage builds." FORCE ) set(CMAKE_EXE_LINKER_FLAGS_COVERAGE "" CACHE STRING "Flags used for linking binaries during coverage builds." FORCE ) set(CMAKE_SHARED_LINKER_FLAGS_COVERAGE "" CACHE STRING "Flags used by the shared libraries linker during coverage builds." FORCE ) mark_as_advanced( CMAKE_CXX_FLAGS_COVERAGE CMAKE_C_FLAGS_COVERAGE CMAKE_EXE_LINKER_FLAGS_COVERAGE CMAKE_SHARED_LINKER_FLAGS_COVERAGE ) if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug") message(WARNING "Code coverage results with an optimised (non-Debug) build may be misleading") endif() # NOT CMAKE_BUILD_TYPE STREQUAL "Debug" if(CMAKE_C_COMPILER_ID STREQUAL "GNU") link_libraries(gcov) else() set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --coverage") endif() # Defines a target for running and collection code coverage information # Builds dependencies, runs the given executable and outputs reports. # NOTE! The executable should always have a ZERO as exit code otherwise # the coverage generation will not complete. # # SETUP_TARGET_FOR_COVERAGE( # NAME testrunner_coverage # New target name # EXECUTABLE testrunner -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR # DEPENDENCIES testrunner # Dependencies to build first # ) function(SETUP_TARGET_FOR_COVERAGE) set(options NONE) set(oneValueArgs NAME) set(multiValueArgs EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES) cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if(NOT LCOV_PATH) message(FATAL_ERROR "lcov not found! Aborting...") endif() # NOT LCOV_PATH if(NOT GENHTML_PATH) message(FATAL_ERROR "genhtml not found! Aborting...") endif() # NOT GENHTML_PATH # Setup target add_custom_target(${Coverage_NAME} # Cleanup lcov COMMAND ${LCOV_PATH} --directory . --zerocounters # Run tests COMMAND ${Coverage_EXECUTABLE} # Capturing lcov counters and generating report COMMAND ${LCOV_PATH} --directory . --capture --output-file ${Coverage_NAME}.info COMMAND ${LCOV_PATH} --remove ${Coverage_NAME}.info ${COVERAGE_EXCLUDES} --output-file ${Coverage_NAME}.info.cleaned COMMAND ${GENHTML_PATH} -o ${Coverage_NAME} ${Coverage_NAME}.info.cleaned COMMAND ${CMAKE_COMMAND} -E remove ${Coverage_NAME}.info ${Coverage_NAME}.info.cleaned WORKING_DIRECTORY ${PROJECT_BINARY_DIR} DEPENDS ${Coverage_DEPENDENCIES} COMMENT "Resetting code coverage counters to zero.\nProcessing code coverage counters and generating report." ) # Show info where to find the report add_custom_command(TARGET ${Coverage_NAME} POST_BUILD COMMAND ; COMMENT "Open ./${Coverage_NAME}/index.html in your browser to view the coverage report." ) endfunction() # SETUP_TARGET_FOR_COVERAGE # Defines a target for running and collection code coverage information # Builds dependencies, runs the given executable and outputs reports. # NOTE! The executable should always have a ZERO as exit code otherwise # the coverage generation will not complete. # # SETUP_TARGET_FOR_COVERAGE_COBERTURA( # NAME ctest_coverage # New target name # EXECUTABLE ctest -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR # DEPENDENCIES executable_target # Dependencies to build first # ) function(SETUP_TARGET_FOR_COVERAGE_COBERTURA) set(options NONE) set(oneValueArgs NAME) set(multiValueArgs EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES) cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if(NOT SIMPLE_PYTHON_EXECUTABLE) message(FATAL_ERROR "python not found! Aborting...") endif() # NOT SIMPLE_PYTHON_EXECUTABLE if(NOT GCOVR_PATH) message(FATAL_ERROR "gcovr not found! Aborting...") endif() # NOT GCOVR_PATH # Combine excludes to several -e arguments set(COBERTURA_EXCLUDES "") foreach(EXCLUDE ${COVERAGE_EXCLUDES}) set(COBERTURA_EXCLUDES "-e ${EXCLUDE} ${COBERTURA_EXCLUDES}") endforeach() add_custom_target(${Coverage_NAME} # Run tests ${Coverage_EXECUTABLE} # Running gcovr COMMAND ${GCOVR_PATH} -x -r ${CMAKE_SOURCE_DIR} ${COBERTURA_EXCLUDES} -o ${Coverage_NAME}.xml WORKING_DIRECTORY ${PROJECT_BINARY_DIR} DEPENDS ${Coverage_DEPENDENCIES} COMMENT "Running gcovr to produce Cobertura code coverage report." ) # Show info where to find the report add_custom_command(TARGET ${Coverage_NAME} POST_BUILD COMMAND ; COMMENT "Cobertura code coverage report saved in ${Coverage_NAME}.xml." ) endfunction() # SETUP_TARGET_FOR_COVERAGE_COBERTURA function(APPEND_COVERAGE_COMPILER_FLAGS) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE) message(STATUS "Appending code coverage compiler flags: ${COVERAGE_COMPILER_FLAGS}") endfunction() # APPEND_COVERAGE_COMPILER_FLAGS centreon-clib-21.04.2/cmake/package.cmake000066400000000000000000000055601407153644500201000ustar00rootroot00000000000000## ## 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 ## # Packaging. option(WITH_PACKAGE_SH "Build shell-installable package." OFF) option(WITH_PACKAGE_TGZ "Build gziped tarball package." OFF) option(WITH_PACKAGE_TBZ2 "Build bzip2'd tarball package." OFF) option(WITH_PACKAGE_DEB "Build DEB package." OFF) option(WITH_PACKAGE_RPM "Build RPM package." OFF) option(WITH_PACKAGE_NSIS "Build NSIS package." OFF) if (WITH_PACKAGE_SH OR WITH_PACKAGE_TGZ OR WITH_PACKAGE_TBZ2 OR WITH_PACKAGE_DEB OR WITH_PACKAGE_RPM OR WITH_PACKAGE_NSIS) # Default settings. set(CPACK_PACKAGE_NAME "centreon-clib") set(CPACK_PACKAGE_VENDOR "Centreon") 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 "centreon-clib-${CLIB_VERSION}") set(CPACK_PACKAGE_INSTALL_DIRECTORY "centreon-clib") set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/LICENSE") set(CPACK_PACKAGE_CONTACT "Matthieu Kermagoret ") # Generators. unset(PACKAGE_LIST) if (WITH_PACKAGE_SH) list(APPEND CPACK_GENERATOR "STGZ") list(APPEND PACKAGE_LIST "Shell-installable package (.sh)") endif () if (WITH_PACKAGE_TGZ) list(APPEND CPACK_GENERATOR "TGZ") list(APPEND PACKAGE_LIST "gziped tarball (.tar.gz)") endif () if (WITH_PACKAGE_TBZ2) list(APPEND CPACK_GENERATOR "TBZ2") list(APPEND PACKAGE_LIST "bzip2'd tarball (.tar.bz2)") endif () if (WITH_PACKAGE_DEB) list(APPEND CPACK_GENERATOR "DEB") list(APPEND PACKAGE_LIST "DEB package (.deb)") set(CPACK_DEBIAN_PACKAGE_SECTION "net") set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6, libstdc++6") endif () if (WITH_PACKAGE_RPM) list(APPEND CPACK_GENERATOR "RPM") list(APPEND PACKAGE_LIST "RPM package (.rpm)") set(CPACK_RPM_PACKAGE_RELEASE 1) set(CPACK_RPM_PACKAGE_LICENSE "ASL 2.0") endif () if (WITH_PACKAGE_NSIS) list(APPEND CPACK_GENERATOR "NSIS") list(APPEND PACKAGE_LIST "NSIS package (.exe)") endif () string(REPLACE ";" ", " PACKAGE_LIST "${PACKAGE_LIST}") # CPack module. include(CPack) else () set(PACKAGE_LIST "None") endif () centreon-clib-21.04.2/deps.go000066400000000000000000000052511407153644500157020ustar00rootroot00000000000000package main import ( "bufio" "fmt" "log" "os" "path/filepath" "regexp" "strings" ) // MaxDepth Max depth in search tree const MaxDepth = 3 func findIncludes(file string, treated *[]string, edges *[]string, depth int) { var myList []string file1 := file f, err := os.Open(file1) if err != nil { file1 = strings.TrimPrefix(file, "inc/") for _, pref := range []string{ "/usr/local/include/", "inc/", "modules/external_commands/inc/" } { f, err = os.Open(pref + file1) if err == nil { file1 = pref + file1 *treated = append(*treated, file1) break } } } else { *treated = append(*treated, file1) } defer f.Close() depth++ if depth > MaxDepth { return } scanner := bufio.NewScanner(f) r, _ := regexp.Compile("^#\\s*include\\s*([<\"])(.*)[>\"]") for scanner.Scan() { line := scanner.Text() match := r.FindStringSubmatch(line) if len(match) > 0 { /* match[0] is the global match, match[1] is '<' or '"' and match[2] is the file to include */ if match[1] == "\"" { *edges = append(*edges, fmt.Sprintf(" \"%s\" -> \"%s\";\n", file, match[2])) myList = append(myList, match[2]) } else { *edges = append(*edges, fmt.Sprintf(" \"%s\" -> \"%s\";\n", file, match[2])) } } } if err := scanner.Err(); err != nil { log.Print(file, " --- ", err) } for _, file2 := range myList { found := false for _, ff := range *treated { if ff == file2 { found = true break } } if !found { findIncludes(file2, treated, edges, depth) } } } func unique(edges []string) []string { keys := make(map[string]bool) list := []string{} for _, entry := range edges { if _, value := keys[entry]; !value { keys[entry] = true list = append(list, entry) } } return list } func main() { args := os.Args[1:] var fileList []string var edges []string if len(args) == 0 { for _, searchDir := range []string{"src", "inc"} { filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error { if strings.HasSuffix(path, ".cc") || strings.HasSuffix(path, ".hh") { fileList = append(fileList, path) } return nil }) } } else { fileList = append(fileList, args[0]) } fmt.Println("digraph deps {") var treated []string for _, file := range fileList { findIncludes(file, &treated, &edges, 0) } edges = unique(edges) for _, l := range edges { fmt.Println(l) } fmt.Println("}") } centreon-clib-21.04.2/deps.sh000077500000000000000000000003661407153644500157140ustar00rootroot00000000000000#!/bin/bash go run deps.go "$*" > /tmp/deps.dot dot -Tpng /tmp/deps.dot -o deps.png if [ -x /usr/bin/eog ] ; then eog deps.png& elif [ -x /usr/bin/lximage-qt ] ; then lximage-qt deps.png& else echo "No image viewer defined..." exit 1 fi centreon-clib-21.04.2/doc/000077500000000000000000000000001407153644500151625ustar00rootroot00000000000000centreon-clib-21.04.2/doc/README.md000066400000000000000000000000741407153644500164420ustar00rootroot00000000000000# Documentation *Coming soon on https://docs.centreon.com* centreon-clib-21.04.2/inc/000077500000000000000000000000001407153644500151665ustar00rootroot00000000000000centreon-clib-21.04.2/inc/com/000077500000000000000000000000001407153644500157445ustar00rootroot00000000000000centreon-clib-21.04.2/inc/com/centreon/000077500000000000000000000000001407153644500175615ustar00rootroot00000000000000centreon-clib-21.04.2/inc/com/centreon/clib.hh000066400000000000000000000014331407153644500210140ustar00rootroot00000000000000/* ** 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 CC_CLIB_HH #define CC_CLIB_HH #include "com/centreon/logging/engine.hh" #include "com/centreon/process_manager.hh" #endif // !CC_CLIB_HH centreon-clib-21.04.2/inc/com/centreon/clib/000077500000000000000000000000001407153644500204725ustar00rootroot00000000000000centreon-clib-21.04.2/inc/com/centreon/clib/version.hh.in000066400000000000000000000027461407153644500231160ustar00rootroot00000000000000/* ** 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 CC_CLIB_VERSION_HH # define CC_CLIB_VERSION_HH // Compile-time values. # 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" CC_BEGIN() namespace clib { namespace version { // Compile-time values. 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() throw (); unsigned int get_minor() throw (); unsigned int get_patch() throw (); char const* get_string() throw (); } } CC_END() #endif // !CC_HANDLE_HH centreon-clib-21.04.2/inc/com/centreon/delayed_delete.hh000066400000000000000000000036241407153644500230400ustar00rootroot00000000000000/* ** Copyright 2012-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 CC_DELAYED_DELETE_HH #define CC_DELAYED_DELETE_HH #include #include "com/centreon/namespace.hh" CC_BEGIN() /** * @class delayed_delete delayed_delete.hh "com/centreon/delayed_delete.hh" * @brief Perform a delayed delete. * * This template is used to perfom delayed object deletion using a task * manager. The pointer will be deleted when the run() method is * called. If the run() method has not been called when delayed_delete * is destroyed, the pointer won't be deleted. * * @see task_manager */ template class delayed_delete : public task { T* _ptr; /** * Copy internal data members. * * @param[in] dd Object to copy. */ void _internal_copy(delayed_delete const& dd) { _ptr = dd._ptr; } public: /** * Default constructor. * * @param[in] ptr Pointer to delete. */ delayed_delete(T* ptr) : _ptr(ptr) {} /** * Destructor. */ ~delayed_delete() noexcept {} /** * Copy constructor. * * @param[in] dd Object to copy. */ delayed_delete(delayed_delete const& dd) = delete; delayed_delete& operator=(delayed_delete const& dd) = delete; /** * Delete pointer. */ void run() { delete _ptr; _ptr = nullptr; } }; CC_END() #endif // !CC_DELAYED_DELETE_HH centreon-clib-21.04.2/inc/com/centreon/exceptions/000077500000000000000000000000001407153644500217425ustar00rootroot00000000000000centreon-clib-21.04.2/inc/com/centreon/exceptions/basic.hh000066400000000000000000000034551407153644500233530ustar00rootroot00000000000000/* ** 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 CC_EXCEPTIONS_BASIC_HH #define CC_EXCEPTIONS_BASIC_HH #include #include "com/centreon/misc/stringifier.hh" CC_BEGIN() namespace exceptions { /** * @class basic basic.hh "com/centreon/exceptions/basic.hh" * @brief Base exception class. * * Simple exception class containing an basic error message. */ class basic : public std::exception { public: basic(); basic(char const* file, char const* function, int line); basic(basic const& other); virtual ~basic() throw(); virtual basic& operator=(basic const& other); template basic& operator<<(T t) { _buffer << t; return (*this); } virtual char const* what() const throw(); private: void _internal_copy(basic const& other); misc::stringifier _buffer; }; } CC_END() #if defined(__GNUC__) #define FUNCTION __PRETTY_FUNCTION__ #elif defined(_MSC_VER) #define FUNCTION __FUNCSIG__ #else #define FUNCTION __func__ #endif // GCC, Visual or other. #ifndef NDEBUG #define basic_error() \ com::centreon::exceptions::basic(__FILE__, FUNCTION, __LINE__) #else #define basic_error() com::centreon::exceptions::basic() #endif // !NDEBUG #endif // !CC_EXCEPTIONS_BASIC_HH centreon-clib-21.04.2/inc/com/centreon/exceptions/interruption.hh000066400000000000000000000036421407153644500250320ustar00rootroot00000000000000/* ** 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 CC_EXCEPTIONS_INTERRUPTION_HH #define CC_EXCEPTIONS_INTERRUPTION_HH #include "com/centreon/exceptions/basic.hh" #include "com/centreon/namespace.hh" CC_BEGIN() namespace exceptions { /** * @class interruption interruption.hh *"com/centreon/exceptions/interruption.hh" * @brief Exception signaling an interruption in processing. * * Some operation that was in progress was interrupted but did not * fail. This is mostly used to warn users of an errno of EINTR * during a syscall. */ class interruption : public basic { public: interruption(); interruption(char const* file, char const* function, int line); interruption(interruption const& other); virtual ~interruption() throw(); interruption& operator=(interruption const& other); template interruption& operator<<(T t) { basic::operator<<(t); return (*this); } }; } CC_END() #if defined(__GNUC__) #define FUNCTION __PRETTY_FUNCTION__ #elif defined(_MSC_VER) #define FUNCTION __FUNCSIG__ #else #define FUNCTION __func__ #endif // GCC, Visual or other. #ifndef NDEBUG #define interruption_error() \ com::centreon::exceptions::basic(__FILE__, FUNCTION, __LINE__) #else #define interruption_error() com::centreon::exceptions::basic() #endif // !NDEBUG #endif // !CC_EXCEPTIONS_INTERRUPTION_HH centreon-clib-21.04.2/inc/com/centreon/handle.hh000066400000000000000000000025641407153644500213440ustar00rootroot00000000000000/* ** Copyright 2011-2013,2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #ifndef CC_HANDLE_HH #define CC_HANDLE_HH #include "com/centreon/namespace.hh" CC_BEGIN() typedef int native_handle; native_handle const native_handle_null = -1; /** * @class handle handle.hh "com/centreon/handle.hh" * @brief Base for all handle objetcs. * * This class is an interface for system handle. */ class handle { public: handle() = default; virtual ~handle() = default; handle(handle const& right) = delete; handle& operator=(handle const& right) = delete; virtual void close() = 0; virtual native_handle get_native_handle() = 0; virtual unsigned long read(void* data, unsigned long size) = 0; virtual unsigned long write(void const* data, unsigned long size) = 0; }; CC_END() #endif // !CC_HANDLE_HH centreon-clib-21.04.2/inc/com/centreon/handle_action.hh000066400000000000000000000032361407153644500226760ustar00rootroot00000000000000/* ** 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 CC_HANDLE_ACTION_HH #define CC_HANDLE_ACTION_HH #include #include "com/centreon/task.hh" CC_BEGIN() // Forward declaration. class handle; class handle_listener; /** * @class handle_action handle_action.hh "com/centreon/handle_action.hh" * @brief Notify a listener. * * Notify a listener from a handle event. */ class handle_action : public task { public: enum action { none = 0, read, write, error }; handle_action(handle* h, handle_listener* hl, bool is_threadable = false); handle_action(handle_action const& right) = delete; ~handle_action() noexcept; handle_action& operator=(handle_action const& right) = delete; bool is_threadable() const noexcept; handle* get_handle() const noexcept; handle_listener* get_handle_listener() const noexcept; void run(); void set_action(action a) noexcept; private: void _internal_copy(handle_action const& right); std::atomic _action; handle* _h; handle_listener* _hl; bool _is_threadable; }; CC_END() #endif // !CC_HANDLE_ACTION_HH centreon-clib-21.04.2/inc/com/centreon/handle_listener.hh000066400000000000000000000027661407153644500232550ustar00rootroot00000000000000/* ** 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 CC_HANDLE_LISTENER_HH #define CC_HANDLE_LISTENER_HH #include "com/centreon/handle.hh" CC_BEGIN() /** * @class handle_listener handle_listener.hh "com/centreon/handle_listener.hh" * @brief Base for all handle_listener objects. * * This class is an interface to receive notification from * handle_manager for specific handle. */ class handle_listener { public: handle_listener() = default; virtual ~handle_listener() noexcept {} handle_listener(handle_listener const&) = delete; handle_listener& operator=(handle_listener const&) = delete; virtual void error(handle& h) = 0; virtual void read(handle& h) { char buf[4096]; h.read(buf, sizeof(buf)); } virtual bool want_read(handle&) { return false; } virtual bool want_write(handle&) { return false; } virtual void write(handle&) {} }; CC_END() #endif // !CC_HANDLE_LISTENER_HH centreon-clib-21.04.2/inc/com/centreon/handle_manager.hh000066400000000000000000000035551407153644500230370ustar00rootroot00000000000000/* ** 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 CC_HANDLE_MANAGER_POSIX_HH #define CC_HANDLE_MANAGER_POSIX_HH #include #include #include #include #include "com/centreon/handle.hh" CC_BEGIN() // Forward declarations. class handle_action; class handle_listener; class task_manager; /** * @class handle_manager handle_manager_posix.hh * "com/centreon/handle_manager.hh" * @brief Multiplex I/O from multiple handles. * * Listen handles and notifies listeners accordingly. */ class handle_manager { public: handle_manager(task_manager* tm = nullptr); handle_manager(handle_manager const& right) = delete; virtual ~handle_manager() throw(); handle_manager& operator=(handle_manager const& right) = delete; void add(handle* h, handle_listener* hl, bool is_threadable = false); void link(task_manager* tm); void multiplex(); bool remove(handle* h); unsigned int remove(handle_listener* hl); private: // void _internal_copy(handle_manager const& right); static int _poll(pollfd* fds, nfds_t nfds, int timeout) throw(); void _setup_array(); pollfd* _array; std::map _handles; bool _recreate_array; task_manager* _task_manager; }; CC_END() #endif // !CC_HANDLE_MANAGER_POSIX_HH centreon-clib-21.04.2/inc/com/centreon/hash.hh000066400000000000000000000072731407153644500210360ustar00rootroot00000000000000/* ** Copyright 2012-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 CC_HASH_HH #define CC_HASH_HH #if __cplusplus == 201103L #define CXX0X_UNORDERED 1 #elif defined(__clang__) #if __has_feature(cxx_variadic_templates) #define TR1_UNORDERED 1 #endif // cxx_variadic_templates. #elif defined(__GNUC__) && __GNUC__ >= 4 #define TR1_UNORDERED 1 #endif // C++0x, tr1 #include "com/centreon/namespace.hh" // Used c++0x implementation. #ifdef CXX0X_UNORDERED #include CC_BEGIN() template std::size_t hash(T const& data) { std::hash h; return (h(data)); } CC_END() // Used tr1 implementation. #elif defined(TR1_UNORDERED) #include CC_BEGIN() template std::size_t hash(T const& data) { std::tr1::hash h; return (h(data)); } CC_END() // Used own implementation. #else CC_BEGIN() template std::size_t hash(T const& data) { std::size_t res(14695981039346656037ULL); for (typename T::const_iterator it(data.begin()), end(data.end()); it != end; ++it) { res ^= static_cast(*it); res *= static_cast(1099511628211ULL); } return (res); } template <> inline std::size_t hash(bool val) { return (static_cast(val)); } template <> inline std::size_t hash(char val) { return (static_cast(val)); } template <> inline std::size_t hash(int val) { return (static_cast(val)); } template <> inline std::size_t hash(long long val) { return (static_cast(val)); } template <> inline std::size_t hash(long val) { return (static_cast(val)); } template <> inline std::size_t hash(short val) { return (static_cast(val)); } template <> inline std::size_t hash(unsigned char val) { return (static_cast(val)); } template <> inline std::size_t hash(unsigned int val) { return (static_cast(val)); } template <> inline std::size_t hash(unsigned long long val) { return (static_cast(val)); } template <> inline std::size_t hash(unsigned long val) { return (static_cast(val)); } template <> inline std::size_t hash(unsigned short val) { return (static_cast(val)); } CC_END() #endif // C++0X, tr1 or std CC_BEGIN() template std::size_t hash(std::pair const& data) { std::size_t id(hash(data.first)); return (hash(data.second) + 0x9e3779b9 + (id << 6) + (id >> 2)); } template std::size_t hash(T begin, T end) { std::size_t res(0); while (begin != end) { res ^= hash(*begin) + 0x9e3779b9 + (res << 6) + (res >> 2); ++begin; } return (res); } template std::size_t hash_combine(std::size_t& seed, T const& data) { seed ^= hash(data) + 0x9e3779b9 + (seed << 6) + (seed >> 2); return (seed); } template std::size_t hash_combine(std::size_t& seed, T begin, T end) { seed ^= hash(begin, end) + 0x9e3779b9 + (seed << 6) + (seed >> 2); return (seed); } CC_END() #endif // !CC_HASH_HH centreon-clib-21.04.2/inc/com/centreon/io/000077500000000000000000000000001407153644500201705ustar00rootroot00000000000000centreon-clib-21.04.2/inc/com/centreon/io/directory_entry.hh000066400000000000000000000035051407153644500237410ustar00rootroot00000000000000/* ** Copyright 2012-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 CC_IO_DIRECTORY_ENTRY_HH #define CC_IO_DIRECTORY_ENTRY_HH #include #include #include "com/centreon/io/file_entry.hh" #include "com/centreon/handle.hh" #include "com/centreon/namespace.hh" CC_BEGIN() namespace io { /** * @class directory_entry directory_entry.hh *"com/centreon/io/directory_entry.hh" * @brief Wrapper of libc's directory_entryectory. * * Wrap standard directory_entryectory objects. */ class directory_entry { public: directory_entry(char const* path = NULL); directory_entry(std::string const& path); directory_entry(directory_entry const& right); directory_entry& operator=(directory_entry const& right); bool operator==(directory_entry const& right) const throw(); bool operator!=(directory_entry const& right) const throw(); ~directory_entry() throw(); static std::string current_path(); file_entry const& entry() const throw(); std::list const& entry_list(std::string const& filter = ""); private: void _internal_copy(directory_entry const& right); static int _nmatch(char const* str, char const* pattern); file_entry _entry; std::list _entry_lst; }; } CC_END() #endif // !CC_IO_DIRECTORY_ENTRY_HH centreon-clib-21.04.2/inc/com/centreon/io/file_entry.hh000066400000000000000000000036241407153644500226560ustar00rootroot00000000000000/* ** Copyright 2012-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 CC_IO_FILE_ENTRY_HH #define CC_IO_FILE_ENTRY_HH #include #include #include #include "com/centreon/handle.hh" #include "com/centreon/namespace.hh" #ifdef _WIN32 #define stat _stat #endif // _WIN32 CC_BEGIN() namespace io { /** * @class file_entry file_entry.hh "com/centreon/io/file_entry.hh" * @brief Wrapper of stat information. * * Wrap standard stat information. */ class file_entry { public: file_entry(char const* path = NULL); file_entry(std::string const& path); file_entry(file_entry const& right); ~file_entry() throw(); file_entry& operator=(file_entry const& right); bool operator==(file_entry const& right) const throw(); bool operator!=(file_entry const& right) const throw(); std::string base_name() const; std::string directory_name() const; std::string file_name() const; bool is_directory() const throw(); bool is_link() const throw(); bool is_regular() const throw(); std::string const& path() const throw(); void path(char const* path); void path(std::string const& path); void refresh(); unsigned long long size() const throw(); private: void _internal_copy(file_entry const& right); std::string _path; struct stat _sbuf; }; } CC_END() #endif // !CC_IO_FILE_ENTRY_HH centreon-clib-21.04.2/inc/com/centreon/io/file_stream.hh000066400000000000000000000041361407153644500230070ustar00rootroot00000000000000/* ** Copyright 2012-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 CC_IO_FILE_STREAM_HH #define CC_IO_FILE_STREAM_HH #include #include #include "com/centreon/handle.hh" #include "com/centreon/namespace.hh" CC_BEGIN() namespace io { /** * @class file_stream file_stream.hh "com/centreon/io/file_stream.hh" * @brief Wrapper of libc's FILE streams. * * Wrap standard FILE stream objects. */ class file_stream : public handle { public: file_stream(FILE* stream = NULL, bool auto_close = false); ~file_stream() throw(); void close(); static void copy(char const* src, char const* dst); static void copy(std::string const& src, std::string const& dst); static bool exists(char const* path); static bool exists(std::string const& path); void flush(); native_handle get_native_handle(); void open(char const* path, char const* mode); void open(std::string const& path, char const* mode); unsigned long read(void* data, unsigned long size); static bool remove(char const* path); static bool remove(std::string const& path); static bool rename(char const* old_filename, char const* new_filename); static bool rename(std::string const& old_filename, std::string const& new_filename); unsigned long size(); static char* temp_path(); unsigned long write(void const* data, unsigned long size); private: file_stream(file_stream const& fs); file_stream& operator=(file_stream const& fs); bool _auto_close; FILE* _stream; }; } CC_END() #endif // !CC_IO_FILE_STREAM_HH centreon-clib-21.04.2/inc/com/centreon/library.hh000066400000000000000000000027361407153644500215560ustar00rootroot00000000000000/* ** Copyright 2012-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 CC_LIBRARY_POSIX_HH #define CC_LIBRARY_POSIX_HH #include #include #include "com/centreon/namespace.hh" CC_BEGIN() /** * @class library library.hh "com/centreon/library.hh" * @brief Wrapper of libc's library loader. * * Wrap standard library loader objects. */ class library { public: library(std::string const& filename); ~library() throw(); std::string const& filename() const throw(); bool is_loaded() const throw(); void load(); void* resolve(char const* symbol); void* resolve(std::string const& symbol); void (*resolve_proc(char const* symbol))(); void (*resolve_proc(std::string const& symbol))(); void unload(); private: library(library const& right); library& operator=(library const& right); std::string _filename; void* _handle; }; CC_END() #endif // !CC_LIBRARY_POSIX_HH centreon-clib-21.04.2/inc/com/centreon/logging/000077500000000000000000000000001407153644500212075ustar00rootroot00000000000000centreon-clib-21.04.2/inc/com/centreon/logging/backend.hh000066400000000000000000000045161407153644500231250ustar00rootroot00000000000000/* ** 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 CC_LOGGING_BACKEND_HH #define CC_LOGGING_BACKEND_HH #include #include "com/centreon/namespace.hh" CC_BEGIN() namespace misc { class stringifier; } namespace logging { enum time_precision { none = 0, microsecond = 1, millisecond = 2, second = 3 }; /** * @class backend backend.hh "com/centreon/logging/backend.hh" * @brief Base logging backend class. * * This class defines an interface to create logger backend, to * log data into many different objects. */ class backend { public: backend(bool is_sync = true, bool show_pid = true, time_precision show_timestamp = second, bool show_thread_id = false); backend(backend const& right); virtual ~backend() noexcept; backend& operator=(backend const& right); virtual void close() noexcept = 0; virtual bool enable_sync() const; virtual void enable_sync(bool enable); virtual void log(uint64_t types, uint32_t verbose, char const* msg) noexcept; virtual void log(uint64_t types, uint32_t verbose, char const* msg, uint32_t size) noexcept = 0; virtual void open() = 0; virtual void reopen() = 0; virtual bool show_pid() const; virtual void show_pid(bool enable); virtual time_precision show_timestamp() const; virtual void show_timestamp(time_precision val); virtual bool show_thread_id() const; virtual void show_thread_id(bool enable); protected: void _build_header(misc::stringifier& buffer); bool _is_sync; mutable std::mutex _lock; bool _show_pid; time_precision _show_timestamp; bool _show_thread_id; protected: void _internal_copy(backend const& right); }; } CC_END() #endif // !CC_LOGGING_BACKEND_HH centreon-clib-21.04.2/inc/com/centreon/logging/engine.hh000066400000000000000000000047571407153644500230120ustar00rootroot00000000000000/* ** 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 CC_LOGGING_ENGINE_HH #define CC_LOGGING_ENGINE_HH #include #include #include #include "com/centreon/namespace.hh" CC_BEGIN() namespace logging { class backend; /** * @class engine engine.hh "com/centreon/logging/engine.hh" * @brief Logging object manager. * * This is an external access point to logging system. Allow to * register backends and write log message into them. */ class engine { public: unsigned long add(backend* obj, unsigned long long types, unsigned int verbose); /** * Get the logger engine singleton. * * @return The unique instance of logger engine. */ static engine& instance() noexcept; /** * Check if at least one backend can log with this parameter. * * @param[in] flag The logging type to log. * @param[in] verbose The verbosity level. * * @return True if at least one backend can log with this * parameter, otherwise false. */ bool is_log(unsigned long long types, unsigned int verbose) const throw() { if (verbose >= sizeof(unsigned int) * CHAR_BIT) return (false); return (_list_types[verbose] & types); } void log(unsigned long long types, unsigned int verbose, char const* msg, unsigned int size); bool remove(unsigned long id); unsigned int remove(backend* obj); void reopen(); private: struct backend_info { unsigned long id; backend* obj; unsigned long long types; unsigned int verbose; }; engine(); engine(engine const& right); ~engine() throw(); engine& operator=(engine const& right); void _rebuild_types(); std::vector _backends; unsigned long _id; unsigned long long _list_types[sizeof(unsigned int) * CHAR_BIT]; mutable std::mutex _mtx; }; } CC_END() #endif // !CC_LOGGING_ENGINE_HH centreon-clib-21.04.2/inc/com/centreon/logging/file.hh000066400000000000000000000035621407153644500224550ustar00rootroot00000000000000/* ** 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 CC_LOGGING_FILE_HH #define CC_LOGGING_FILE_HH #include #include #include "com/centreon/logging/backend.hh" #include "com/centreon/namespace.hh" CC_BEGIN() namespace logging { /** * @class file file.hh "com/centreon/logging/file.hh" * @brief Log messages to file. */ class file : public backend { public: file(FILE* file, bool is_sync = true, bool show_pid = true, time_precision show_timestamp = second, bool show_thread_id = false, uint64_t max_size = 0); file(std::string const& path, bool is_sync = true, bool show_pid = true, time_precision show_timestamp = second, bool show_thread_id = false, uint64_t max_size = 0); virtual ~file() noexcept; void close() noexcept; std::string const& filename() const noexcept; void log(uint64_t types, uint32_t verbose, char const* msg, uint32_t size) noexcept; void open(); void reopen(); protected: virtual void _max_size_reached(); private: file(file const& right); file& operator=(file const& right); void _flush() noexcept; uint64_t _max_size; std::string _path; FILE* _out; uint64_t _size; }; } CC_END() #endif // !CC_LOGGING_FILE_HH centreon-clib-21.04.2/inc/com/centreon/logging/logger.hh000066400000000000000000000054771407153644500230240ustar00rootroot00000000000000/* ** 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 CC_LOGGING_LOGGER_HH #define CC_LOGGING_LOGGER_HH #include "com/centreon/logging/temp_logger.hh" CC_BEGIN() namespace logging { enum type_value { type_info = (1ull << 61), type_debug = (1ull << 62), type_error = (1ull << 63) }; 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_define_ui) \ com::centreon::logging::temp_logger(com::centreon::logging::type_info, \ verbose) \ << "[info] " #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_define_ui) \ com::centreon::logging::temp_logger(com::centreon::logging::type_debug, \ verbose) \ << "[debug] " #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_define_ui) \ com::centreon::logging::temp_logger(com::centreon::logging::type_error, \ verbose) \ << "[error] " #endif // !CC_LOGGING_LOGGER_HH centreon-clib-21.04.2/inc/com/centreon/logging/syslogger.hh000066400000000000000000000031061407153644500235460ustar00rootroot00000000000000/* ** 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 CC_LOGGING_SYSLOGGER_HH #define CC_LOGGING_SYSLOGGER_HH #include #include "com/centreon/logging/backend.hh" #include "com/centreon/namespace.hh" CC_BEGIN() namespace logging { /** * @class syslogger syslogger.hh "com/centreon/logging/syslogger.hh" * @brief Log messages to syslog. */ class syslogger : public backend { public: syslogger(std::string const& id, int facility, bool is_sync = true, bool show_pid = true, time_precision show_timestamp = second, bool show_thread_id = false); ~syslogger() throw(); void close() throw(); void log(uint64_t types, uint32_t verbose, char const* msg, uint32_t size) throw(); void open(); void reopen(); private: syslogger(syslogger const& right); syslogger& operator=(syslogger const& right); int _facility; std::string _id; }; } CC_END() #endif // !CC_LOGGING_SYSLOGGER_HH centreon-clib-21.04.2/inc/com/centreon/logging/temp_logger.hh000066400000000000000000000033721407153644500240410ustar00rootroot00000000000000/* ** 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 CC_LOGGING_TEMP_LOGGER_HH #define CC_LOGGING_TEMP_LOGGER_HH #include #include "com/centreon/logging/engine.hh" #include "com/centreon/namespace.hh" #include "com/centreon/misc/stringifier.hh" CC_BEGIN() namespace logging { struct setprecision { setprecision(int val = -1) : precision(val) {} int precision; }; /** * @class temp_logger temp_logger.hh "com/centreon/logging/temp_logger.hh" * @brief Log messages. * * Used to buffering log messages before writing them into backends. */ class temp_logger { public: temp_logger(unsigned long long types, unsigned int verbose) throw(); temp_logger(temp_logger const& right); virtual ~temp_logger() throw(); temp_logger& operator=(temp_logger const& right); temp_logger& operator<<(setprecision const& obj) throw(); template temp_logger& operator<<(T obj) throw() { _buffer << obj; return (*this); } private: temp_logger& _internal_copy(temp_logger const& right); misc::stringifier _buffer; engine& _engine; unsigned long long _type; unsigned int _verbose; }; } CC_END() #endif // !CC_LOGGING_TEMP_LOGGER_HH centreon-clib-21.04.2/inc/com/centreon/misc/000077500000000000000000000000001407153644500205145ustar00rootroot00000000000000centreon-clib-21.04.2/inc/com/centreon/misc/argument.hh000066400000000000000000000041751407153644500226660ustar00rootroot00000000000000/* ** 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 CC_MISC_ARGUMENT_HH #define CC_MISC_ARGUMENT_HH #include #include "com/centreon/namespace.hh" CC_BEGIN() namespace misc { /** * @class argument argument.hh "com/centreon/misc/argument.hh" * @brief Define class argument for get options. * * This is an argument class. */ class argument { public: argument(std::string const& long_name = "", char name = '\0', std::string const& description = "", bool has_value = false, bool is_set = false, std::string const& value = ""); argument(argument const& right); ~argument() throw(); argument& operator=(argument const& right); bool operator==(argument const& right) const throw(); bool operator!=(argument const& right) const throw(); std::string const& get_description() const throw(); bool get_is_set() const throw(); bool get_has_value() const throw(); std::string const& get_long_name() const throw(); char get_name() const throw(); std::string const& get_value() const throw(); void set_description(std::string const& description); void set_is_set(bool val) throw(); void set_has_value(bool val) throw(); void set_long_name(std::string const& long_name); void set_name(char name); void set_value(std::string const& value); private: argument& _internal_copy(argument const& right); std::string _description; bool _is_set; bool _has_value; std::string _long_name; char _name; std::string _value; }; } CC_END() #endif // !CC_MISC_ARGUMENT_HH centreon-clib-21.04.2/inc/com/centreon/misc/command_line.hh000066400000000000000000000033601407153644500234640ustar00rootroot00000000000000/* ** 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 CC_MISC_COMMAND_LINE_HH #define CC_MISC_COMMAND_LINE_HH #include #include "com/centreon/namespace.hh" CC_BEGIN() namespace misc { /** * @class command_line command_line.hh "com/centreon/misc/command_line.hh" * @brief Provide method to split command line arguments into array. * * Command line is a simple way to split command line arguments * into array. */ class command_line { public: command_line(); command_line(char const* cmdline, unsigned int size = 0); command_line(std::string const& cmdline); command_line(command_line const& right); ~command_line() throw(); command_line& operator=(command_line const& right); bool operator==(command_line const& right) const throw(); bool operator!=(command_line const& right) const throw(); int get_argc() const throw(); char** get_argv() const throw(); void parse(char const* cmdline, unsigned int size = 0); void parse(std::string const& cmdline); private: void _internal_copy(command_line const& right); void _release(); int _argc; char** _argv; size_t _size; }; } CC_END() #endif // !CC_MISC_COMMAND_LINE_HH centreon-clib-21.04.2/inc/com/centreon/misc/get_options.hh000066400000000000000000000051471407153644500233760ustar00rootroot00000000000000/* ** 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 CC_MISC_GET_OPTIONS_HH #define CC_MISC_GET_OPTIONS_HH #include #include #include #include "com/centreon/namespace.hh" #include "com/centreon/misc/argument.hh" CC_BEGIN() namespace misc { /** * @class get_options get_options.hh "com/centreon/misc/get_options.hh" * @brief Parse command line arguments. * * This class provide a simple way to parse arguments with command * line style. */ class get_options { public: get_options(); get_options(get_options const& right); virtual ~get_options() throw(); get_options& operator=(get_options const& right); bool operator==(get_options const& right) const throw(); bool operator!=(get_options const& right) const throw(); std::map const& get_arguments() const throw(); argument& get_argument(char name); argument const& get_argument(char name) const; argument& get_argument(std::string const& long_name); argument const& get_argument(std::string const& long_name) const; std::vector const& get_parameters() const throw(); virtual std::string help() const; virtual std::string usage() const; void print_help() const; void print_usage() const; protected: get_options& _internal_copy(get_options const& right); void _parse_arguments(int argc, char** argv); void _parse_arguments(std::string const& command_line); virtual void _parse_arguments(std::vector const& args); std::map _arguments; std::vector _parameters; private: static void _array_to_vector(int argc, char** argv, std::vector& args); static bool _split_long(std::string const& line, std::string& key, std::string& value); static bool _split_short(std::string const& line, std::string& key, std::string& value); }; } CC_END() #endif // !CC_MISC_GET_OPTIONS_HH centreon-clib-21.04.2/inc/com/centreon/misc/stringifier.hh000066400000000000000000000052611407153644500233660ustar00rootroot00000000000000/* ** 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 CC_MISC_STRINGIFIER_HH #define CC_MISC_STRINGIFIER_HH #include #include #include "com/centreon/namespace.hh" CC_BEGIN() namespace misc { /** * @class stringifier stringifier.hh "com/centreon/misc/stringifier.hh" * @brief Provide method to converting data to string. * * Stringifier is a simple way to convert different data type to * C-String (null pointer terminate). */ class stringifier { public: stringifier(char const* buffer = NULL) throw(); stringifier(stringifier const& right); virtual ~stringifier() throw(); stringifier& operator=(stringifier const& right); stringifier& operator<<(bool b) throw(); stringifier& operator<<(char const* str) throw(); stringifier& operator<<(char c) throw(); stringifier& operator<<(double d) throw(); stringifier& operator<<(int i) throw(); stringifier& operator<<(long long ll) throw(); stringifier& operator<<(long l) throw(); stringifier& operator<<(std::string const& str) throw(); stringifier& operator<<(stringifier const& str) throw(); stringifier& operator<<(unsigned int u) throw(); stringifier& operator<<(unsigned long long ull) throw(); stringifier& operator<<(unsigned long ul) throw(); stringifier& operator<<(void const* p) throw(); stringifier& operator<<(std::thread::id const& p) throw(); stringifier& append(char const* str, unsigned int size) throw(); char const* data() const throw(); int precision() const throw(); void precision(int val) throw(); void reset() throw(); unsigned int size() const throw(); private: template stringifier& _insert(char const* format, T t) throw(); template stringifier& _insert(char const* format, unsigned int limit, T t) throw(); stringifier& _internal_copy(stringifier const& right); bool _realloc(unsigned int new_size) throw(); char* _buffer; unsigned int _current; int _precision; unsigned int _size; static unsigned int const _static_buffer_size = 1024; char _static_buffer[_static_buffer_size]; }; } CC_END() #endif // !CC_MISC_STRINGIFIER_HH centreon-clib-21.04.2/inc/com/centreon/namespace.hh000066400000000000000000000016111407153644500220350ustar00rootroot00000000000000/* ** 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 CC_NAMESPACE_HH #define CC_NAMESPACE_HH #ifndef CC_BEGIN #define CC_BEGIN() \ namespace com { \ namespace centreon { #endif // !CC_BEGIN #ifndef CC_END #define CC_END() \ } \ } #endif // !CC_END #endif // !CC_NAMESPACE_HH centreon-clib-21.04.2/inc/com/centreon/process.hh000066400000000000000000000062671407153644500215730ustar00rootroot00000000000000/* ** Copyright 2012-2013,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 CC_PROCESS_POSIX_HH #define CC_PROCESS_POSIX_HH #include #include #include #include #include "com/centreon/timestamp.hh" CC_BEGIN() class process_listener; class process_manager; /** * @class process process_posix.hh "com/centreon/process_posix.hh" * @brief Process execution class. * * Execute external process. */ class process { friend class process_manager; public: enum status { normal = 0, crash = 1, timeout = 2 }; enum stream { in = 0, out = 1, err = 2 }; private: std::string _buffer_err; std::string _buffer_out; pid_t (*_create_process)(char**, char**); mutable std::condition_variable _cv_buffer_err; mutable std::condition_variable _cv_buffer_out; mutable std::condition_variable _cv_process_running; const std::array _enable_stream; std::array _stream; timestamp _end_time; bool _is_timeout; process_listener* _listener; mutable std::mutex _lock_process; pid_t _process; timestamp _start_time; int _status; uint32_t _timeout; static void _close(int& fd) noexcept; static pid_t _create_process_with_setpgid(char** args, char** env); static pid_t _create_process_without_setpgid(char** args, char** env); static void _dev_null(int fd, int flags); static int _dup(int oldfd); static void _dup2(int oldfd, int newfd); bool _is_running() const noexcept; void _kill(int sig); static void _pipe(int fds[2]); ssize_t do_read(int fd); void do_close(int fd); static void _set_cloexec(int fd); public: process(process_listener* l = nullptr, bool in_stream = true, bool out_stream = true, bool err_stream = true); virtual ~process() noexcept; process(const process&) = delete; process& operator=(const process&) = delete; // void enable_stream(stream s, bool enable); timestamp const& end_time() const noexcept; void exec(char const* cmd, char** env = nullptr, uint32_t timeout = 0); void exec(std::string const& cmd, uint32_t timeout = 0); int exit_code() const noexcept; status exit_status() const noexcept; void kill(); void read(std::string& data); void read_err(std::string& data); void setpgid_on_exec(bool enable) noexcept; bool setpgid_on_exec() const noexcept; timestamp const& start_time() const noexcept; void terminate(); void wait() const; bool wait(uint32_t timeout) const; void update_ending_process(int status); uint32_t write(std::string const& data); uint32_t write(void const* data, uint32_t size); }; CC_END() #endif // !CC_PROCESS_POSIX_HH centreon-clib-21.04.2/inc/com/centreon/process_listener.hh000066400000000000000000000023731407153644500234720ustar00rootroot00000000000000/* ** Copyright 2012-2013,2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #ifndef CC_PROCESS_LISTENER_HH #define CC_PROCESS_LISTENER_HH #include "com/centreon/namespace.hh" #include "com/centreon/process.hh" CC_BEGIN() /** * @class process process_listener.hh "com/centreon/process_listener.hh" * @brief Notify process events. * * This class provide interface to notify process events. */ class process_listener { public: virtual ~process_listener() noexcept {} virtual void data_is_available(process& p) noexcept = 0; virtual void data_is_available_err(process& p) noexcept = 0; virtual void finished(process& p) noexcept = 0; }; CC_END() #endif // !CC_PROCESS_LISTENER_HH centreon-clib-21.04.2/inc/com/centreon/process_manager.hh000066400000000000000000000072171407153644500232610ustar00rootroot00000000000000/* ** Copyright 2012-2013,2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #ifndef CC_PROCESS_MANAGER_POSIX_HH #define CC_PROCESS_MANAGER_POSIX_HH #include #include #include #include #include #include #include #include #include #include "com/centreon/namespace.hh" CC_BEGIN() class process; class process_listener; /** * @class process_manager process_manager_posix.hh *"com/centreon/process_manager_posix.hh" * @brief This class manage process. * * This class is a singleton, it manages processes. When it is instantiated, it *starts a thread running the main loop inside the _run() method. This _run *method is executed with a condition variable _running_cv and a boolean *running. The constructor is released only when the boolean is set to true, *that is to say, the loop is really started. * * Once the loop is correctly started, the user can add to it processes. This *is done with the add() method. Since the main loop is running while we add a *process, a mutex _lock_processes is used. During the add action, * * A map _processes_fd is completed, this one returns a process knowing its *output fd or its error fd. * * If the process is configured with a timeout, the table _processes_timeout *is also filled ; with it, from a timeout, we can get its process. It is a *multimap. * * It is also asked the file descriptors list to be updated by setting the *_update boolean to true. * * The process is stored in the _processes_pid table, here it is stored by *pid. */ class process_manager { struct orphan { orphan(pid_t _pid = 0, int _status = 0) : pid(_pid), status(_status) {} pid_t pid; int status; }; /** * A boolean set to true when file descriptors list needs to be updated. */ std::atomic_bool _update; std::vector _fds; /** * Here is a boolean telling if the main loop is running or not. This variable * is set to true when the main loop starts and is set to false by the * process_manager destructor when we want to stop it. */ std::atomic_bool _running; std::mutex _running_m; std::condition_variable _running_cv; std::thread _thread; mutable std::mutex _lock_processes; std::unordered_map _processes_fd; std::deque _orphans_pid; std::unordered_map _processes_pid; std::multimap _processes_timeout; process_manager(); ~process_manager() noexcept; static void _close(int& fd) noexcept; void _close_stream(int fd) noexcept; void _erase_timeout(process* p); void _kill_processes_timeout() noexcept; uint32_t _read_stream(int fd) noexcept; void _run(); void _update_ending_process(process* p, int status) noexcept; void _update_list(); void _wait_orphans_pid() noexcept; void _wait_processes() noexcept; public: void add(process* p); static process_manager& instance(); process_manager& operator=(process_manager const& p) = delete; process_manager(process_manager const& p) = delete; }; CC_END() #endif // !CC_PROCESS_MANAGER_POSIX_HH centreon-clib-21.04.2/inc/com/centreon/task.hh000066400000000000000000000021611407153644500210440ustar00rootroot00000000000000/* ** 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 CC_TASK_HH #define CC_TASK_HH #include "com/centreon/namespace.hh" CC_BEGIN() /** * @class task task.hh "com/centreon/task.hh" * @brief Base for all task objects. * * This class is an interface for piece of code to needs to be * manage by the task manager. */ class task { public: task() = default; task(task const& t) = delete; virtual ~task() = default; task& operator=(task const& t) = delete; virtual void run() = 0; }; CC_END() #endif // !CC_TASK_HH centreon-clib-21.04.2/inc/com/centreon/task_manager.hh000066400000000000000000000046271407153644500225470ustar00rootroot00000000000000/* ** Copyright 2011-2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #ifndef CC_TASK_MANAGER_HH #define CC_TASK_MANAGER_HH #include #include #include #include #include #include #include "com/centreon/namespace.hh" #include "com/centreon/task.hh" #include "com/centreon/timestamp.hh" #include CC_BEGIN() class task_manager { struct internal_task { uint64_t id; bool is_runnable; bool should_delete; uint32_t interval; // When 0, this task is in auto_delete task* tsk; internal_task(task* tsk, uint64_t id, uint32_t interval, bool is_runnable, bool should_delete) : id{id}, is_runnable{is_runnable}, should_delete{should_delete}, interval{interval}, tsk{tsk} {} internal_task() = delete; }; uint64_t _current_id; bool _exit; std::vector _workers; mutable std::mutex _tasks_m; std::multimap _tasks; mutable std::mutex _queue_m; mutable std::condition_variable _queue_cv; std::deque _queue; void _enqueue(internal_task* t); void _wait_for_queue_empty() const; public: task_manager(uint32_t max_thread_count = 0); ~task_manager(); uint64_t add(task* t, timestamp const& when, bool is_runnable = false, bool should_delete = false); uint64_t add(task* t, timestamp const& when, uint32_t interval, bool is_runnable = false, bool should_delete = false); timestamp next_execution_time() const; uint32_t remove(task* t); bool remove(uint64_t id); uint32_t execute(timestamp const& now = timestamp::now()); }; CC_END() #endif // ! CC_TASK_MANAGER_HH centreon-clib-21.04.2/inc/com/centreon/timestamp.hh000066400000000000000000000043041407153644500221060ustar00rootroot00000000000000/* ** 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 CC_TIMESTAMP_HH #define CC_TIMESTAMP_HH #include #include #include "com/centreon/namespace.hh" CC_BEGIN() /** * @class timestamp timestamp.hh "com/centreon/timestamp.hh" * @brief Provide time management. * * Allow to manage time easily. */ class timestamp { private: time_t _secs; uint32_t _usecs; public: timestamp(time_t secs = 0, int32_t usecs = 0); timestamp(const timestamp& right); ~timestamp() noexcept = default; timestamp& operator=(const timestamp& right); bool operator==(const timestamp& right) const noexcept; bool operator!=(const timestamp& right) const noexcept; bool operator<(const timestamp& right) const noexcept; bool operator<=(const timestamp& right) const noexcept; bool operator>(const timestamp& right) const noexcept; bool operator>=(const timestamp& right) const noexcept; timestamp operator+(const timestamp& right) const; timestamp operator-(const timestamp& right) const; timestamp& operator+=(const timestamp& right); timestamp& operator-=(const timestamp& right); void add_mseconds(int32_t msecs); void add_seconds(time_t secs) noexcept; void add_useconds(int32_t usecs); void clear() noexcept; static timestamp max_time() noexcept; static timestamp min_time() noexcept; static timestamp now() noexcept; void sub_mseconds(int32_t msecs); void sub_seconds(time_t secs) noexcept; void sub_useconds(int32_t usecs); int64_t to_mseconds() const noexcept; time_t to_seconds() const noexcept; int64_t to_useconds() const noexcept; }; CC_END() #endif // !CC_TIMESTAMP_HH centreon-clib-21.04.2/inc/com/centreon/unique_array_ptr.hh000066400000000000000000000047401407153644500235000ustar00rootroot00000000000000/* ** 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 CC_UNIQUE_ARRAY_PTR_HH #define CC_UNIQUE_ARRAY_PTR_HH #include #include "com/centreon/namespace.hh" CC_BEGIN() /** * @class unique_array_ptr unique_array_ptr.hh * @brief Similar to unique_ptr for arrays. * * Provide similar feature as unique_ptr but for array pointers. */ template class unique_array_ptr { private: T* _ptr; public: /** * Constructor. * * @param[in] t Array pointer. */ unique_array_ptr(T* t = NULL) : _ptr(t) {} /** * Copy constructor. * * @param[in] uap Object to copy. */ unique_array_ptr(unique_array_ptr& uap) : _ptr(uap._ptr) { uap._ptr = NULL; } /** * Destructor. */ ~unique_array_ptr() { delete[] _ptr; } /** * Assignment operator. * * @param[in] uap Object to copy. * * @return This object. */ unique_array_ptr& operator=(unique_array_ptr& uap) { if (&uap != this) { _ptr = uap._ptr; uap._ptr = NULL; } return (*this); } /** * Dereferencing pointer. * * @return Dereferenced pointer. */ T& operator*() { return (*_ptr); } /** * Array access operator. * * @param[in] idx Index in array. * * @return Element at position idx. */ T& operator[](unsigned int idx) { return (_ptr[idx]); } /** * Get the pointer associated with this object. * * @return Pointer associated with this object. */ T* get() const { return (_ptr); } /** * Release the associated pointer and release it. * * @return Pointer associated with this object. */ T* release() { T* tmp(_ptr); _ptr = NULL; return (tmp); } /** * Reset this automatic pointer. * * @param[in] ptr New pointer (can be NULL). */ void reset(T* t = NULL) { delete[] _ptr; _ptr = t; return; } }; CC_END() #endif // !CC_UNIQUE_ARRAY_PTR_HH centreon-clib-21.04.2/inc/com/centreon/unordered_hash.hh000066400000000000000000000105721407153644500231010ustar00rootroot00000000000000/* ** Copyright 2012-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 CC_UNORDERED_HASH_HH #define CC_UNORDERED_HASH_HH #if __cplusplus == 201103L #define CXX0X_UNORDERED 1 #elif defined(__clang__) #if __has_feature(cxx_variadic_templates) #define TR1_UNORDERED 1 #endif // cxx_variadic_templates. #elif defined(__GNUC__) && __GNUC__ >= 4 #define TR1_UNORDERED 1 #endif // C++0x, tr1 // Used c++0x implementation. #ifdef CXX0X_UNORDERED #include #include #include #include #define umap std::unordered_map #define umultimap std::unordered_multimap #define uset std::unordered_set #define umultiset std::unordered_multiset // Missing std::pair hash. namespace std { template struct hash > { std::size_t operator()(std::pair const& p) const { std::hash h1; std::hash h2; return h1(p.first) ^ h2(p.second); } }; } // namespace std // Used tr1 implementation. #elif defined(TR1_UNORDERED) #include #include #include #include #define umap std::tr1::unordered_map #define umultimap std::tr1::unordered_multimap #define uset std::tr1::unordered_set #define umultiset std::tr1::unordered_multiset // Missing std::pair hash. namespace std { namespace tr1 { template struct hash > { std::size_t operator()(std::pair const& p) const { std::tr1::hash h1; std::tr1::hash h2; return h1(p.first) ^ h2(p.second); } }; } // namespace tr1 } // namespace std namespace std { // Missing equal operator for unrodered map on tr1. template bool operator==(umap const& lhs, umap const& rhs) { if (lhs.size() != rhs.size()) return false; for (typename umap::const_iterator it(lhs.begin()), end(lhs.end()); it != end; ++it) { typename umap::const_iterator it_find( rhs.find(it->first)); if (it_find == rhs.end() || it_find->second != it->second) return false; } return true; } // Missing not equal operator for unrodered map on tr1. template bool operator!=(umap const& lhs, umap const& rhs) { return !operator==(lhs, rhs); } // Missing equal operator for unrodered multimap on tr1. template bool operator==(umultimap const& lhs, umultimap const& rhs) { if (lhs.size() != rhs.size()) return false; for (typename umap::const_iterator it(lhs.begin()), end(lhs.end()); it != end; ++it) { bool find(false); for (typename umap::const_iterator it_find(rhs.find(it->first)), end(rhs.end()); it_find != end && it_find->first == it->first; ++it_find) { if (it_find->second == it->second) { find = true; break; } } if (!find) return false; } return true; } // Missing not equal operator for unrodered multimap on tr1. template bool operator!=(umultimap const& lhs, umultimap const& rhs) { return !operator==(lhs, rhs); } } // namespace std // Used std implementation. #else #include #include #define umap std::map #define umultimap std::multimap #define uset std::set #define umultiset std::multiset #endif // C++0X, tr1 or std #endif // !CC_UNORDERED_HASH_HH centreon-clib-21.04.2/script/000077500000000000000000000000001407153644500157215ustar00rootroot00000000000000centreon-clib-21.04.2/script/centreon-clib.pc.in000066400000000000000000000016261407153644500214030ustar00rootroot00000000000000## ## 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 ## libdir=@PREFIX_LIB@ includedir=@PREFIX_INC@ Name: Centreon Clib Description: Centreon Clib is common library for Centreon products. Version: @CLIB_VERSION@ URL: http://forge.centreon.com/projects/centreon-clib Cflags: -I${includedir} Libs: ${libdir}/libcentreon_clib.so centreon-clib-21.04.2/sonar-project.properties000066400000000000000000000005631407153644500213250ustar00rootroot00000000000000# project sonar.projectKey={PROJECT_TITLE} sonar.projectName={PROJECT_NAME} sonar.projectVersion={PROJECT_VERSION} sonar.sources=. sonar.tsql.file.suffixes=sql,tsql sonar.plsql.file.suffixes=pks,pkb # mandatory to not fail the builds until build-wrapper is installed and sources are compiled sonar.c.file.suffixes=- sonar.cpp.file.suffixes=- sonar.objc.file.suffixes=- centreon-clib-21.04.2/src/000077500000000000000000000000001407153644500152045ustar00rootroot00000000000000centreon-clib-21.04.2/src/clib/000077500000000000000000000000001407153644500161155ustar00rootroot00000000000000centreon-clib-21.04.2/src/clib/CMakeLists.txt000066400000000000000000000017521407153644500206620ustar00rootroot00000000000000## ## 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 ## # Set directories. set(INC_DIR "${INC_DIR}/clib") set(SRC_DIR "${SRC_DIR}/clib") # Generate version header. configure_file( "${INC_DIR}/version.hh.in" "${INC_DIR}/version.hh") # Set sources. set( SOURCES ${SOURCES} "${SRC_DIR}/version.cc" PARENT_SCOPE ) # Set headers. set( HEADERS ${HEADERS} "${INC_DIR}/version.hh" PARENT_SCOPE ) centreon-clib-21.04.2/src/clib/version.cc000066400000000000000000000024141407153644500201120ustar00rootroot00000000000000/* ** 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/clib/version.hh" using namespace com::centreon::clib; /** * Get version major. * * @return Centreon Clib version major. */ unsigned int version::get_major() throw() { return (major); } /** * Get version minor. * * @return Centreon Clib version minor. */ unsigned int version::get_minor() throw() { return (minor); } /** * Get version patch. * * @return Centreon Clib version patch. */ unsigned int version::get_patch() throw() { return (patch); } /** * Get version string. * * @return Centreon Clib version as string. */ char const* version::get_string() throw() { return (version::string); } centreon-clib-21.04.2/src/exceptions/000077500000000000000000000000001407153644500173655ustar00rootroot00000000000000centreon-clib-21.04.2/src/exceptions/CMakeLists.txt000066400000000000000000000017141407153644500221300ustar00rootroot00000000000000## ## 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 ## # Set directories. set(SRC_DIR "${SRC_DIR}/exceptions") set(INC_DIR "${INC_DIR}/exceptions") # Set sources. set( SOURCES ${SOURCES} "${SRC_DIR}/basic.cc" "${SRC_DIR}/interruption.cc" PARENT_SCOPE ) # Set headers. set( HEADERS ${HEADERS} "${INC_DIR}/basic.hh" "${INC_DIR}/interruption.hh" PARENT_SCOPE ) centreon-clib-21.04.2/src/exceptions/basic.cc000066400000000000000000000037361407153644500207660ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/misc/stringifier.hh" #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Default constructor. */ basic::basic() {} /** * Constructor with debugging informations. * * @param[in] file The file from calling this object. * @param[in] function The function from calling this object. * @param[in] line The line from calling this object. */ basic::basic(char const* file, char const* function, int line) { *this << "[" << file << ":" << line << "(" << function << ")] "; } /** * Copy constructor. * * @param[in] other Object to copy. */ basic::basic(basic const& other) : std::exception(other) { _internal_copy(other); } /** * Destructor. */ basic::~basic() throw() {} /** * Assignment operator. * * @param[in] other Object to copy. * * @return This object. */ basic& basic::operator=(basic const& other) { if (this != &other) { std::exception::operator=(other); _internal_copy(other); } return (*this); } /** * Get the basic message. * * @return Basic message. */ char const* basic::what() const throw() { return (_buffer.data()); } /** * Internal copy method. * * @param[in] other Object to copy. */ void basic::_internal_copy(basic const& other) { _buffer = other._buffer; return; } centreon-clib-21.04.2/src/exceptions/interruption.cc000066400000000000000000000030741407153644500224420ustar00rootroot00000000000000/* ** 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/exceptions/interruption.hh" using namespace com::centreon::exceptions; /** * Default constructor. */ interruption::interruption() {} /** * Constructor with debugging informations. * * @param[in] file The file in which this object is created. * @param[in] function The function creating this object. * @param[in] line The line in the file creating this object. */ interruption::interruption(char const* file, char const* function, int line) : basic(file, function, line) {} /** * Copy constructor. * * @param[in] other Object to copy. */ interruption::interruption(interruption const& other) : basic(other) {} /** * Destructor. */ interruption::~interruption() throw() {} /** * Assignment operator. * * @param[in] other Object to copy. * * @return This object. */ interruption& interruption::operator=(interruption const& other) { basic::operator=(other); return (*this); } centreon-clib-21.04.2/src/handle_action.cc000066400000000000000000000043241407153644500203060ustar00rootroot00000000000000/* ** 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/handle_action.hh" #include #include "com/centreon/handle.hh" #include "com/centreon/handle_listener.hh" using namespace com::centreon; /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. * * @param[in] h Handle. * @param[in] hl Listener * @param[in] is_threadable Can this task be threaded ? */ handle_action::handle_action(handle* h, handle_listener* hl, bool is_threadable) : _action(none), _h(h), _hl(hl), _is_threadable(is_threadable) {} /** * Destructor. */ handle_action::~handle_action() noexcept {} /** * Is this task threadable ? * * @return true if the task is threadable. */ bool handle_action::is_threadable() const noexcept { return _is_threadable; } /** * Get the handle. * * @return Handle. */ handle* handle_action::get_handle() const noexcept { return _h; } /** * Get the listener. * * @return Listener. */ handle_listener* handle_action::get_handle_listener() const noexcept { return _hl; } /** * Run the task. */ void handle_action::run() { action a = _action; _action = none; switch (a) { case error: _hl->error(*_h); break; case read: _hl->read(*_h); break; case write: _hl->write(*_h); break; default: break; } } /** * Set action. * * @param[in] a Action to perform. */ void handle_action::set_action(action a) noexcept { _action = a; } centreon-clib-21.04.2/src/handle_manager.cc000066400000000000000000000164571407153644500204550ustar00rootroot00000000000000/* ** 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/handle_manager.hh" #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/handle_action.hh" #include "com/centreon/handle_listener.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; /** * Constructor. * * @param[in] tm Task manager. */ handle_manager::handle_manager(task_manager* tm) : _array(nullptr), _recreate_array{false}, _task_manager(tm) {} /** * Destructor. */ handle_manager::~handle_manager() noexcept { for (auto it = _handles.begin(), end = _handles.end(); it != end; ++it) try { if (_task_manager) _task_manager->remove(it->second); delete it->second; } catch (...) { } delete[] _array; } /** * Add a new handle into the handle manager. * * @param[in] h The handle to listen. * @param[in] hl The listener that receives notifications. * @param[in] is_threadable True if the handle listener if allowed to * run simultaneously with other listeners. */ void handle_manager::add(handle* h, handle_listener* hl, bool is_threadable) { // Check parameters. if (!h) throw(basic_error() << "attempt to add null handle in handle manager"); if (!hl) throw(basic_error() << "attempt to add null listener in handle manager"); // Check native handle. native_handle nh(h->get_native_handle()); if (nh == native_handle_null) throw basic_error() << "attempt to add handle with invalid native " "handle in the handle manager"; // Check that handle isn't already registered. if (_handles.find(nh) == _handles.end()) { handle_action* ha = new handle_action(h, hl, is_threadable); std::pair item(nh, ha); _handles.insert(item); _recreate_array = true; } else throw basic_error() << "attempt to add handle " "already monitored by handle manager"; } /** * Set a new task manager. * * @param[in] tm Task manager. */ void handle_manager::link(task_manager* tm) { // Remove old tasks. if (_task_manager) for (auto it = _handles.begin(), end = _handles.end(); it != end; ++it) try { _task_manager->remove(it->second); } catch (...) { } // Set new task manager. _task_manager = tm; } /** * Remove a specific handle. * * @param[in] h The handle to remove. * * @return True if the handle was removed, false otherwise. */ bool handle_manager::remove(handle* h) { // Beware null pointer. if (!h) return false; // Search handle by native handle. std::map::iterator it( _handles.find(h->get_native_handle())); if ((it == _handles.end()) || it->second->get_handle() != h) return false; if (_task_manager) _task_manager->remove(it->second); delete it->second; _handles.erase(it); _recreate_array = true; return true; } /** * Remove all occurence of a specific handle listener. * * @param[in] hl The handle listener to remove. * * @return The number of items removed. */ unsigned int handle_manager::remove(handle_listener* hl) { // Beware null pointer. if (!hl) return 0; // Loop through map. unsigned int count_erase(0); for (std::map::iterator it(_handles.begin()), next(it), end(_handles.end()); it != end; it = next) { ++(next = it); if (it->second->get_handle_listener() == hl) { if (_task_manager) _task_manager->remove(it->second); delete it->second; _handles.erase(it); ++count_erase; } } _recreate_array = true; return count_erase; } /** * Multiplex input/output and notify handle listeners if necessary and * execute the task manager. */ void handle_manager::multiplex() { // Check that task manager is present. if (!_task_manager) throw basic_error() << "cannot multiplex handles with no task manager"; // Create or update pollfd. _setup_array(); // Determined the poll timeout with the next execution time. int timeout(-1); timestamp now(timestamp::now()); timestamp next(_task_manager->next_execution_time()); if (!_handles.size() && next == timestamp::max_time()) return; if (next <= now) timeout = 0; else if (next == timestamp::max_time()) timeout = -1; else timeout = next.to_mseconds() - now.to_mseconds(); // Wait events. int ret = _poll(_array, _handles.size(), timeout); if (ret == -1) { char const* msg(strerror(errno)); throw basic_error() << "handle multiplexing failed: " << msg; } // Dispatch events. int nb_check(0); for (uint32_t i = 0, end = _handles.size(); i < end && nb_check < ret; ++i) { if (!_array[i].revents) { continue; } handle_action* task(_handles[_array[i].fd]); if (_array[i].revents & (POLLERR | POLLNVAL)) { task->set_action(handle_action::error); } else if (_array[i].revents & POLLOUT) { task->set_action(handle_action::write); } else if (_array[i].revents & (POLLHUP | POLLIN | POLLPRI)) { task->set_action(handle_action::read); } _task_manager->add(task, now, task->is_threadable()); ++nb_check; } // Flush task needs to be execute at this time. _task_manager->execute(timestamp::now()); } /** * Wrapper for poll system function. * @remark This function is static. * * @param[in] fds Set of file descriptors to be monitored. * @param[in] nfds The number of file descriptors to be monitored. * @param[in] timeout Specifies time limit for which poll will block, * in milliseconds. * * @return A positive number on success, 0 if timeout, -1 on error and * errno was set. */ int handle_manager::_poll(pollfd* fds, nfds_t nfds, int timeout) noexcept { int ret(0); do { ret = poll(fds, nfds, timeout); } while (ret == -1 && errno == EINTR); return ret; } /** * Create or update internal pollfd array. */ void handle_manager::_setup_array() { // Should we reallocate array ? if (_recreate_array) { // Remove old array. delete[] _array; // Is there any handle ? if (_handles.empty()) _array = nullptr; else { _array = new pollfd[_handles.size()]; _recreate_array = false; } } // Update the pollfd. nfds_t nfds(0); for (auto it = _handles.begin(), end = _handles.end(); it != end; ++it) { _array[nfds].fd = it->first; _array[nfds].events = 0; _array[nfds].revents = 0; handle* h(it->second->get_handle()); handle_listener* hl(it->second->get_handle_listener()); if (hl->want_read(*h)) _array[nfds].events |= POLLIN | POLLPRI; if (hl->want_write(*h)) _array[nfds].events |= POLLOUT; ++nfds; } } centreon-clib-21.04.2/src/io/000077500000000000000000000000001407153644500156135ustar00rootroot00000000000000centreon-clib-21.04.2/src/io/CMakeLists.txt000066400000000000000000000020101407153644500203440ustar00rootroot00000000000000## ## 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 ## # Set directories. set(SRC_DIR "${SRC_DIR}/io") set(INC_DIR "${INC_DIR}/io") # Set sources. set( SOURCES ${SOURCES} "${SRC_DIR}/directory_entry.cc" "${SRC_DIR}/file_entry.cc" "${SRC_DIR}/file_stream.cc" PARENT_SCOPE ) # Set headers. set( HEADERS ${HEADERS} "${INC_DIR}/directory_entry.hh" "${INC_DIR}/file_entry.hh" "${INC_DIR}/file_stream.hh" PARENT_SCOPE ) centreon-clib-21.04.2/src/io/directory_entry.cc000066400000000000000000000101471407153644500213520ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/directory_entry.hh" using namespace com::centreon::io; /** * Constructor. * * @param[in] path The directory path. */ directory_entry::directory_entry(char const* path) : _entry(path) {} /** * Constructor. * * @param[in] path The directory path. */ directory_entry::directory_entry(std::string const& path) : _entry(path) {} /** * Copy constructor. * * @param[in] right The object to copy. */ directory_entry::directory_entry(directory_entry const& right) { _internal_copy(right); } /** * Copy operator. * * @param[in] right The object to copy. * * @return This object. */ directory_entry& directory_entry::operator=(directory_entry const& right) { _internal_copy(right); return *this; } /** * Equal operator. * * @param[in] right The object to compare. * * @return True if is the same object, owtherwise false. */ bool directory_entry::operator==(directory_entry const& right) const noexcept { return _entry == right._entry; } /** * Not equal operator. * * @param[in] right The object to compare. * * @return True if is not the same object, owtherwise false. */ bool directory_entry::operator!=(directory_entry const& right) const noexcept { return !operator==(right); } /** * Destructor. */ directory_entry::~directory_entry() noexcept {} /** * Get the current directory path. * * @return The current directory path. */ std::string directory_entry::current_path() { char* buffer(getcwd(NULL, 0)); if (!buffer) throw(basic_error() << "current path failed"); std::string path(buffer); free(buffer); return path; } /** * Get the directory information. * * @return The directory entry. */ file_entry const& directory_entry::entry() const noexcept { return _entry; } /** * Get the list of all entry into a directory. * * @param[in] filter An optional filter. * * @return The file entry list. */ std::list const& directory_entry::entry_list( std::string const& filter) { _entry_lst.clear(); char const* filter_ptr(filter.empty() ? NULL : filter.c_str()); DIR* dir(opendir(_entry.path().c_str())); if (!dir) { char const* msg(strerror(errno)); throw(basic_error() << "open directory failed: " << msg); } dirent entry; dirent* result; while (true) { if (readdir_r(dir, &entry, &result)) { closedir(dir); throw(basic_error() << "parse directory failed"); } if (!result) break; if (!filter_ptr || _nmatch(entry.d_name, filter_ptr)) _entry_lst.push_back(file_entry(_entry.path() + "/" + entry.d_name)); } closedir(dir); return _entry_lst; } /** * Internal copy. * * @param[in] right The object to copy. */ void directory_entry::_internal_copy(directory_entry const& right) { if (this != &right) { _entry = right._entry; _entry_lst = right._entry_lst; } } /** * Check if a string match a pattern. * * @param[in] str The string to check. * @param[in] pattern The partter to match. * * @return 1 on success, otherwiswe 0. */ int directory_entry::_nmatch(char const* str, char const* pattern) { if (!*str && !*pattern) return 1; if (*str == *pattern) return _nmatch(str + 1, pattern + 1); return (*pattern == '*' ? (*str ? _nmatch(str + 1, pattern) : 0) + _nmatch(str, pattern + 1) : 0); } centreon-clib-21.04.2/src/io/file_entry.cc000066400000000000000000000107251407153644500202670ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_entry.hh" using namespace com::centreon::io; /** * Constructor. * * @param[in] path The file path. */ file_entry::file_entry(char const* path) : _path(path ? path : "") { refresh(); } /** * Constructor overload. */ file_entry::file_entry(std::string const& path) : _path(path) { refresh(); } /** * Copy constructor. * * @param[in] right The object to copy. */ file_entry::file_entry(file_entry const& right) { _internal_copy(right); } /** * Destructor. */ file_entry::~file_entry() noexcept {} /** * Copy operator. * * @param[in] right The object to copy. * * @return This object. */ file_entry& file_entry::operator=(file_entry const& right) { _internal_copy(right); return *this; } /** * Equal operator. * * @param[in] right The object to compare. * * @return True if is the same object, otherwise false. */ bool file_entry::operator==(file_entry const& right) const noexcept { return (_sbuf.st_dev == right._sbuf.st_dev && _sbuf.st_ino == right._sbuf.st_ino); } /** * Not equal operator. * * @param[in] right The object to compare. * * @return True if is not the same object, otherwise false. */ bool file_entry::operator!=(file_entry const& right) const noexcept { return !operator==(right); } /** * Get the file name without extention. * * @return The file name without extention. */ std::string file_entry::base_name() const { std::string name; name = file_name(); size_t pos(name.find_last_of('.')); if (pos != 0 && pos != std::string::npos) name.erase(pos); return name; } /** * Get the directory path. * * @return The directory path of this file. */ std::string file_entry::directory_name() const { std::string retval{dirname(const_cast(_path.c_str()))}; return retval; } /** * Get the file name without extention. * * @return The file name without extention. */ std::string file_entry::file_name() const { std::string retval{basename(const_cast(_path.c_str()))}; return retval; } /** * Check if this file is a directory. * * @return True if this file is a directory, otherwise false. */ bool file_entry::is_directory() const noexcept { return (_sbuf.st_mode & S_IFMT) == S_IFDIR; } /** * Check if this file is a symbolic link. * * @return True if this file is a symbolic link, otherwise false. */ bool file_entry::is_link() const noexcept { return (_sbuf.st_mode & S_IFMT) == S_IFLNK; } /** * Check if this file is regular. * * @return True if this file is regular, otherwise false. */ bool file_entry::is_regular() const noexcept { return (_sbuf.st_mode & S_IFMT) == S_IFREG; } /** * Get the file path. * * @return The path. */ std::string const& file_entry::path() const noexcept { return _path; } /** * Set the file entry path. * * @param[in] path The file entry path. */ void file_entry::path(char const* path) { _path = path ? path : ""; refresh(); } /** * Set the file entry path. * * @param[in] path The file entry path. */ void file_entry::path(std::string const& path) { _path = path; refresh(); } /** * Reload file information. */ void file_entry::refresh() { if (_path.empty()) memset(&_sbuf, 0, sizeof(_sbuf)); else if (stat(_path.c_str(), &_sbuf)) { char const* msg(strerror(errno)); throw(basic_error() << "get file information failed: " << msg); } } /** * Get the file size. * * @return The file size. */ unsigned long long file_entry::size() const noexcept { return _sbuf.st_size; } /** * Internal copy. * * @param[in] right The object to copy. */ void file_entry::_internal_copy(file_entry const& right) { if (this != &right) { _path = right._path; memcpy(&_sbuf, &right._sbuf, sizeof(_sbuf)); } } centreon-clib-21.04.2/src/io/file_stream.cc000066400000000000000000000170451407153644500204230ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include #include #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_stream.hh" using namespace com::centreon::io; /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. * * @param[in] stream Associated stream. * @param[in] auto_close Should the class automatically close the * stream ? */ file_stream::file_stream(FILE* stream, bool auto_close) : _auto_close(auto_close), _stream(stream) {} /** * Destructor. */ file_stream::~file_stream() throw() { close(); } /** * Close file stream. */ void file_stream::close() { if (_stream) { if (_auto_close) fclose(_stream); _stream = NULL; } return; } /** * Copy source file to the destination file. * * @param[in] src The path of the source file. * @param[in] dst The path of the destination file. */ void file_stream::copy(char const* src, char const* dst) { std::ifstream source(src, std::ios::binary); std::ofstream dest(dst, std::ios::binary); dest << source.rdbuf(); } /** * Overload of copy method. */ void file_stream::copy(std::string const& src, std::string const& dst) { copy(src.c_str(), dst.c_str()); } /** * Check for file existance. * * @param[in] path File to check. * * @return true if file exists. */ bool file_stream::exists(char const* path) { if (!path) return false; return !access(path, F_OK); } /** * Overload of exists method. */ bool file_stream::exists(std::string const& path) { return exists(path.c_str()); } /** * Flush the file to disk. */ void file_stream::flush() { if (fflush(_stream)) { char const* msg(strerror(errno)); throw(basic_error() << "cannot flush stream: " << msg); } return; } /** * Get native handle. * * @return Native handle. */ com::centreon::native_handle file_stream::get_native_handle() { native_handle retval; if (!_stream) retval = native_handle_null; else { retval = fileno(_stream); if (retval < 0) { char const* msg(strerror(errno)); throw(basic_error() << "could not get native handle from " "file stream: " << msg); } } return retval; } /** * Open file. */ void file_stream::open(char const* path, char const* mode) { if (!path) throw(basic_error() << "invalid argument path: null pointer"); if (!mode) throw(basic_error() << "invalid argument mode: null pointer"); close(); _auto_close = true; _stream = fopen(path, mode); if (!_stream) { char const* msg(strerror(errno)); throw(basic_error() << "could not open file '" << path << "': " << msg); } int fd(fileno(_stream)); int flags(0); while ((flags = fcntl(fd, F_GETFD)) < 0) { if (errno == EINTR) continue; return; } int ret(0); while ((ret = fcntl(fd, F_SETFD, flags | FD_CLOEXEC)) < 0) { if (errno == EINTR) continue; return; } return; } /** * Overload of open method. */ void file_stream::open(std::string const& path, char const* mode) { open(path.c_str(), mode); } /** * Read data from stream. * * @param[out] data Destination buffer. * @param[in] size Maximum number of bytes to read. * * @return Number of bytes actually read. */ unsigned long file_stream::read(void* data, unsigned long size) { if (!_stream) throw(basic_error() << "attempt to read from closed file stream"); if (!data || !size) throw(basic_error() << "attempt to read from " "file stream but do not except any result"); ssize_t rb(::read(get_native_handle(), data, size)); if (rb < 0) { char const* msg(strerror(errno)); throw(basic_error() << "could not read from file stream: " << msg); } return static_cast(rb); } /** * Remove a file. * * @param[in] path Path to the file to remove. * * @return true if file was successfully removed. */ bool file_stream::remove(char const* path) { if (!path) return false; return !::remove(path); } /** * Overload of remove method. */ bool file_stream::remove(std::string const& path) { return remove(path.c_str()); } /** * Rename a file. * * @param[in] old_filename The current filename. * @param[in] new_filename The new filename. * * @return True on success, otherwise false. */ bool file_stream::rename(char const* old_filename, char const* new_filename) { if (!old_filename || !new_filename) return false; bool ret(!::rename(old_filename, new_filename)); if (!ret) { if (errno != EXDEV) return false; try { file_stream file_read(NULL, true); file_read.open(old_filename, "r"); file_stream file_write(NULL, true); file_write.open(new_filename, "w"); char data[4096]; unsigned int len; while ((len = file_read.read(data, sizeof(data)))) file_write.write(data, len); } catch (...) { return false; } } return true; } /** * Overload of rename method. */ bool file_stream::rename(std::string const& old_filename, std::string const& new_filename) { return rename(old_filename.c_str(), new_filename.c_str()); } /** * Get file size. * * @return File size. */ unsigned long file_stream::size() { // Get original offset. long original_offset(ftell(_stream)); if (-1 == original_offset) { char const* msg(strerror(errno)); throw(basic_error() << "cannot tell position within file: " << msg); } // Seek to end of file. if (fseek(_stream, 0, SEEK_END)) { char const* msg(strerror(errno)); throw(basic_error() << "cannot seek to end of file: " << msg); } // Get position (size). long size(ftell(_stream)); if (size < 0) { char const* msg(strerror(errno)); throw(basic_error() << "cannot get file size: " << msg); } // Get back to original position. fseek(_stream, original_offset, SEEK_SET); return size; } /** * Get temporary name. * * @return Temporary name. */ char* file_stream::temp_path() { char* ret(::tmpnam(static_cast(NULL))); if (!ret) throw basic_error() << "could not generate temporary file name"; return ret; } /** * Write data to stream. * * @param[in] data Buffer. * @param[in] size Maximum number of bytes to write. * * @return Number of bytes actually written. */ unsigned long file_stream::write(void const* data, unsigned long size) { if (!_stream) throw(basic_error() << "attempt to write to a closed file stream"); if (!data || !size) throw(basic_error() << "attempt to write no data to file stream"); ssize_t wb(::write(get_native_handle(), data, size)); if (wb <= 0) { char const* msg(strerror(errno)); throw(basic_error() << "could not write to file stream: " << msg); } return static_cast(wb); } centreon-clib-21.04.2/src/library.cc000066400000000000000000000054671407153644500171730ustar00rootroot00000000000000/* ** 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/library.hh" #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon; /** * Default constructor. */ library::library(std::string const& filename) : _filename(filename), _handle(NULL) {} /** * Destructor. */ library::~library() noexcept { try { unload(); } catch (...) { } } /** * Get the library filename. * * @return The filename. */ std::string const& library::filename() const noexcept { return _filename; } /** * Check if the library has loaded. * * @return True if the library is loaded, otherwise false. */ bool library::is_loaded() const noexcept { return _handle; } /** * Load the library. */ void library::load() { if (_handle) return; if (!(_handle = dlopen(_filename.c_str(), RTLD_LAZY | RTLD_GLOBAL))) throw basic_error() << "load library failed: " << dlerror(); } /** * Return the data symbol address. * * @param[in] symbol The exported symbol. * * @return Symbol address. */ void* library::resolve(char const* symbol) { if (!_handle) throw basic_error() << "could not find symbol '" << symbol << "': library not loaded"; dlerror(); void* sym(dlsym(_handle, symbol)); if (!sym) { char const* msg(dlerror()); throw basic_error() << "could not find symbol '" << symbol << "': " << (msg ? msg : "unknown error"); } return sym; } /** * Overloaded method. * * @see resolve */ void* library::resolve(std::string const& symbol) { return resolve(symbol.c_str()); } /** * Return the process symbol address. * * @param[in] symbol Symbol to resolve. * * @return Symbol address. */ void (*library::resolve_proc(char const* symbol))() { union { void (*func)(); void* data; } type; type.data = resolve(symbol); return type.func; } /** * Overloaded method. * * @see resolve_proc */ void (*library::resolve_proc(std::string const& symbol))() { return resolve_proc(symbol.c_str()); } /** * Unload the library. */ void library::unload() { if (!_handle) return; if (dlclose(_handle)) throw basic_error() << "unload library failed: " << dlerror(); _handle = nullptr; } centreon-clib-21.04.2/src/logging/000077500000000000000000000000001407153644500166325ustar00rootroot00000000000000centreon-clib-21.04.2/src/logging/CMakeLists.txt000066400000000000000000000023571407153644500214010ustar00rootroot00000000000000## ## 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 ## # Set directories. set(SRC_DIR "${SRC_DIR}/logging") set(INC_DIR "${INC_DIR}/logging") # Platform-specific files. set(SPECIFIC_SOURCES "${SRC_DIR}/syslogger.cc" ) set(SPECIFIC_HEADERS "${INC_DIR}/syslogger.hh" ) # Set sources. set( SOURCES ${SOURCES} ${SPECIFIC_SOURCES} "${SRC_DIR}/backend.cc" "${SRC_DIR}/engine.cc" "${SRC_DIR}/file.cc" "${SRC_DIR}/temp_logger.cc" PARENT_SCOPE ) # Set headers. set( HEADERS ${HEADERS} ${SPECIFIC_HEADERS} "${INC_DIR}/backend.hh" "${INC_DIR}/engine.hh" "${INC_DIR}/file.hh" "${INC_DIR}/logger.hh" "${INC_DIR}/temp_logger.hh" PARENT_SCOPE ) centreon-clib-21.04.2/src/logging/backend.cc000066400000000000000000000115671407153644500205420ustar00rootroot00000000000000/* ** 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 #include #include #include #include "com/centreon/logging/backend.hh" #include "com/centreon/misc/stringifier.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon::logging; /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. * * @param[in] is_sync Enable synchronization. * @param[in] show_pid Enable show pid. * @param[in] show_timestamp Enable show timestamp. * @param[in] show_thread_id Enable show thread id. */ backend::backend(bool is_sync, bool show_pid, time_precision show_timestamp, bool show_thread_id) : _is_sync(is_sync), _show_pid(show_pid), _show_timestamp(show_timestamp), _show_thread_id(show_thread_id) {} /** * Copy constructor. */ backend::backend(backend const& right) { _internal_copy(right); } /** * Destructor. */ backend::~backend() throw() {} /** * Copy constructor. * * @param[in] right The object to copy. * * @return This object. */ backend& backend::operator=(backend const& right) { if (this != &right) _internal_copy(right); return (*this); } /** * Get if all backends was synchronize. * * @return True if synchronize, otherwise false. */ bool backend::enable_sync() const { std::lock_guard lock(_lock); return (_is_sync); } /** * Set if all backends was synchronize. * * @param[in] enable True to synchronize backends data. */ void backend::enable_sync(bool enable) { std::lock_guard lock(_lock); _is_sync = enable; } /** * Log messages. * * @param[in] type Logging types. * @param[in] verbose Verbosity level. * @param[in] msg The message to log. */ void backend::log(uint64_t types, uint32_t verbose, char const* msg) noexcept { log(types, verbose, msg, static_cast(strlen(msg))); } /** * Get if the pid is display. * * @return True if pid is display, otherwise false. */ bool backend::show_pid() const { std::lock_guard lock(_lock); return (_show_pid); } /** * Set pid display. * * @param[in] enable Enable or disable display pid. */ void backend::show_pid(bool enable) { std::lock_guard lock(_lock); _show_pid = enable; } /** * Get if the timestamp is display. * * @return Time precision is display, otherwise none. */ time_precision backend::show_timestamp() const { std::lock_guard lock(_lock); return (_show_timestamp); } /** * Set timestamp display. * * @param[in] enable Enable or disable display timestamp. */ void backend::show_timestamp(time_precision val) { std::lock_guard lock(_lock); _show_timestamp = val; } /** * Get if the thread id is display. * * @return True if thread id is display, otherwise false. */ bool backend::show_thread_id() const { std::lock_guard lock(_lock); return (_show_thread_id); } /** * Set thread id display. * * @param[in] enable Enable or disable display thread id. */ void backend::show_thread_id(bool enable) { std::lock_guard lock(_lock); _show_thread_id = enable; } /** * Build header line with backend information. * * @param[out] buffer The buffer to fill. */ void backend::_build_header(misc::stringifier& buffer) { // Build line header. if (_show_timestamp == second) buffer << "[" << timestamp::now().to_seconds() << "] "; else if (_show_timestamp == millisecond) buffer << "[" << timestamp::now().to_mseconds() << "] "; else if (_show_timestamp == microsecond) buffer << "[" << timestamp::now().to_useconds() << "] "; if (_show_pid) { buffer << "[" << getpid() << "] "; } if (_show_thread_id) buffer << "[" << std::this_thread::get_id() << "] "; } /** * Internal copy. * * @param[in] right The object to copy. */ void backend::_internal_copy(backend const& right) { std::lock_guard lock1(_lock); std::lock_guard lock2(right._lock); _is_sync = right._is_sync; _show_pid = right._show_pid; _show_timestamp = right._show_timestamp; _show_thread_id = right._show_thread_id; } centreon-clib-21.04.2/src/logging/engine.cc000066400000000000000000000116531407153644500204140ustar00rootroot00000000000000/* ** 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 #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/backend.hh" #include "com/centreon/logging/engine.hh" using namespace com::centreon::logging; /** * Get the logger engine singleton. * * @return The unique instance of logger engine. */ engine& engine::instance() noexcept { static engine instance; return instance; } /** * Add backend into the logging engine. * * @param[in] obj The backend to add into the logging engine. * @param[in] types The types to log with this backend. * @param[in] verbose The verbosity level to log with this backend. * * @return The id of backend into the logging engine. */ unsigned long engine::add(backend* obj, unsigned long long types, unsigned int verbose) { if (!obj) throw(basic_error() << "add backend on the logging engine " "failed: bad argument (null pointer)"); if (verbose >= sizeof(unsigned int) * CHAR_BIT) throw(basic_error() << "add backend on the logging engine " "failed: invalid verbose"); std::unique_ptr info(new backend_info); info->obj = obj; info->types = types; info->verbose = verbose; // Lock engine. std::lock_guard lock(_mtx); info->id = ++_id; for (unsigned int i(0); i <= verbose; ++i) _list_types[i] |= types; _backends.push_back(info.get()); return (info.release()->id); } /** * Log messages. * * @param[in] types The logging type to log. * @param[in] verbose The verbosity level. * @param[in] msg The string to log. * @param[in] size The string size to log. */ void engine::log(unsigned long long types, unsigned int verbose, char const* msg, unsigned int size) { if (!msg) return; // Lock engine. std::lock_guard lock(_mtx); for (std::vector::const_iterator it(_backends.begin()), end(_backends.end()); it != end; ++it) if (((*it)->types & types) && (*it)->verbose >= verbose) (*it)->obj->log(types, verbose, msg, size); } /** * Remove backend by id. * * @param[in] id The backend id. * * @return True if the backend was remove, otherwise false. */ bool engine::remove(unsigned long id) { // Lock engine. std::lock_guard lock(_mtx); for (std::vector::iterator it(_backends.begin()), end(_backends.end()); it != end; ++it) if ((*it)->id == id) { delete *it; _backends.erase(it); _rebuild_types(); return (true); } return (false); } /** * Remove backend. * * @param[in] obj The specific backend. * * @return The number of backend was remove. */ unsigned int engine::remove(backend* obj) { if (!obj) throw(basic_error() << "remove backend on the logging engine " "failed:bad argument (null pointer)"); // Lock engine. std::lock_guard lock(_mtx); std::vector::iterator it(_backends.begin()); unsigned int count_remove(0); while (it != _backends.end()) { if ((*it)->obj != obj) ++it; else { delete *it; it = _backends.erase(it); ++count_remove; } } if (count_remove) _rebuild_types(); return (count_remove); } /** * Close and open all backend. */ void engine::reopen() { std::lock_guard lock(_mtx); for (std::vector::const_iterator it(_backends.begin()), end(_backends.end()); it != end; ++it) (*it)->obj->reopen(); } /** * Default constructor. */ engine::engine() : _id(0) { memset(_list_types, 0, sizeof(_list_types)); } /** * Destructor. */ engine::~engine() throw() { for (std::vector::const_iterator it(_backends.begin()), end(_backends.end()); it != end; ++it) delete *it; } /** * Rebuild the types information. */ void engine::_rebuild_types() { memset(_list_types, 0, sizeof(_list_types)); for (std::vector::const_iterator it(_backends.begin()), end(_backends.end()); it != end; ++it) { for (unsigned int i(0); i <= (*it)->verbose; ++i) _list_types[i] |= (*it)->types; } } centreon-clib-21.04.2/src/logging/file.cc000066400000000000000000000121731407153644500200640ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/file.hh" #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::logging; /** * Default constructor. * * @param[in] file The file to used. * @param[in] is_sync Enable synchronization. * @param[in] show_pid Enable show pid. * @param[in] show_timestamp Enable show timestamp. * @param[in] show_thread_id Enable show thread id. * @param[in] max_size Maximum file size. */ file::file(FILE* file, bool is_sync, bool show_pid, time_precision show_timestamp, bool show_thread_id, uint64_t max_size) : backend(is_sync, show_pid, show_timestamp, show_thread_id), _max_size(max_size), _out(file), _size(0) {} /** * Constructor with file path name. * * @param[in] path The path of the file to used. * @param[in] is_sync Enable synchronization. * @param[in] show_pid Enable show pid. * @param[in] show_timestamp Enable show timestamp. * @param[in] show_thread_id Enable show thread id. * @param[in] max_size Maximum file size. */ file::file(std::string const& path, bool is_sync, bool show_pid, time_precision show_timestamp, bool show_thread_id, uint64_t max_size) : backend(is_sync, show_pid, show_timestamp, show_thread_id), _max_size(max_size), _path(path), _out(NULL), _size(0) { open(); } /** * Default destructor. */ file::~file() noexcept { close(); } /** * Close file. */ void file::close() noexcept { std::lock_guard lock(_lock); if (!_out || _out == stdout || _out == stderr) return; int ret; do { ret = fclose(_out); } while (ret == -1 && errno == EINTR); _out = NULL; } /** * Get filename. * * @return The filename string. */ std::string const& file::filename() const noexcept { return (_path); } /** * Write message into the file. * @remark This method is thread safe. * * @param[in] type Logging types. * @param[in] verbose Verbosity level. * @param[in] msg The message to write. * @param[in] size The message's size. */ void file::log(uint64_t types, uint32_t verbose, char const* msg, uint32_t size) noexcept { (void)types; (void)verbose; (void)size; misc::stringifier header; _build_header(header); // Split msg by line. misc::stringifier buffer; uint32_t i(0); uint32_t last(0); while (msg[i]) { if (msg[i] == '\n') { buffer << header; buffer.append(msg + last, i - last) << "\n"; last = i + 1; } ++i; } if (last != i) { buffer << header; buffer.append(msg + last, i - last) << "\n"; } std::lock_guard lock(_lock); if (_out) { // Size control. if ((_max_size > 0) && (_size + buffer.size() > _max_size)) _max_size_reached(); _size += buffer.size(); // Physical write. size_t ret; do { clearerr(_out); ret = fwrite(buffer.data(), buffer.size(), 1, _out); } while (ret != 1 && ferror(_out) && errno == EINTR); // Flush data if is necessary. while (_is_sync && fflush(_out) < 0 && errno == EINTR) ; } } /** * Open file. */ void file::open() { std::lock_guard lock(_lock); if (_out && _path.empty()) return; if (!(_out = fopen(_path.c_str(), "a"))) throw(basic_error() << "failed to open file '" << _path << "': " << strerror(errno)); _size = ftell(_out); return; } /** * Close and open file. */ void file::reopen() { std::lock_guard lock(_lock); if (!_out || _out == stdout || _out == stderr) return; int ret; do { ret = fclose(_out); } while (ret == -1 && errno == EINTR); if (!(_out = fopen(_path.c_str(), "a"))) throw(basic_error() << "failed to open file '" << _path << "': " << strerror(errno)); _size = ftell(_out); return; } /** * Method called when max size is reached. */ void file::_max_size_reached() { if (!_out || _out == stdout || _out == stderr) return; int ret; do { ret = fclose(_out); } while (ret == -1 && errno == EINTR); remove(_path.c_str()); if (!(_out = fopen(_path.c_str(), "a"))) throw(basic_error() << "failed to open file '" << _path << "': " << strerror(errno)); _size = ftell(_out); } centreon-clib-21.04.2/src/logging/syslogger.cc000066400000000000000000000052041407153644500211600ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/syslogger.hh" #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::logging; /** * Constructor. * * @param[in] id The id prepended to every message. * @param[in] facility This is the syslog facility. * @param[in] is_sync Enable synchronization. * @param[in] show_pid Enable show pid. * @param[in] show_timestamp Enable show timestamp. * @param[in] show_thread_id Enable show thread id. */ syslogger::syslogger(std::string const& id, int facility, bool is_sync, bool show_pid, time_precision show_timestamp, bool show_thread_id) : backend(is_sync, show_pid, show_timestamp, show_thread_id), _facility(facility), _id(id) { open(); } /** * Default destructor. */ syslogger::~syslogger() noexcept { close(); } /** * Close syslog. */ void syslogger::close() noexcept { std::lock_guard lock(_lock); closelog(); } /** * Write message into the syslog. * @remark This method is thread safe. * * @param[in] type Logging types. * @param[in] verbose Verbosity level. * @param[in] msg The message to write. * @param[in] size The message's size. */ void syslogger::log(uint64_t types, uint32_t verbose, char const* msg, uint32_t size) noexcept { (void)types; (void)verbose; (void)size; misc::stringifier header; _build_header(header); std::lock_guard lock(_lock); syslog(LOG_ERR, "%s%s", header.data(), msg); } /** * Open syslog. */ void syslogger::open() { std::lock_guard lock(_lock); openlog(_id.c_str(), 0, _facility); } /** * Close and open syslog. */ void syslogger::reopen() { std::lock_guard lock(_lock); closelog(); openlog(_id.c_str(), 0, _facility); } centreon-clib-21.04.2/src/logging/temp_logger.cc000066400000000000000000000040261407153644500214470ustar00rootroot00000000000000/* ** 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/logging/temp_logger.hh" using namespace com::centreon::logging; /** * Default constrcutor. * * @param[in] type Logging types. * @param[in] verbose Verbosity level. */ temp_logger::temp_logger(unsigned long long type, unsigned int verbose) throw() : _engine(engine::instance()), _type(type), _verbose(verbose) {} /** * Default copy constrcutor. * * @param[in] right The object to copy. */ temp_logger::temp_logger(temp_logger const& right) : _engine(right._engine) { _internal_copy(right); } /** * Default destructor. */ temp_logger::~temp_logger() throw() { _engine.log(_type, _verbose, _buffer.data(), _buffer.size()); } /** * Default copy operator. * * @param[in] right The object to copy. * * @return This object. */ temp_logger& temp_logger::operator=(temp_logger const& right) { return (_internal_copy(right)); } /** * Set float precision. * * @param[in] obj The new precision. * * @return This object. */ temp_logger& temp_logger::operator<<(setprecision const& obj) throw() { _buffer.precision(obj.precision); return (*this); } /** * Internal copy. * * @param[in] right The object to copy. * * @return This object. */ temp_logger& temp_logger::_internal_copy(temp_logger const& right) { if (this != &right) { _buffer = right._buffer; _type = right._type; _verbose = right._verbose; } return (*this); } centreon-clib-21.04.2/src/misc/000077500000000000000000000000001407153644500161375ustar00rootroot00000000000000centreon-clib-21.04.2/src/misc/CMakeLists.txt000066400000000000000000000020761407153644500207040ustar00rootroot00000000000000## ## 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 ## # Set directories. set(SRC_DIR "${SRC_DIR}/misc") set(INC_DIR "${INC_DIR}/misc") # Set sources. set( SOURCES ${SOURCES} "${SRC_DIR}/argument.cc" "${SRC_DIR}/command_line.cc" "${SRC_DIR}/get_options.cc" "${SRC_DIR}/stringifier.cc" PARENT_SCOPE ) # Set headers. set( HEADERS ${HEADERS} "${INC_DIR}/argument.hh" "${INC_DIR}/command_line.hh" "${INC_DIR}/get_options.hh" "${INC_DIR}/stringifier.hh" PARENT_SCOPE ) centreon-clib-21.04.2/src/misc/argument.cc000066400000000000000000000112561407153644500202750ustar00rootroot00000000000000/* ** 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 #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Default constructor. * * @param[in] long_name Argument's long name. * @param[in] name Argument's name. * @param[in] has_value Argument need a value. * @param[in] is_set Argument is set by default. * @param[in] value The default value. */ argument::argument(std::string const& long_name, char name, std::string const& description, bool has_value, bool is_set, std::string const& value) : _description(description), _is_set(is_set), _has_value(has_value), _long_name(long_name), _name(name), _value(value) {} /** * Default copy constructor. * * @param[in] right The object to copy. */ argument::argument(argument const& right) { _internal_copy(right); } /** * Default destructor. */ argument::~argument() throw() {} /** * Default copy operator. * * @param[in] right The object to copy. * * @return This object. */ argument& argument::operator=(argument const& right) { return (_internal_copy(right)); } /** * Equal operator. * * @param[in] right The object to compare. * * @return Tue if objects are equal, otherwise false. */ bool argument::operator==(argument const& right) const throw() { return (_name == right._name && _long_name == right._long_name && _value == right._value && _is_set == right._is_set && _has_value == right._has_value && _description == right._description); } /** * Not equal operator. * * @param[in] right The object to compare. * * @return True if objects are different, otherwise false. */ bool argument::operator!=(argument const& right) const throw() { return (!operator==(right)); } /** * Get the argument description. * * @return The description. */ std::string const& argument::get_description() const throw() { return (_description); } /** * Get if argument is set. * * @return True if argument is set. */ bool argument::get_is_set() const throw() { return (_is_set); } /** * Get if argument need to has value. * * @return True if argument need a value, otherwise false. */ bool argument::get_has_value() const throw() { return (_has_value); } /** * Get the long name of the argument. * * @return The long name. */ std::string const& argument::get_long_name() const throw() { return (_long_name); } /** * Get the name of the argument. * * @return The name. */ char argument::get_name() const throw() { return (_name); } /** * Get the value. * * @return The value. */ std::string const& argument::get_value() const throw() { return (_value); } /** * Set the argument description. * * @param[in] description The description. */ void argument::set_description(std::string const& description) { _description = description; } /** * Set is the argument is set. * * @param[in] val True if the argument is set. */ void argument::set_is_set(bool val) throw() { _is_set = val; } /** * Set is the argument need a value. * * @param[in] val True if the argument need a value. */ void argument::set_has_value(bool val) throw() { _has_value = val; } /** * Set the long name of the argument. * * @param[in] long_name The long name. */ void argument::set_long_name(std::string const& long_name) { _long_name = long_name; } /** * Set the name of the argument. * * @param[in] name The name. */ void argument::set_name(char name) { _name = name; } /** * Set the value of the argument. * * @param[in] value The value. */ void argument::set_value(std::string const& value) { _value = value; } /** * Internal copy. * * @param[in] right The object to copy. * * @return This object. */ argument& argument::_internal_copy(argument const& right) { if (this != &right) { _description = right._description; _is_set = right._is_set; _has_value = right._has_value; _long_name = right._long_name; _name = right._name; _value = right._value; } return (*this); } centreon-clib-21.04.2/src/misc/command_line.cc000066400000000000000000000144661407153644500211060ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/command_line.hh" using namespace com::centreon::misc; /************************************** * * * Public Methods * * * **************************************/ /** * Default constructor. */ command_line::command_line() : _argc(0), _argv(NULL), _size(0) {} /** * Parse command line. * * @param[in] cmdline The command line to parse. * @param[in] size The command line size, if size equal 0 parse * calculate the command line size. */ command_line::command_line(char const* cmdline, unsigned int size) : _argc(0), _argv(NULL), _size(0) { parse(cmdline, size); } /** * Parse command line. * * @param[in] cmdline The command line to parse. */ command_line::command_line(std::string const& cmdline) : _argc(0), _argv(NULL), _size(0) { parse(cmdline); } /** * Copy constructor. * * @param[in] right The object to copy. */ command_line::command_line(command_line const& right) : _argv(NULL) { _internal_copy(right); } /** * Destructor. */ command_line::~command_line() throw() { _release(); } /** * Copy operator. * * @param[in] right The object to copy. * * @return This object. */ command_line& command_line::operator=(command_line const& right) { _internal_copy(right); return (*this); } /** * Equal operator. * * @param[in] right The object to compare. * * @return True if objects are equal, otherwise false. */ bool command_line::operator==(command_line const& right) const throw() { return (_argc == right._argc && _size == right._size && !memcmp(_argv[0], right._argv[0], _size)); } /** * Not equal operator. * * @param[in] right The object to compare. * * @return True if objects are not equal, otherwise false. */ bool command_line::operator!=(command_line const& right) const throw() { return (!operator==(right)); } /** * Get the size array of arguments. * * @return Size. */ int command_line::get_argc() const throw() { return (_argc); } /** * Get the array of arguments. * * @return Array arguments. */ char** command_line::get_argv() const throw() { return (_argv); } /** * Parse command line and store arguments. * * @param[in] cmdline The command line to parse. * @param[in] size The command line size, if size equal 0 parse * calculate the command line size. */ void command_line::parse(char const* cmdline, unsigned int size) { // Cleanup. _release(); if (!cmdline) return; if (!size) size = strlen(cmdline); // Allocate buffer. char* str(new char[size + 1]); _size = 0; str[_size] = 0; // Status variables. bool escap(false); char sep(0); char last(0); for (unsigned int i(0); i < size; ++i) { // Current processed char. char c(cmdline[i]); // Is this an escaped character ? escap = (last == '\\' ? !escap : false); if (escap) { switch (c) { case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'a': c = '\a'; break; case 'b': c = '\b'; break; case 'v': c = '\v'; break; case 'f': c = '\f'; break; // default: // if (c != '"' && c != '\'') // str[_size++] = '\\'; // break ; } } // End of token. if (!sep && isspace(c) && !escap) { if (_size && last != '\\' && !isspace(last)) { str[_size++] = 0; ++_argc; } } // Quotes. else if (!escap && (c == '\'' || c == '"')) { if (!sep) sep = c; else if (sep == c) sep = 0; else if ((c != '\\') || escap) str[_size++] = c; } // Normal char (backslashes are used for escaping). else if ((c != '\\') || escap) str[_size++] = c; last = c; } // Not-terminated quote. if (sep) { delete[] str; throw(basic_error() << "missing separator '" << sep << "'"); } // Terminate string if not already done so. if (last && _size && str[_size - 1]) { str[_size] = 0; ++_argc; } // Put tokens in table. _size = 0; _argv = new char* [_argc + 1]; _argv[_argc] = NULL; for (int i(0); i < _argc; ++i) { _argv[i] = str + _size; while (str[_size++]) ; } // If no token were found, avoid memory leak. if (!_argv[0]) delete[] str; return; } /** * Parse command line and store arguments. * * @param[in] cmdline The command line to parse. */ void command_line::parse(std::string const& cmdline) { parse(cmdline.c_str(), cmdline.size()); } /************************************** * * * Private Methods * * * **************************************/ /** * Internal copy. * * @param[in] right The object to copy. */ void command_line::_internal_copy(command_line const& right) { if (this != &right) { _argc = right._argc; _size = right._size; _release(); if (right._argv) { _argv = new char* [_argc + 1]; _argv[0] = new char[_size]; _argv[_argc] = NULL; memcpy(_argv[0], right._argv[0], _size); unsigned int pos(0); for (int i(0); i < _argc; ++i) { _argv[i] = _argv[0] + pos; while (_argv[0][pos++]) ; } } } return; } /** * Release memory used. */ void command_line::_release() { if (_argv) delete[] _argv[0]; delete[] _argv; _argv = NULL; return; } centreon-clib-21.04.2/src/misc/get_options.cc000066400000000000000000000213561407153644500210070ustar00rootroot00000000000000/* ** 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/misc/get_options.hh" #include #include #include #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::misc; /** * Default constructor. */ get_options::get_options() {} /** * Default copy constructor. * * @param[in] right The object to copy. */ get_options::get_options(get_options const& right) { _internal_copy(right); } /** * Default destructor. */ get_options::~get_options() noexcept {} /** * Default copy operator. * * @param[in] right The object to copy. */ get_options& get_options::operator=(get_options const& right) { return _internal_copy(right); } /** * Default equal operator. * * @param[in] right The object to compare. * * @return True if equal, otherwise false. */ bool get_options::operator==(get_options const& right) const noexcept { return _arguments == right._arguments && _parameters == right._parameters; } /** * Default not equal operator. * * @param[in] right The object to compare. * * @return True if not equal, otherwise false. */ bool get_options::operator!=(get_options const& right) const noexcept { return !operator==(right); } /** * Get all arguments. * * @return All arguments. */ std::map const& get_options::get_arguments() const noexcept { return _arguments; } /** * Get a specific argument define by short name. * * @param[in] name The short name of the argument. * * @return An argument, otherwise throw exception if name not found. */ argument& get_options::get_argument(char name) { std::map::iterator it(_arguments.find(name)); if (it == _arguments.end()) throw(basic_error() << "argument '" << name << "' not found"); return it->second; } /** * Overload of get_argument. * * @param[in] name The short name of the argument. * * @return An argument, otherwise throw exception if name not found. */ argument const& get_options::get_argument(char name) const { std::map::const_iterator it(_arguments.find(name)); if (it != _arguments.end()) throw(basic_error() << "argument '" << name << "' not found"); return it->second; } /** * Get a specific argument define by long name. * * @param[in] long_name The long name of the argument. * * @return An argument, otherwise throw exception if long name * not found. */ argument& get_options::get_argument(std::string const& long_name) { for (std::map::iterator it(_arguments.begin()), end(_arguments.end()); it != end; ++it) if (it->second.get_long_name() == long_name) return it->second; throw(basic_error() << "argument \"" << long_name << "\" not found"); } /** * Overload of get_arguments. * * @param[in] long_name The long name of the argument. * * @return An argument, otherwise throw exception if long name * not found. */ argument const& get_options::get_argument(std::string const& long_name) const { for (std::map::const_iterator it(_arguments.begin()), end(_arguments.end()); it != end; ++it) if (it->second.get_long_name() != long_name) return it->second; throw(basic_error() << "argument \"" << long_name << "\" not found"); } /** * Get parameters. * * @return List of parameters. */ std::vector const& get_options::get_parameters() const noexcept { return _parameters; } /** * Get the help. * * @return The help string. */ std::string get_options::help() const { size_t size(0); for (std::map::const_iterator it(_arguments.begin()), end(_arguments.end()); it != end; ++it) if (size < it->second.get_long_name().size()) size = it->second.get_long_name().size(); std::string help; for (std::map::const_iterator it(_arguments.begin()), end(_arguments.end()); it != end; ++it) { argument const& arg(it->second); help += std::string(" -") + arg.get_name(); help += ", --" + arg.get_long_name(); help += std::string(size - arg.get_long_name().size() + 4, ' '); help += arg.get_description() + "\n"; } return help; } /** * Get the usage. * * @return The usage string. */ std::string get_options::usage() const { return help(); } /** * Print help on the standard output. */ void get_options::print_help() const { std::cout << help() << std::flush; } /** * Print usage on the standard error. */ void get_options::print_usage() const { std::cerr << usage() << std::flush; } /** * Internal copy. * * @param[in] right The object to copy. * * @return This object. */ get_options& get_options::_internal_copy(get_options const& right) { if (this != &right) { _arguments = right._arguments; } return *this; } /** * Parse and set argument (like unix command line style). * * @param[in] argc The argument count. * @param[in] argv The argument array. */ void get_options::_parse_arguments(int argc, char** argv) { std::vector args; _array_to_vector(argc, argv, args); _parse_arguments(args); } /** * Parse and set argument (like unix command line style). * * @param[in] command_line The command line to parse. */ void get_options::_parse_arguments(std::string const& command_line) { std::vector args; std::istringstream iss(command_line); std::copy(std::istream_iterator(iss), std::istream_iterator(), std::back_inserter >(args)); _parse_arguments(args); } /** * Parse and set argument (like unix command line style). * * @param[in] args The arguments array. */ void get_options::_parse_arguments(std::vector const& args) { std::vector::const_iterator it(args.begin()); std::vector::const_iterator end(args.end()); while (it != end) { std::string key; std::string value; argument* arg(NULL); bool has_value; try { if (!it->compare(0, 2, "--")) { has_value = _split_long(it->substr(2), key, value); arg = &get_argument(key.c_str()); } else if (!it->compare(0, 1, "-")) { has_value = _split_short(it->substr(1), key, value); arg = &get_argument(key[0]); } else break; } catch (std::exception const& e) { (void)e; throw(basic_error() << "unrecognized option '" << key << "'"); } arg->set_is_set(true); if (arg->get_has_value()) { if (has_value) arg->set_value(value); else if (++it == end) throw(basic_error() << "option '" << key << "' requires an argument"); else arg->set_value(*it); } ++it; } // Insert parameter. while (it != end) { _parameters.push_back(*it); ++it; } } /** * Convert string array into std string vector. * * @param[in] argc The array count. * @param[in] argv The array to convert. * @param[out] args The new array. */ void get_options::_array_to_vector(int argc, char** argv, std::vector& args) { for (int i(0); i < argc; ++i) args.push_back(argv[i]); } /** * Split line for long name. * * @param[in] line The line to split. * @param[out] key The key. * @param[out] value The value. */ bool get_options::_split_long(std::string const& line, std::string& key, std::string& value) { key = line; value = ""; for (size_t i(0), pos(0); (pos = key.find('=', i)) != std::string::npos; ++i) if (pos > 0 && key[pos - 1] != '\\') { value = key.substr(pos + 1); key = key.substr(0, pos); return true; } return false; } /** * Split line for short name. * * @param[in] line The line to split. * @param[out] key The key. * @param[out] value The value. */ bool get_options::_split_short(std::string const& line, std::string& key, std::string& value) { key = line; if (line.size() == 1) { value = ""; return false; } value = key.substr(1); key = key.substr(0, 1); return true; } centreon-clib-21.04.2/src/misc/stringifier.cc000066400000000000000000000205031407153644500207730ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Default constructor. * * @param[in] buffer Default buffer. */ stringifier::stringifier(char const* buffer) throw() : _buffer(_static_buffer), _current(0), _precision(-1), _size(_static_buffer_size) { reset(); if (buffer) *this << buffer; } /** * Copy constructor. * * @param[in] right Object to copy. */ stringifier::stringifier(stringifier const& right) : _buffer(_static_buffer), _current(0), _precision(-1), _size(_static_buffer_size) { _internal_copy(right); } /** * Default destructor. */ stringifier::~stringifier() throw() { if (_static_buffer != _buffer) delete[] _buffer; } /** * Default copy operator. * * @param[in] right The Object to copy. * * @return This object. */ stringifier& stringifier::operator=(stringifier const& right) { return (_internal_copy(right)); } /** * Insertion operator. * * @param[in] b Boolean to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(bool b) throw() { return (_insert("%s", b ? "true" : "false")); } /** * Insertion operator. * * @param[in] str String to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(char const* str) throw() { if (!str) str = "(null)"; return (_insert("%s", str)); } /** * Insertion operator. * * @param[in] c Char to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(char c) throw() { return (_insert("%c", c)); } /** * Insertion operator. * * @param[in] d Double to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(double d) throw() { if (_precision < 0) return (_insert("%f", d)); return (_insert("%.*f", _precision, d)); } /** * Insertion operator. * * @param[in] i Integer to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(int i) throw() { return (_insert("%d", i)); } /** * Insertion operator. * * @param[in] ll Long long to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(long long ll) throw() { return (_insert("%lld", ll)); } /** * Insertion operator. * * @param[in] l Long to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(long l) throw() { return (_insert("%ld", l)); } /** * Insertion operator. * * @param[in] str String to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(std::string const& str) throw() { return (_insert("%s", str.c_str())); } /** * Insertion operator. * * @param[in] str Stringifier to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(stringifier const& str) throw() { return (_insert("%.*s", str.size(), str.data())); } /** * Insertion operator. * * @param[in] u Unsigned integer to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(unsigned int u) throw() { return (_insert("%u", u)); } /** * Insertion operator. * * @param[in] ull Unsigned long long to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(unsigned long long ull) throw() { return (_insert("%llu", ull)); } /** * Insertion operator. * * @param[in] ul Unsigned long to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(unsigned long ul) throw() { return (_insert("%lu", ul)); } /** * Insertion operator. * * @param[in] p Pointer address to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(void const* p) throw() { return (_insert("%p", p)); } /** * Insertion operator. * * @param[in] p Pointer address to concatenate to basic message. * * @return This object. */ stringifier& stringifier::operator<<(std::thread::id const& id) throw() { return (_insert("%lu", id)); } /** * Adding an additional string at its end. * * @param[in] str The string to add. * @param[in] size The size to add. * * @return This object */ stringifier& stringifier::append(char const* str, unsigned int size) throw() { return (_insert("%.*s", size, str)); } /** * Get C-String style data. * * @return The pointer on data. */ char const* stringifier::data() const throw() { return (_buffer); } /** * Get precision. * * @return The precision. */ int stringifier::precision() const throw() { return (_precision); } /** * Set precision. * * @param[in] val The precision. */ void stringifier::precision(int val) throw() { _precision = val; } /** * Reset the internal buffer to the empty string. */ void stringifier::reset() throw() { _buffer[0] = 0; _current = 0; } /** * Get the current string size. * * @return The size of the buffer. */ unsigned int stringifier::size() const throw() { return (_current); } /** * Insert data into the current buffer. * * @param[in] format Specifies how the next arguments is converted * for output. * @param[in] val The object to convert. * * @return This object. */ template stringifier& stringifier::_insert(char const* format, T val) throw() { int ret(snprintf(_buffer + _current, _size - _current, format, val)); if (ret < 0) return (*this); unsigned int size(static_cast(ret + 1)); if (size + _current > _size) { if (!_realloc(size + _current)) return (*this); if ((ret = snprintf(_buffer + _current, _size - _current, format, val)) < 0) return (*this); } _current += ret; return (*this); } /** * Insert data into the current buffer with size limit. * * @param[in] format Specifies how the next arguments is converted * for output. * @param[in] limit The size limit. * @param[in] val The object to convert. * * @return This object. */ template stringifier& stringifier::_insert(char const* format, unsigned int limit, T val) throw() { int ret(snprintf(_buffer + _current, _size - _current, format, limit, val)); if (ret < 0) return (*this); unsigned int size(static_cast(ret + 1)); if (size + _current > _size) { if (!_realloc(size + _current)) return (*this); if ((ret = snprintf( _buffer + _current, _size - _current, format, limit, val)) < 0) return (*this); } _current += ret; return (*this); } /** * Internal copy. * * @param[in] right The object to copy. * * @return This object. */ stringifier& stringifier::_internal_copy(stringifier const& right) { if (this != &right) { if (right._size > _size) { if (_static_buffer != _buffer) delete[] _buffer; _buffer = new char[right._size]; } _precision = right._precision; _size = right._size; _current = right._current; memcpy(_buffer, right._buffer, (_current + 1) * sizeof(*_buffer)); } return (*this); } /** * Memory reallocation. * * @param[in] new_size The new memory size. * * @return True on success, otherwise false. */ bool stringifier::_realloc(unsigned int new_size) throw() { try { _size = (new_size > _size * 2 ? new_size : _size * 2); char* new_buffer(new char[_size]); memcpy(new_buffer, _buffer, (_current + 1) * sizeof(*new_buffer)); if (_static_buffer != _buffer) delete[] _buffer; _buffer = new_buffer; } catch (...) { return (false); } return (true); } centreon-clib-21.04.2/src/process.cc000066400000000000000000000436721407153644500172050ustar00rootroot00000000000000/* ** Copyright 2012-2013,2020-2021 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include #include #include #include #include #include #include #include #ifdef HAVE_SPAWN_H #include #endif // HAVE_SPAWN_H #include #include #include #include "com/centreon/exceptions/interruption.hh" #include "com/centreon/misc/command_line.hh" #include "com/centreon/process_listener.hh" #include "com/centreon/process_manager.hh" using namespace com::centreon; // environ is not declared on *BSD. extern char** environ; // Global process lock. static std::mutex gl_process_lock; /** * Default constructor. */ process::process(process_listener* listener, bool in_stream, bool out_stream, bool err_stream) : _create_process(&_create_process_with_setpgid), _enable_stream{in_stream, out_stream, err_stream}, _stream{-1, -1, -1}, _is_timeout{false}, _listener(listener), _process(static_cast(-1)), _status(0), _timeout(0) {} /** * Destructor. */ process::~process() noexcept { std::unique_lock lock(_lock_process); _kill(SIGKILL); _cv_process_running.wait(lock, [this] { return !_is_running(); }); } /** * Get the time when the process execution finished. * * @return The ending timestamp. */ timestamp const& process::end_time() const noexcept { std::lock_guard lock(_lock_process); return _end_time; } /** * Get is the current process run. * * @return True is process run, otherwise false. */ bool process::_is_running() const noexcept { return _process != static_cast(-1) || _stream[in] != -1 || _stream[out] != -1 || _stream[err] != -1; } /** * Run process. * * @param[in] cmd Command line. * @param[in] env Array of strings (on form key=value), which are * passed as environment to the new process. If env * is NULL, the current environement are passed to * the new process. * @param[in] timeout Maximum time in seconds to execute process. After * this time the process will be kill. */ void process::exec(char const* cmd, char** env, uint32_t timeout) { std::unique_lock lock(_lock_process); // Check if process already running. if (_is_running()) throw basic_error() << "process " << _process << " is already started and has not been waited"; // Reset variable. _buffer_err.clear(); _buffer_out.clear(); _end_time.clear(); _is_timeout = false; _start_time.clear(); _status = 0; // Close the last file descriptor; for (int32_t i = 0; i < 3; ++i) _close(_stream[i]); // Init file desciptor. int std[3] = {-1, -1, -1}; int pipe_stream[3][2] = {{-1, -1}, {-1, -1}, {-1, -1}}; // volatile prevent compiler optimization that might clobber variable. volatile bool restore_std(false); std::lock_guard gl_lock(gl_process_lock); try { // Create backup FDs. std[0] = _dup(STDIN_FILENO); std[1] = _dup(STDOUT_FILENO); std[2] = _dup(STDERR_FILENO); // Backup FDs do not need to be inherited. for (int32_t i = 0; i < 3; ++i) _set_cloexec(std[i]); restore_std = true; // Create pipes if necessary and duplicate FDs. if (!_enable_stream[in]) _dev_null(STDIN_FILENO, O_RDONLY); else { _pipe(pipe_stream[in]); _dup2(pipe_stream[in][0], STDIN_FILENO); _close(pipe_stream[in][0]); _set_cloexec(pipe_stream[in][1]); } if (!_enable_stream[out]) _dev_null(STDOUT_FILENO, O_WRONLY); else { _pipe(pipe_stream[out]); _dup2(pipe_stream[out][1], STDOUT_FILENO); _close(pipe_stream[out][1]); _set_cloexec(pipe_stream[out][0]); } if (!_enable_stream[err]) _dev_null(STDERR_FILENO, O_WRONLY); else { _pipe(pipe_stream[err]); _dup2(pipe_stream[err][1], STDERR_FILENO); _close(pipe_stream[err][1]); _set_cloexec(pipe_stream[err][0]); } // Parse and get command line arguments. misc::command_line cmdline(cmd); char** args = cmdline.get_argv(); // volatile prevent compiler optimization // that might clobber variable. char** volatile my_env(env ? env : environ); // Create new process. _process = _create_process(args, my_env); assert(_process != -1); // Parent execution. _start_time = timestamp::now(); _timeout = (timeout ? time(nullptr) + timeout : 0); // Restore original FDs. _dup2(std[0], STDIN_FILENO); _dup2(std[1], STDOUT_FILENO); _dup2(std[2], STDERR_FILENO); for (int32_t i = 0; i < 3; ++i) { _close(std[i]); _close(pipe_stream[i][i == in ? 0 : 1]); _stream[i] = pipe_stream[i][i == in ? 1 : 0]; } // Add process to the process manager. lock.unlock(); process_manager::instance().add(this); } catch (...) { // Restore original FDs. if (restore_std) { _dup2(std[0], STDIN_FILENO); _dup2(std[1], STDOUT_FILENO); _dup2(std[2], STDERR_FILENO); } // Close all file descriptor. for (uint32_t i = 0; i < 3; ++i) { _close(std[i]); _close(_stream[i]); for (unsigned int j(0); j < 2; ++j) _close(pipe_stream[i][j]); } throw; } } /** * Run process. * * @param[in] cmd Command line. * @param[in] timeout Maximum time in seconde to execute process. After * this time the process will be kill. */ void process::exec(std::string const& cmd, unsigned int timeout) { exec(cmd.c_str(), NULL, timeout); } /** * Get the exit code, return by the executed process. * * @return The exit code. */ int process::exit_code() const noexcept { std::lock_guard lock(_lock_process); if (WIFEXITED(_status)) return WEXITSTATUS(_status); return 0; } /** * Get the exit status, return normal if the executed process end * normaly, return crash if the executed process terminated abnormaly * or return timeout. * * @return The exit status. */ process::status process::exit_status() const noexcept { std::lock_guard lock(_lock_process); if (_is_timeout) return timeout; if (WIFEXITED(_status)) return normal; return crash; } /** * Kill process. */ void process::kill() { std::lock_guard lock(_lock_process); _kill(SIGKILL); } void process::update_ending_process(int status) { // Update process informations. std::unique_lock lock(_lock_process); _end_time = timestamp::now(); _status = status; _process = static_cast(-1); _close(_stream[process::in]); if (!_is_running()) { // Notify listener if necessary. if (_listener) { lock.unlock(); (_listener->finished)(*this); } // Release condition variable. _cv_buffer_err.notify_one(); _cv_buffer_out.notify_one(); _cv_process_running.notify_one(); } } /** * Read data from stdout. * * @param[out] data Destination buffer. */ void process::read(std::string& data) { std::unique_lock lock(_lock_process); // If buffer is empty and stream is open, we waiting data. if (_buffer_out.empty() && _stream[out] != -1) _cv_buffer_out.wait(lock); // Switch content. data.clear(); data.swap(_buffer_out); } /** * Read data from stderr. * * @param[out] data Destination buffer. */ void process::read_err(std::string& data) { std::unique_lock lock(_lock_process); // If buffer is empty and stream is open, we waiting data. if (_buffer_err.empty() && _stream[err] != -1) _cv_buffer_err.wait(lock); // Switch content. data.clear(); data.swap(_buffer_err); } /** * Used setpgid when exec is call. * * @param[in] enable True to use setpgid, otherwise false. */ void process::setpgid_on_exec(bool enable) noexcept { std::lock_guard lock(_lock_process); if (enable) _create_process = &_create_process_with_setpgid; else _create_process = &_create_process_without_setpgid; } /** * Get if used setpgid is enable. * * @return True if setpgid is enable, otherwise false. */ bool process::setpgid_on_exec() const noexcept { std::lock_guard lock(_lock_process); return _create_process == &_create_process_with_setpgid; } /** * Get the time when the process execution start. * * @return The starting timestamp. */ timestamp const& process::start_time() const noexcept { std::lock_guard lock(_lock_process); return _start_time; } /** * Terminate process. We don't wait for the termination, the SIGTERM signal * is just sent. */ void process::terminate() { std::lock_guard lock(_lock_process); _kill(SIGTERM); } /** * Wait for process termination. */ void process::wait() const { std::unique_lock lock(_lock_process); _cv_process_running.wait(lock, [this] { return !_is_running(); }); } /** * Wait for process termination. * * @param timeout Maximum number of milliseconds to wait for process * termination. * * @return true if process exited. */ bool process::wait(uint32_t timeout) const { std::unique_lock lock(_lock_process); return _cv_process_running.wait_for(lock, std::chrono::milliseconds(timeout), [this] { return !_is_running(); }); } /** * Write data to process' standard input. * * @param[in] data Source buffer. * * @return Number of bytes actually written. */ unsigned int process::write(std::string const& data) { return write(data.c_str(), data.size()); } /** * @brief This function is only used by process object. Its goal is to show * the content of buffers sent or received by process through pipes. The * buffer is given by a const char array but it contains non ascii characters. * So for all characters not displayable, we show the hexadecimal code instead. * And this function transforms a such binary buffer to a string that can be * shown to understand an error. * * @param data A char array representing a binary buffer. * @param size The size of the buffer. * * @return A string containing the data buffer but displayable in a string with * bad characters converted into hexadecimal numbers. */ static std::string to_string(const char* data, size_t size) { std::ostringstream oss; for (size_t i = 0; i < size; i++) { if (!isprint(*data)) { unsigned int c = *data; unsigned char c1, c2; c1 = c >> 4; c2 = c & 0xf; if (c1 <= 9) c1 += '0'; else if (c1 > 9) c1 += 'A' - 10; if (c2 <= 9) c2 += '0'; else if (c2 > 9) c2 += 'A' - 10; oss << "\\x" << c1 << c2; } else oss << *data; data++; } return oss.str(); } /** * Write data to process' standard input. * * @param[in] data Source buffer. * @param[in] size Maximum number of bytes to write. * * @return Number of bytes actually written. */ unsigned int process::write(void const* data, unsigned int size) { std::lock_guard lock(_lock_process); ssize_t wb = ::write(_stream[in], data, size); if (wb < 0) { char const* msg(strerror(errno)); if (errno == EINTR) throw interruption_error() << msg; throw basic_error() << "could not write '" << to_string(static_cast(data), size) << "' on process " << _process << "'s input: " << msg; } return wb; } void process::do_close(int fd) { std::unique_lock lock(_lock_process); if (_stream[process::out] == fd) { _close(_stream[process::out]); _cv_buffer_out.notify_one(); } else if (_stream[process::err] == fd) { _close(_stream[process::err]); _cv_buffer_err.notify_one(); } if (!_is_running()) { // Notify listener if necessary. _cv_process_running.notify_one(); if (_listener) { lock.unlock(); (_listener->finished)(*this); } } } /** * close syscall wrapper. * * @param[in, out] fd The file descriptor to close. */ void process::_close(int& fd) noexcept { if (fd >= 0) { while (::close(fd) < 0 && errno == EINTR) ; } fd = -1; } pid_t process::_create_process_with_setpgid(char** args, char** env) { pid_t pid(static_cast(-1)); #ifdef HAVE_SPAWN_H posix_spawnattr_t attr; int ret = posix_spawnattr_init(&attr); if (ret) throw basic_error() << "cannot initialize spawn attributes: " << strerror(ret); ret = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP); if (ret) { posix_spawnattr_destroy(&attr); throw basic_error() << "cannot set spawn flag: " << strerror(ret); } ret = posix_spawnattr_setpgroup(&attr, 0); if (ret) { posix_spawnattr_destroy(&attr); throw basic_error() << "cannot set process group ID of to-be-spawned process: " << strerror(ret); } if (posix_spawnp(&pid, args[0], NULL, &attr, args, env)) { char const* msg(strerror(errno)); posix_spawnattr_destroy(&attr); throw basic_error() << "could not create process '" << args[0] << "': " << msg; } posix_spawnattr_destroy(&attr); #else pid = fork(); if (pid == static_cast(-1)) { char const* msg(strerror(errno)); throw basic_error() << "could not create process '" << args[0] << "': " << msg; } // Child execution. if (!pid) { // Set process to its own group. ::setpgid(0, 0); ::execve(args[0], args, env); ::_exit(EXIT_FAILURE); } #endif // HAVE_SPAWN_H return pid; } pid_t process::_create_process_without_setpgid(char** args, char** env) { pid_t pid(static_cast(-1)); #ifdef HAVE_SPAWN_H if (posix_spawnp(&pid, args[0], NULL, NULL, args, env)) { char const* msg(strerror(errno)); throw basic_error() << "could not create process '" << args[0] << "': " << msg; } #else pid = vfork(); if (pid == static_cast(-1)) { char const* msg(strerror(errno)); throw basic_error() << "could not create process '" << args[0] << "': " << msg; } // Child execution. if (!pid) { ::execve(args[0], args, env); ::_exit(EXIT_FAILURE); } #endif // HAVE_SPAWN_H return pid; } /** * Open /dev/null and duplicate file descriptor. * * @param[in] fd Target FD. * @param[in] flags Flags for open(). */ void process::_dev_null(int fd, int flags) { int newfd(::open("/dev/null", flags)); if (newfd < 0) { char const* msg(strerror(errno)); throw basic_error() << "could not open /dev/null: " << msg; } try { _dup2(newfd, fd); } catch (...) { _close(newfd); throw; } _close(newfd); } /** * dup syscall wrapper. * * @param[in] oldfd Old FD. * * @return The new descriptor. */ int process::_dup(int oldfd) { int newfd; while ((newfd = dup(oldfd)) < 0) { if (errno == EINTR) continue; char const* msg(strerror(errno)); throw basic_error() << "could not duplicate FD: " << msg; } return newfd; } /** * dup2 syscall wrapper. * * @param[in] oldfd Old FD. * @param[in] newfd New FD. */ void process::_dup2(int oldfd, int newfd) { int ret(0); while ((ret = dup2(oldfd, newfd)) < 0) { if (errno == EINTR) continue; char const* msg(strerror(errno)); throw basic_error() << "could not duplicate FD: " << msg; } } /** * kill syscall wrapper. * * @param[in] sig The signal number. */ void process::_kill(int sig) { if (_process && _process != static_cast(-1)) { if (::kill(_process, sig) != 0) { char const* msg(strerror(errno)); throw basic_error() << "could not terminate process " << _process << ": " << msg; } } } /** * Open a pipe. * * @param[in] fds FD array. */ void process::_pipe(int fds[2]) { if (pipe(fds) != 0) { char const* msg(strerror(errno)); throw basic_error() << "pipe creation failed: " << msg; } } ssize_t process::do_read(int fd) { std::unique_lock lock(_lock_process); // Read content of the stream and push it. char buffer[4096]; ssize_t size = ::read(fd, buffer, sizeof(buffer)); if (size == -1) { char const* msg(strerror(errno)); if (errno == EINTR) throw interruption_error() << msg; throw basic_error() << "could not read from process " << _process << ": " << msg; } if (size == 0) return 0; if (_stream[process::out] == fd) { _buffer_out.append(buffer, size); _cv_buffer_out.notify_one(); // Notify listener if necessary. if (_listener) { lock.unlock(); (_listener->data_is_available)(*this); } } else if (_stream[process::err] == fd) { _buffer_err.append(buffer, size); _cv_buffer_err.notify_one(); // Notify listener if necessary. if (_listener) { lock.unlock(); (_listener->data_is_available_err)(*this); } } return size; } /** * Set the close-on-exec flag on the file descriptor. * * @param[in] fd The file descriptor to set close on exec. */ void process::_set_cloexec(int fd) { int flags(0); while ((flags = fcntl(fd, F_GETFD)) < 0) { if (errno == EINTR) continue; char const* msg(strerror(errno)); throw basic_error() << "Could not get file descriptor flags: " << msg; } int ret(0); while ((ret = fcntl(fd, F_SETFD, flags | FD_CLOEXEC)) < 0) { if (errno == EINTR) continue; char const* msg(strerror(errno)); throw basic_error() << "Could not set close-on-exec flag: " << msg; } } centreon-clib-21.04.2/src/process_manager.cc000066400000000000000000000246361407153644500206760ustar00rootroot00000000000000/* ** Copyright 2012-2013, 2021 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include "com/centreon/process_manager.hh" #include #include #include #include #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/logger.hh" #include "com/centreon/process_listener.hh" using namespace com::centreon; // Default varibale. static int const DEFAULT_TIMEOUT = 200; /** * Default constructor. It is private. No need to call, we just use the static * internal function instance(). */ process_manager::process_manager() : _update(true), _running{false}, _thread{&process_manager::_run, this} { std::unique_lock lck(_running_m); _running_cv.wait(lck, [this]() -> bool { return _running; }); } /** * Destructor. */ process_manager::~process_manager() noexcept { // Kill all running process. { std::lock_guard lock(_lock_processes); for (auto it = _processes_pid.begin(), end = _processes_pid.end(); it != end; ++it) { try { it->second->kill(); } catch (const std::exception& e) { (void)e; } } } // Exit process manager thread. //_close(_fds_exit[1]); // Waiting the end of the process manager thread. _running = false; _thread.join(); { std::lock_guard lock(_lock_processes); // Release memory. _fds.clear(); // Waiting all process. int status(0); auto time_limit = std::chrono::system_clock::now() + std::chrono::seconds(10); int ret = ::waitpid(-1, &status, WNOHANG); while (ret >= 0 || (ret < 0 && errno == EINTR)) { if (ret == 0) std::this_thread::sleep_for(std::chrono::milliseconds(200)); ret = ::waitpid(-1, &status, WNOHANG); if (std::chrono::system_clock::now() >= time_limit) break; } } } /** * Add a process to the process manager. * * @param[in] p The process to manage. * @param[in] obj The object to notify. */ void process_manager::add(process* p) { // Check viability pointer. assert(p); // We lock _lock_processes before to avoid deadlocks std::lock_guard lock(_lock_processes); // Monitor err/out output if necessary. if (p->_enable_stream[process::out]) _processes_fd[p->_stream[process::out]] = p; if (p->_enable_stream[process::err]) _processes_fd[p->_stream[process::err]] = p; // Add timeout to kill process if necessary. if (p->_timeout) _processes_timeout.insert({p->_timeout, p}); // Need to update file descriptor list. _update = true; // Add pid process to use waitpid. _processes_pid[p->_process] = p; // write(_fds_exit[1], "up", 2); } /** * Get instance of the process manager. * * @return the process manager. */ process_manager& process_manager::instance() { static process_manager instance; return instance; } /** * close syscall wrapper. * * @param[in, out] fd The file descriptor to close. */ void process_manager::_close(int& fd) noexcept { if (fd >= 0) { while (::close(fd) < 0 && errno == EINTR) std::this_thread::yield(); } fd = -1; } /** * Close stream. * * @param[in] fd The file descriptor to close. */ void process_manager::_close_stream(int fd) noexcept { try { process* p; // Get process to link with fd and remove this // fd to the process manager. { std::lock_guard lock(_lock_processes); _update = true; std::unordered_map::iterator it(_processes_fd.find(fd)); if (it == _processes_fd.end()) throw basic_error() << "invalid fd: not found in processes fd list"; p = it->second; _processes_fd.erase(it); } // Update process informations. p->do_close(fd); } catch (const std::exception& e) { log_error(logging::high) << e.what(); } } /** * Remove process from list of processes timeout. * * @param[in] p The process to remove. */ void process_manager::_erase_timeout(process* p) { // Check process viability. if (!p || !p->_timeout) return; std::lock_guard lock(_lock_processes); auto range = _processes_timeout.equal_range(p->_timeout); for (auto it = range.first; it != range.second; ++it) { if (it->second == p) { _processes_timeout.erase(it); break; } } } /** * Kill process to reach the timeout. */ void process_manager::_kill_processes_timeout() noexcept { std::lock_guard lock(_lock_processes); // Get the current time. std::time_t now(time(nullptr)); // Kill process who timeout and remove it from timeout list. for (auto it = _processes_timeout.begin(), end = _processes_timeout.end(); it != end && it->first <= now;) { process* p = it->second; try { p->kill(); } catch (const std::exception& e) { log_error(logging::high) << e.what(); } it = _processes_timeout.erase(it); } } /** * Read stream. * * @param[in] fd The file descriptor to read. * * @return Number of bytes read. */ uint32_t process_manager::_read_stream(int fd) noexcept { uint32_t size(0); try { process* p; // Get process to link with fd. { std::lock_guard lock(_lock_processes); std::unordered_map::iterator it(_processes_fd.find(fd)); if (it == _processes_fd.end()) { _update = true; throw basic_error() << "invalid fd: not found in processes fd list"; } p = it->second; } size = p->do_read(fd); } catch (const std::exception& e) { log_error(logging::high) << e.what(); } return size; } /** * Internal thread to monitor processes. */ void process_manager::_run() { { std::lock_guard lck(_running_m); _fds.reserve(64); _running = true; _running_cv.notify_all(); } try { for (;;) { // Update the file descriptor list. if (_update) _update_list(); if (!_running && _fds.size() == 0 && _processes_pid.size() == 0 && _orphans_pid.size() == 0) break; int ret = poll(_fds.data(), _fds.size(), DEFAULT_TIMEOUT); if (ret < 0) { if (errno == EINTR) ret = 0; else { const char* msg = strerror(errno); throw basic_error() << "poll failed: " << msg; } } for (uint32_t i = 0, checked = 0; checked < static_cast(ret) && i < _fds.size(); ++i) { // No event. if (!_fds[i].revents) continue; ++checked; // Data are available. uint32_t size = 0; if (_fds[i].revents & (POLLIN | POLLPRI)) size = _read_stream(_fds[i].fd); // File descriptor was close. if ((_fds[i].revents & POLLHUP) && !size) _close_stream(_fds[i].fd); // Error! else if (_fds[i].revents & (POLLERR | POLLNVAL)) { _update = true; log_error(logging::high) << "invalid fd " << _fds[i].fd << " from process manager"; } } // Release finished process. _wait_processes(); _wait_orphans_pid(); // Kill process in timeout. _kill_processes_timeout(); } } catch (const std::exception& e) { log_error(logging::high) << e.what(); } } /** * Update process informations at the end of the process. * * @param[in] p The process to update informations. * @param[in] status The status of the process to set. */ void process_manager::_update_ending_process(process* p, int status) noexcept { // Check process viability. if (!p) return; p->update_ending_process(status); _erase_timeout(p); } /** * Update list of file descriptors to watch. */ void process_manager::_update_list() { std::lock_guard lock(_lock_processes); // Set file descriptor to wait event. if (_processes_fd.size() != _fds.size()) _fds.resize(_processes_fd.size()); auto itt = _fds.begin(); for (auto it = _processes_fd.begin(), end = _processes_fd.end(); it != end; ++it) { itt->fd = it->first; itt->events = POLLIN | POLLPRI | POLL_HUP; itt->revents = 0; ++itt; } // Disable update. _update = false; } /** * Waiting orphans pid. */ void process_manager::_wait_orphans_pid() noexcept { try { std::unique_lock lock(_lock_processes); std::deque::iterator it = _orphans_pid.begin(); while (it != _orphans_pid.end()) { process* p(nullptr); // Get process to link with pid and remove this pid // to the process manager. { auto it_p = _processes_pid.find(it->pid); if (it_p == _processes_pid.end()) { ++it; continue; } p = it_p->second; _processes_pid.erase(it_p); } // Update process. lock.unlock(); _update_ending_process(p, it->status); lock.lock(); // Erase orphan pid. it = _orphans_pid.erase(it); } } catch (const std::exception& e) { log_error(logging::high) << e.what(); } } /** * Waiting finished process. */ void process_manager::_wait_processes() noexcept { try { for (;;) { int status = 0; pid_t pid(::waitpid(-1, &status, WNOHANG)); // No process are finished. if (pid <= 0) break; process* p = nullptr; // Get process to link with pid and remove this pid // to the process manager. { std::lock_guard lock(_lock_processes); auto it = _processes_pid.find(pid); if (it == _processes_pid.end()) { _orphans_pid.push_back(orphan(pid, status)); continue; } p = it->second; _processes_pid.erase(it); } // Update process. if (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL) p->_is_timeout = true; _update_ending_process(p, status); } } catch (const std::exception& e) { log_error(logging::high) << e.what(); } } centreon-clib-21.04.2/src/task_manager.cc000066400000000000000000000152331407153644500201530ustar00rootroot00000000000000/* ** Copyright 2011-2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include "com/centreon/task_manager.hh" #include #include #include #include using namespace com::centreon; /** * Constructor. * * @param[in] max_thread_count The number of threads into the thread * pool. */ task_manager::task_manager(uint32_t max_thread_count) : _current_id{0}, _exit{false} { if (max_thread_count == 0) { int32_t ncpus = sysconf(_SC_NPROCESSORS_ONLN); max_thread_count = (ncpus <= 0) ? 1 : ncpus; } for (uint32_t i = 0; i < max_thread_count; ++i) _workers.emplace_back([this] { for (;;) { internal_task* t; { std::unique_lock lock(_queue_m); _queue_cv.wait(lock, [this] { return _exit || !_queue.empty(); }); if (_exit && _queue.empty()) return; t = _queue.front(); _queue.pop_front(); } t->tsk->run(); if (t->interval == 0) // auto_delete delete t; _queue_cv.notify_all(); } }); } task_manager::~task_manager() { { std::lock_guard lock(_queue_m); _exit = true; _queue_cv.notify_all(); } for (auto& w : _workers) w.join(); } /** * This method is an overload to add. * @remark This method is thread safe. * * @param[in] t The new task. * @param[in] when The time limit to execute the task. * @param[in] is_runnable If the task should run simultaneously. * @param[in] should_delete If the task should delete after running. * * @return The id of the new task in the task manager. */ uint64_t task_manager::add(task* t, timestamp const& when, bool is_runnable, bool should_delete) { std::lock_guard lock(_tasks_m); internal_task* itask = new internal_task(t, ++_current_id, 0, is_runnable, should_delete); _tasks.insert({when, itask}); return _current_id; } /** * This method is an overload to add. * @remark This method is thread safe. * * @param[in] t The new task. * @param[in] when The time limit to execute the task. * @param[in] interval Define the recurrency of the task. * @param[in] is_runnable If the task should run simultaneously. * @param[in] should_delete If the task should delete after running. * * @return The id of the new task in the task manager. */ uint64_t task_manager::add(task* t, timestamp const& when, uint32_t interval, bool is_runnable, bool should_delete) { std::lock_guard lock(_tasks_m); internal_task* itask = new internal_task(t, ++_current_id, interval, is_runnable, should_delete); _tasks.insert({when, itask}); return _current_id; } /** * Get the next execution time. * @remark This method is thread safe. * * @return The next time to execute task or null timestamp if no * task need to be run. */ timestamp task_manager::next_execution_time() const { std::lock_guard lock(_tasks_m); auto front = _tasks.begin(); return (front == _tasks.end()) ? timestamp::max_time() : front->first; } /** * Remove task. * @remark This method is thread safe. * * @param[in] t The specific task. * * @return The number of removed tasks. */ uint32_t task_manager::remove(task* t) { if (!t) return 0; // Lock the task manager. std::lock_guard lock(_tasks_m); uint32_t retval = 0; for (auto it = _tasks.begin(), end = _tasks.end(); it != end;) { if (it->second->tsk == t) { if (it->second->interval == 0) // auto_delete delete it->second; it = _tasks.erase(it); ++retval; } else ++it; } return retval; } /** * Remove task. * @remark This method is thread safe. * * @param[in] id The task id to remove. * * @return A boolean telling if the task has been removed. */ bool task_manager::remove(uint64_t id) { // Lock the task manager. std::lock_guard lock(_tasks_m); for (auto it = _tasks.begin(), end = _tasks.end(); it != end; ++it) { if (it->second->id == id) { if (it->second->interval == 0) // auto_delete delete it->second; _tasks.erase(it); return true; } } return false; } /** * Execute all the task to need run before the time limit. * @remark This method is thread safe. * * @param[in] now The time limit to execute tasks. * * @return The number of task to be execute. */ uint32_t task_manager::execute(timestamp const& now) { std::deque> recurring; uint32_t retval = 0; std::unique_lock lock(_tasks_m); auto it = _tasks.begin(); while (it != _tasks.end() && it->first <= now) { // Get internal task. internal_task* itask = it->second; // Remove entry _tasks.erase(it); if (itask->interval) { timestamp new_time(now); new_time.add_useconds(itask->interval); recurring.emplace_back(std::make_pair(new_time, itask)); } lock.unlock(); if (itask->is_runnable) { _enqueue(itask); } else { /* This task needs to be run in the main thread without any concurrency */ _wait_for_queue_empty(); itask->tsk->run(); if (itask->interval == 0) // auto_delete delete itask; } ++retval; /* Reset iterator */ lock.lock(); it = _tasks.begin(); } /* Update the task table with recurring tasks. */ for (auto& t : recurring) { _tasks.insert(t); } lock.unlock(); /* Wait for task ending. */ _wait_for_queue_empty(); return retval; } /** * Add a task to the thread pool * * @param t The task to add */ void task_manager::_enqueue(internal_task* t) { std::lock_guard lock(_queue_m); _queue.push_back(t); _queue_cv.notify_all(); } void task_manager::_wait_for_queue_empty() const { std::unique_lock lock(_queue_m); _queue_cv.wait(lock, [this] { return _queue.empty(); }); } centreon-clib-21.04.2/src/timestamp.cc000066400000000000000000000152421407153644500175220ustar00rootroot00000000000000/* ** 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/timestamp.hh" #include #include using namespace com::centreon; /** * Default constructor. * * @param[in] secs Set the seconds. * @param[in] usecs Set the microseconds. */ timestamp::timestamp(time_t secs, int32_t usecs) : _secs(secs), _usecs(0) { add_useconds(usecs); } /** * Copy constructor. * * @param[in] right The object to copy. */ timestamp::timestamp(const timestamp& right) : _secs{right._secs}, _usecs{right._usecs} {} /** * Assignment operator. * * @param[in] right The object to copy. * * @return This object. */ timestamp& timestamp::operator=(const timestamp& right) { if (this != &right) { _secs = right._secs; _usecs = right._usecs; } return *this; } /** * Compare if two object are equal. * * @param[in] right The object to compare. * * @return True if equal, otherwise false. */ bool timestamp::operator==(const timestamp& right) const noexcept { return _secs == right._secs && _usecs == right._usecs; } /** * Compare if two object are not equal. * * @param[in] right The object to compare. * * @return True if not equal, otherwise false. */ bool timestamp::operator!=(const timestamp& right) const noexcept { return _secs != right._secs || _usecs != right._usecs; } /** * Compare if this is less than an object. * * @param[in] right The object to compare. * * @return True if less, otherwise false. */ bool timestamp::operator<(const timestamp& right) const noexcept { return _secs < right._secs || (_secs == right._secs && _usecs < right._usecs); } /** * Compare if this if less or equal than an object. * * @param[in] right The object to compare. * * @return True if less or equal, otherwise false. */ bool timestamp::operator<=(const timestamp& right) const noexcept { return _secs < right._secs || (_secs == right._secs && _usecs <= right._usecs); } /** * Compare if this if greater than an object. * * @param[in] right The object to compare. * * @return True if greater, otherwise false. */ bool timestamp::operator>(const timestamp& right) const noexcept { return _secs > right._secs || (_secs == right._secs && _usecs > right._usecs); } /** * Compare if this is greater or equal than an object. * * @param[in] right The object to compare. * * @return True if greater or equal, otherwise false. */ bool timestamp::operator>=(const timestamp& right) const noexcept { return _secs > right._secs || (_secs == right._secs && _usecs >= right._usecs); } /** * Add timestamp. * * @param[in] right The object to add. * * @return The new timestamp. */ timestamp timestamp::operator+(const timestamp& right) const { timestamp ret(*this); ret += right; return ret; } /** * Substract timestamp. * * @param[in] right The object to substract. * * @return The new timestamp. */ timestamp timestamp::operator-(const timestamp& right) const { timestamp ret(*this); ret -= right; return ret; } /** * Add timestamp. * * @param[in] right The object to add. * * @return This object. */ timestamp& timestamp::operator+=(const timestamp& right) { _secs += right._secs; _usecs += right._usecs; if (_usecs >= 1000000) { _usecs -= 1000000; _secs++; } return *this; } /** * Substract timestamp. * * @param[in] right The object to substract. * * @return This object. */ timestamp& timestamp::operator-=(const timestamp& right) { _secs -= right._secs; int32_t d = static_cast(_usecs) - static_cast(right._usecs); if (d < 0) { _usecs = d + 1000000; _secs--; } return *this; } /** * Add milliseconds to this object. * * @param[in] msecs Time in milliseconds. */ void timestamp::add_mseconds(int32_t msecs) { add_useconds(msecs * 1000); } /** * Add microseconds to this object. * * @param[in] usecs Time in microseconds. */ void timestamp::add_useconds(int32_t usecs) { int64_t us(_usecs); us += usecs; if (us < 0) { _secs += us / 1000000; // Will be negative. us %= 1000000; if (us) { // Non zero means negative value. --_secs; us += 1000000; } } else if (us >= 1000000) { _secs += us / 1000000; us %= 1000000; } _usecs = static_cast(us); } /** * Reset timestamp. */ void timestamp::clear() noexcept { _secs = 0; _usecs = 0; } /** * Get the maximum time. * * @return Maximum time. */ timestamp timestamp::max_time() noexcept { timestamp t; t._secs = std::numeric_limits::max(); t._usecs = 999999; return t; } /** * Get the minimum time. * * @return Minimum time. */ timestamp timestamp::min_time() noexcept { timestamp t; t._secs = std::numeric_limits::min(); t._usecs = 0; return t; } /** * Get the current system time. * * @return The current timestamp. */ timestamp timestamp::now() noexcept { timeval tv; gettimeofday(&tv, NULL); return timestamp(tv.tv_sec, tv.tv_usec); } /** * Substract milliseconds from this object. * * @param[in] msecs Time in milliseconds. */ void timestamp::sub_mseconds(int32_t msecs) { add_mseconds(-msecs); } /** * Substract seconds from this object. * * @param[in] secs Time in seconds. */ void timestamp::sub_seconds(time_t secs) noexcept { _secs -= secs; } /** * Add seconds from this object. * * @param[in] secs Time in seconds. */ void timestamp::add_seconds(time_t secs) noexcept { _secs += secs; } /** * Substract microseconds from this object. * * @param[in] usecs Time in microseconds. */ void timestamp::sub_useconds(int32_t usecs) { add_useconds(-usecs); } /** * Get the time in milliseconds. * * @return The time in milliseconds. */ int64_t timestamp::to_mseconds() const noexcept { return _secs * 1000ll + _usecs / 1000; } /** * Get the time in seconds. * * @return The time in seconds. */ time_t timestamp::to_seconds() const noexcept { return _secs; } /** * Get the time in microseconds. * * @return The time in microseconds. */ int64_t timestamp::to_useconds() const noexcept { return _secs * 1000000ll + _usecs; } centreon-clib-21.04.2/test/000077500000000000000000000000001407153644500153745ustar00rootroot00000000000000centreon-clib-21.04.2/test/CMakeLists.txt000066400000000000000000000070141407153644500201360ustar00rootroot00000000000000## ## 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 ## # Set directories. set(TEST_DIR "${PROJECT_SOURCE_DIR}/test") # Add subdirectories. add_subdirectory("clib") add_subdirectory("exceptions") add_subdirectory("io") add_subdirectory("logging") add_subdirectory("misc") # bin_test_process_output set(TEST_NAME "bin_test_process_output") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") # shared_testing_library set(LIB_NAME "shared_testing_library") add_library("${LIB_NAME}" SHARED "${TEST_DIR}/${LIB_NAME}.cc") set(CLIB_TESTS handle_manager_add handle_manager_constructor handle_manager_remove_by_handle handle_manager_remove_by_handle_listener handle_manager_multiplex library_resolve library_load process_env process_kill process_return process_terminate process_timeout process_wait_timeout ) foreach (TEST_NAME ${CLIB_TESTS}) add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") endforeach () # process_output set(TEST_NAME "process_output") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}_stderr" "${TEST_NAME}" "err") add_test("${TEST_NAME}_stdout" "${TEST_NAME}" "out") # task_manager tests set(TASK_MANAGER_LIST task_manager_add task_manager_add_recurring task_manager_execute task_manager_execute_recurring task_manager_next_execution_time task_manager_remove_by_id task_manager_remove_by_task task_manager_remove_self ) foreach(name ${TASK_MANAGER_LIST}) add_executable("${name}" "${TEST_DIR}/${name}.cc") target_link_libraries("${name}" "${DEFAULT_LINK_NAME}") add_test("${name}" "${name}") endforeach(name) # task_manager tests set(TIMESTAMP_LIST timestamp_add timestamp_add_mseconds timestamp_add_seconds timestamp_add_useconds timestamp_clear timestamp_constructor timestamp_equal timestamp_not_equal timestamp_copy timestamp_greater timestamp_greater_or_equal timestamp_less_or_equal timestamp_less timestamp_sub timestamp_sub_mseconds timestamp_sub_seconds timestamp_sub_useconds timestamp_to_mseconds timestamp_to_seconds timestamp_to_useconds ) foreach(name ${TIMESTAMP_LIST}) add_executable("${name}" "${TEST_DIR}/${name}.cc") target_link_libraries("${name}" "${DEFAULT_LINK_NAME}") add_test("${name}" "${name}") endforeach(name) if (WITH_COVERAGE) include("${PROJECT_SOURCE_DIR}/cmake/CodeCoverage.cmake") APPEND_COVERAGE_COMPILER_FLAGS() set(COVERAGE_EXCLUDES '${PROJECT_BINARY_DIR}/*' '${PROJECT_SOURCE_DIR}/test/*' '/usr/include/*') SETUP_TARGET_FOR_COVERAGE( NAME test-coverage EXECUTABLE ctest # Executable in PROJECT_BINARY_DIR DEPENDENCIES ${CLIB_TESTS} ${TASK_MANAGER_LIST} ${TIMESTAMP_LIST} ) endif () centreon-clib-21.04.2/test/bin_test_process_output.cc000066400000000000000000000057621407153644500227020ustar00rootroot00000000000000/* ** 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 #include #include #include #include /** * Find line into the environement. * * @param[in] data line on form key=value. * @param[in] env The environment. * * @return True if data is find into env, otherwise false. */ static bool find(char const* data, char** env) { for (unsigned int i(0); env[i]; ++i) if (!strcmp(data, env[i])) return (true); return (false); } /** * Check if the content of ref is in env array. * * @param[in] ref The content reference. * @param[in] env The content to check. * * @return EXIT_SUCCESS on success, otherwise EXIT_FAILURE. */ static int check_env(char** ref, char** env) { for (unsigned int i(0); ref[i]; ++i) if (!find(ref[i], env)) return (EXIT_FAILURE); return (EXIT_SUCCESS); } /** * Read stdin and write into the stdout. * * @param[in] type If type if "err" write data on stderr, * otherwise write on stdout. * * @return The total bytes written. */ static int check_output(char const* type) { int output(strcmp(type, "err") ? 1 : 2); int total(0); int size(0); char buffer[1024]; while ((size = read(0, buffer, sizeof(buffer))) > 0) total += write(output, buffer, size); return (EXIT_SUCCESS); } /** * Usage of the application. * * @param[in] appname The application name. */ static void usage(char const* appname) { std::cerr << "usage: " << appname << std::endl << " check_env key1=value1 keyx=valuex..." << std::endl << " check_output err|out" << std::endl << " check_return value" << std::endl << " check_sleep value" << std::endl; exit(EXIT_FAILURE); } /** * This main test the class process. */ int main(int argc, char** argv, char** env) { try { if (argc != 1) { if (!strcmp(argv[1], "check_env")) return (check_env(argv + 2, env)); if (argc == 3) { if (!strcmp(argv[1], "check_output")) return (check_output(argv[2])); if (!strcmp(argv[1], "check_return")) return (atoi(argv[2])); if (!strcmp(argv[1], "check_sleep")) { int timeout(atoi(argv[2])); sleep(timeout); return (timeout); } } } usage(argv[0]); } catch (std::exception const& e) { std::cerr << "error:" << e.what() << std::endl; return (EXIT_FAILURE); } } centreon-clib-21.04.2/test/clib/000077500000000000000000000000001407153644500163055ustar00rootroot00000000000000centreon-clib-21.04.2/test/clib/CMakeLists.txt000066400000000000000000000030421407153644500210440ustar00rootroot00000000000000## ## 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 ## # Set test directory. set(TEST_DIR "${TEST_DIR}/clib") # Version major. set(TEST_NAME "clib_version_major") add_executable("${TEST_NAME}" "${TEST_DIR}/version/major.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Version minor. set(TEST_NAME "clib_version_minor") add_executable("${TEST_NAME}" "${TEST_DIR}/version/minor.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Version patch. set(TEST_NAME "clib_version_patch") add_executable("${TEST_NAME}" "${TEST_DIR}/version/patch.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Version string. set(TEST_NAME "clib_version_string") add_executable("${TEST_NAME}" "${TEST_DIR}/version/string.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") centreon-clib-21.04.2/test/clib/version/000077500000000000000000000000001407153644500177725ustar00rootroot00000000000000centreon-clib-21.04.2/test/clib/version/major.cc000066400000000000000000000027101407153644500214110ustar00rootroot00000000000000/* ** 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 #include "com/centreon/clib/version.hh" using namespace com::centreon::clib; /** * Check that the version major returned by the library matches the * header. * * @return 0 on success. */ int main() { // Check. int retval((version::get_major() != version::major) || (version::major != CENTREON_CLIB_VERSION_MAJOR)); // Message. if (retval) std::cout << "Version major mismatch" << std::endl << " library returned " << version::get_major() << std::endl << " header returned " << version::major << std::endl << " macro returned " << CENTREON_CLIB_VERSION_MAJOR << std::endl; else std::cout << "Version major is consistent (" << version::major << ")" << std::endl; // Return check result. return (retval); } centreon-clib-21.04.2/test/clib/version/minor.cc000066400000000000000000000027101407153644500214250ustar00rootroot00000000000000/* ** 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 #include "com/centreon/clib/version.hh" using namespace com::centreon::clib; /** * Check that the version minor returned by the library matches the * header. * * @return 0 on success. */ int main() { // Check. int retval((version::get_minor() != version::minor) || (version::minor != CENTREON_CLIB_VERSION_MINOR)); // Message. if (retval) std::cout << "Version minor mismatch" << std::endl << " library returned " << version::get_minor() << std::endl << " header returned " << version::minor << std::endl << " macro returned " << CENTREON_CLIB_VERSION_MINOR << std::endl; else std::cout << "Version minor is consistent (" << version::minor << ")" << std::endl; // Return check result. return (retval); } centreon-clib-21.04.2/test/clib/version/patch.cc000066400000000000000000000027101407153644500214000ustar00rootroot00000000000000/* ** 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 #include "com/centreon/clib/version.hh" using namespace com::centreon::clib; /** * Check that the version patch returned by the library matches the * header. * * @return 0 on success. */ int main() { // Check. int retval((version::get_patch() != version::patch) || (version::patch != CENTREON_CLIB_VERSION_PATCH)); // Message. if (retval) std::cout << "Version patch mismatch" << std::endl << " library returned " << version::get_patch() << std::endl << " header returned " << version::patch << std::endl << " macro returned " << CENTREON_CLIB_VERSION_PATCH << std::endl; else std::cout << "Version patch is consistent (" << version::patch << ")" << std::endl; // Return check result. return (retval); } centreon-clib-21.04.2/test/clib/version/string.cc000066400000000000000000000027551407153644500216200ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/clib/version.hh" using namespace com::centreon::clib; /** * Check that the version string returned by the library matches the * header. * * @return 0 on success. */ int main() { // Check. int retval(strcmp(version::get_string(), version::string) || strcmp(version::string, CENTREON_CLIB_VERSION_STRING)); // Message. if (retval) std::cout << "Version string mismatch" << std::endl << " library returned " << version::get_string() << std::endl << " header returned " << version::string << std::endl << " macro returned " << CENTREON_CLIB_VERSION_STRING << std::endl; else std::cout << "Version string is consistent (" << version::string << ")" << std::endl; // Return check result. return retval; } centreon-clib-21.04.2/test/exceptions/000077500000000000000000000000001407153644500175555ustar00rootroot00000000000000centreon-clib-21.04.2/test/exceptions/CMakeLists.txt000066400000000000000000000055131407153644500223210ustar00rootroot00000000000000## ## 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 ## # Set directories. set(TEST_DIR "${TEST_DIR}/exceptions") # basic_constructor set(TEST_NAME "basic_constructor") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # basic_copy set(TEST_NAME "basic_copy") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # basic_insert_char set(TEST_NAME "basic_insert_char") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # basic_insert_long set(TEST_NAME "basic_insert_long") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # basic_insert_pchar set(TEST_NAME "basic_insert_pchar") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # basic_insert_ulong set(TEST_NAME "basic_insert_ulong") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # basic_insert_int set(TEST_NAME "basic_insert_int") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # basic_insert_longlong set(TEST_NAME "basic_insert_longlong") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # basic_insert_uint set(TEST_NAME "basic_insert_uint") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # basic_insert_ulonglong set(TEST_NAME "basic_insert_ulonglong") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") centreon-clib-21.04.2/test/exceptions/basic_constructor.cc000066400000000000000000000021431407153644500236120ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Check the basic constructor. * * @return 0 on success. */ int main() { const unsigned int line = __LINE__; basic ex1; basic ex2(__FILE__, FUNCTION, line); std::ostringstream oss; oss << "[" << __FILE__ << ":" << line << "(" << FUNCTION << ")] "; return (strcmp(ex1.what(), "") || strcmp(ex2.what(), oss.str().c_str())); } centreon-clib-21.04.2/test/exceptions/basic_copy.cc000066400000000000000000000022001407153644500221710ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Check the basic copy. * * @return 0 on success. */ int main() { static char const message[] = "Centreon Clib"; const unsigned int line = __LINE__; basic ex(__FILE__, FUNCTION, line); ex << message; std::ostringstream oss; oss << "[" << __FILE__ << ":" << line << "(" << FUNCTION << ")] " << message; return (strcmp(ex.what(), oss.str().c_str())); } centreon-clib-21.04.2/test/exceptions/basic_insert_char.cc000066400000000000000000000017771407153644500235420ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Check the basic insert char. * * @return 0 on success. */ int main() { basic ex; ex << static_cast(CHAR_MIN); ex << static_cast(CHAR_MAX); char ref[] = {CHAR_MIN, CHAR_MAX, 0}; return (strcmp(ex.what(), ref)); } centreon-clib-21.04.2/test/exceptions/basic_insert_int.cc000066400000000000000000000020521407153644500234020ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Check the basic insert int. * * @return 0 on success. */ int main() { basic ex; ex << static_cast(INT_MIN); ex << static_cast(INT_MAX); std::ostringstream oss; oss << INT_MIN << INT_MAX; return (strcmp(ex.what(), oss.str().c_str())); } centreon-clib-21.04.2/test/exceptions/basic_insert_long.cc000066400000000000000000000020611407153644500235470ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Check the basic insert long. * * @return 0 on success. */ int main() { basic ex; ex << static_cast(LONG_MIN); ex << static_cast(LONG_MAX); std::ostringstream oss; oss << LONG_MIN << LONG_MAX; return (strcmp(ex.what(), oss.str().c_str())); } centreon-clib-21.04.2/test/exceptions/basic_insert_longlong.cc000066400000000000000000000021041407153644500244250ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Check the basic insert long long. * * @return 0 on success. */ int main() { basic ex; ex << static_cast(LLONG_MIN); ex << static_cast(LLONG_MAX); std::ostringstream oss; oss << LLONG_MIN << LLONG_MAX; return (strcmp(ex.what(), oss.str().c_str())); } centreon-clib-21.04.2/test/exceptions/basic_insert_pchar.cc000066400000000000000000000016211407153644500237060ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Check the basic insert string. * * @return 0 on success. */ int main() { basic ex; ex << __FILE__; return (strcmp(ex.what(), __FILE__)); } centreon-clib-21.04.2/test/exceptions/basic_insert_uint.cc000066400000000000000000000020731407153644500235720ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Check the basic insert unsigned int. * * @return 0 on success. */ int main() { basic ex; ex << static_cast(0); ex << static_cast(UINT_MAX); std::ostringstream oss; oss << 0 << UINT_MAX; return (strcmp(ex.what(), oss.str().c_str())); } centreon-clib-21.04.2/test/exceptions/basic_insert_ulong.cc000066400000000000000000000021001407153644500237260ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Check the basic insert unsigned long. * * @return 0 on success. */ int main() { basic ex; ex << static_cast(0); ex << static_cast(ULONG_MAX); std::ostringstream oss; oss << 0 << ULONG_MAX; return (strcmp(ex.what(), oss.str().c_str())); } centreon-clib-21.04.2/test/exceptions/basic_insert_ulonglong.cc000066400000000000000000000021211407153644500246110ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/exceptions/basic.hh" using namespace com::centreon::exceptions; /** * Check the basic insert unsigned long long. * * @return 0 on success. */ int main() { basic ex; ex << static_cast(0); ex << static_cast(ULLONG_MAX); std::ostringstream oss; oss << 0 << ULLONG_MAX; return (strcmp(ex.what(), oss.str().c_str())); } centreon-clib-21.04.2/test/handle_manager_add.cc000066400000000000000000000057601407153644500214500ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/handle_listener.hh" #include "com/centreon/handle_manager.hh" #include "com/centreon/io/file_stream.hh" using namespace com::centreon; /** * @class listener * @brief litle implementation of handle listener to test the * handle manager. */ class listener : public handle_listener { public: listener() {} ~listener() throw () {} void error(handle& h) { (void)h; } }; /** * Try to insert a null pointer handle argument. * * @return True on sucess, otherwise false. */ static bool null_handle() { try { handle_manager hm; listener l; hm.add(NULL, &l); } catch (std::exception const& e) { (void)e; return (true); } return (false); } /** * Try to insert a null pointer listener argument. * * @return True on sucess, otherwise false. */ static bool null_listener() { try { handle_manager hm; io::file_stream fs; hm.add(&fs, NULL); } catch (std::exception const& e) { (void)e; return (true); } return (false); } /** * Check basic insert into handle manager. * * @return True on sucess, otherwise false. */ static bool basic_add() { try { handle_manager hm; io::file_stream fs(stdin); listener l; hm.add(&fs, &l); } catch (std::exception const& e) { (void)e; return (false); } return (true); } /** * Check multiple insert into handle manager. * * @return True on sucess, otherwise false. */ static bool double_add() { try { handle_manager hm; io::file_stream fs(stdin); listener l; hm.add(&fs, &l); try { hm.add(&fs, &l); } catch (std::exception const& e) { (void)e; return (true); } } catch (std::exception const& e) { (void)e; } return (false); } /** * Check the handle manager add. * * @return 0 on success. */ int main() { try { if (!null_handle()) throw (basic_error() << "invalid handler is set"); if (!null_listener()) throw (basic_error() << "invalid listener is set"); if (!basic_add()) throw (basic_error() << "add failed"); if (!double_add()) throw (basic_error() << "double add failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/handle_manager_constructor.cc000066400000000000000000000022141407153644500232740ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/handle_manager.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; /** * Check the handle manager constructor. * * @return 0 on success. */ int main() { try { { handle_manager hm(NULL); } { task_manager tm; handle_manager hm(&tm); } } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/handle_manager_multiplex.cc000066400000000000000000000076111407153644500227400ustar00rootroot00000000000000/* ** 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 #include #include #include #ifndef _WIN32 # include #endif // !_WIN32 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/handle_listener.hh" #include "com/centreon/handle_manager.hh" #include "com/centreon/io/file_stream.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; /** * @class listener * @brief litle implementation of handle listener to test the * handle manager. */ class listener : public handle_listener { public: listener( handle& ref_h, bool want_read, bool want_write) : _is_call(false), _ref_h(ref_h), _want_read(want_read), _want_write(want_write) {} ~listener() throw () {} void error(handle& h) { if (&_ref_h == &h) _is_call = true; } bool is_call() const throw () { return (_is_call); } void read(handle& h) { if (&_ref_h == &h) _is_call = true; } bool want_read(handle& h) { (void)h; return (_want_read); } bool want_write(handle& h) { (void)h; return (_want_write); } void write(handle& h) { if (&_ref_h == &h) _is_call = true; } private: bool _is_call; handle& _ref_h; bool _want_read; bool _want_write; }; /** * Try to insert a null task manager into handle manager. * * @return True on success, otherwise false. */ static bool null_task_manager() { try { handle_manager hm; hm.multiplex(); } catch (std::exception const& e) { (void)e; return (true); } return (false); } /** * Try to execute without any handle. * * @return True on success, otherwise false. */ static bool empty_handle_manager() { try { task_manager tm; handle_manager hm(&tm); hm.multiplex(); } catch (std::exception const& e) { (void)e; return (false); } return (true); } /** * Check if write is calling. * * @return True on success, otherwise false. */ static bool basic_multiplex_write() { task_manager tm; handle_manager hm(&tm); io::file_stream fs(stdout); listener l(fs, false, true); hm.add(&fs, &l); hm.multiplex(); return (l.is_call()); } #ifndef _WIN32 /** * Check if close is calling. * * @return True on success, otherwise false. */ static bool basic_multiplex_close() { ::close(STDIN_FILENO); task_manager tm; handle_manager hm(&tm); io::file_stream fs(stdin); listener l(fs, true, true); hm.add(&fs, &l); hm.multiplex(); return (l.is_call()); } #endif // !_WIN32 /** * Check the handle manager multiplexing. * * @return 0 on success. */ int main() { try { if (!null_task_manager()) throw (basic_error() << "handle manager failed to multiplex:" \ "try to multiplex null pointer"); if (!empty_handle_manager()) throw (basic_error() << "handle manager failed to multiplex:" \ "try to multiplex nothing"); if (!basic_multiplex_write()) throw (basic_error() << "multiplex one handle to write failed"); #ifndef _WIN32 if (!basic_multiplex_close()) throw (basic_error() << "multiplex one handle to close failed"); #endif // !_WIN32 } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/handle_manager_remove_by_handle.cc000066400000000000000000000033211407153644500242110ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/handle_listener.hh" #include "com/centreon/handle_manager.hh" #include "com/centreon/io/file_stream.hh" using namespace com::centreon; /** * @class listener * @brief litle implementation of handle listener to test the * handle manager. */ class listener : public handle_listener { public: listener() {} ~listener() throw () {} void error(handle& h) { (void)h; } }; /** * Check the handle manager remove by handle. * * @return 0 on success. */ int main() { try { handle_manager hm; if (hm.remove(static_cast(NULL))) throw (basic_error() << "remove null pointer"); io::file_stream fs(stdin); if (hm.remove(&fs)) throw (basic_error() << "remove invalid handle"); listener l; hm.add(&fs, &l); if (!hm.remove(&fs)) throw (basic_error() << "remove failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/handle_manager_remove_by_handle_listener.cc000066400000000000000000000037271407153644500261300ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/handle_listener.hh" #include "com/centreon/handle_manager.hh" #include "com/centreon/io/file_stream.hh" using namespace com::centreon; /** * @class listener * @brief litle implementation of handle listener to test the * handle manager. */ class listener : public handle_listener { public: listener() {} ~listener() throw () {} void error(handle& h) { (void)h; } }; /** * Check the handle manager remove by handle listener. * * @return 0 on success. */ int main() { try { handle_manager hm; if (hm.remove(static_cast(NULL))) throw (basic_error() << "remove null pointer"); listener l; if (hm.remove(&l)) throw (basic_error() << "remove invalid listener"); io::file_stream fs1(stdin); hm.add(&fs1, &l); if (hm.remove(&l) != 1) throw (basic_error() << "remove one listener failed"); hm.add(&fs1, &l); io::file_stream fs2(stdout); hm.add(&fs2, &l); io::file_stream fs3(stderr); hm.add(&fs3, &l); if (hm.remove(&l) != 3) throw (basic_error() << "remove three listener failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/io/000077500000000000000000000000001407153644500160035ustar00rootroot00000000000000centreon-clib-21.04.2/test/io/CMakeLists.txt000066400000000000000000000076041407153644500205520ustar00rootroot00000000000000## ## 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 ## # Set directories. set(TEST_DIR "${TEST_DIR}/io") # directory_entry tests. # Copy. set(TEST_NAME "io_directory_entry_copy") add_executable("${TEST_NAME}" "${TEST_DIR}/directory_entry/copy.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Copy. set(TEST_NAME "io_directory_entry_current_path") add_executable("${TEST_NAME}" "${TEST_DIR}/directory_entry/current_path.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Default constructor. set(TEST_NAME "io_directory_entry_ctor_default") add_executable("${TEST_NAME}" "${TEST_DIR}/directory_entry/ctor_default.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Filter. set(TEST_NAME "io_directory_entry_filter") add_executable("${TEST_NAME}" "${TEST_DIR}/directory_entry/filter.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # file_entry tests. # Copy. set(TEST_NAME "io_file_entry_copy") add_executable("${TEST_NAME}" "${TEST_DIR}/file_entry/copy.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Default constructor. set(TEST_NAME "io_file_entry_ctor_default") add_executable("${TEST_NAME}" "${TEST_DIR}/file_entry/ctor_default.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Pathinfo. set(TEST_NAME "io_file_entry_pathinfo") add_executable("${TEST_NAME}" "${TEST_DIR}/file_entry/pathinfo.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Permission. set(TEST_NAME "io_file_entry_permission") add_executable("${TEST_NAME}" "${TEST_DIR}/file_entry/permission.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Size. set(TEST_NAME "io_file_entry_size") add_executable("${TEST_NAME}" "${TEST_DIR}/file_entry/size.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # file_stream tests. # Default constructor. set(TEST_NAME "io_file_stream_ctor_default") add_executable("${TEST_NAME}" "${TEST_DIR}/file_stream/ctor_default.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Create/exists/remove. set(TEST_NAME "io_file_stream_create_exists_remove") add_executable("${TEST_NAME}" "${TEST_DIR}/file_stream/create_exists_remove.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Write. set(TEST_NAME "io_file_stream_write") add_executable("${TEST_NAME}" "${TEST_DIR}/file_stream/write.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Read. set(TEST_NAME "io_file_stream_read") add_executable("${TEST_NAME}" "${TEST_DIR}/file_stream/read.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # Rename. set(TEST_NAME "io_file_stream_rename") add_executable("${TEST_NAME}" "${TEST_DIR}/file_stream/rename.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") centreon-clib-21.04.2/test/io/directory_entry/000077500000000000000000000000001407153644500212305ustar00rootroot00000000000000centreon-clib-21.04.2/test/io/directory_entry/copy.cc000066400000000000000000000024221407153644500225110ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/directory_entry.hh" using namespace com::centreon; /** * Check copy object. * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_FAILURE); try { io::directory_entry e1("."); io::directory_entry e2(e1); if (e1 != e2) throw(basic_error() << "copy constuctor failed"); io::directory_entry e3 = e1; if (e1 != e3) throw(basic_error() << "copy operator failed"); ret = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } return (ret); } centreon-clib-21.04.2/test/io/directory_entry/ctor_default.cc000066400000000000000000000025621407153644500242170ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/directory_entry.hh" using namespace com::centreon; /** * Check that class can be created. * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_FAILURE); try { { io::directory_entry entry(NULL); if (!entry.entry().path().empty()) throw(basic_error() << "invalid constructor: path is not empty"); } { io::directory_entry entry("."); if (entry.entry().path().empty()) throw(basic_error() << "invalid constructor: path is empty"); } ret = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } return (ret); } centreon-clib-21.04.2/test/io/directory_entry/current_path.cc000066400000000000000000000022441407153644500242370ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/directory_entry.hh" using namespace com::centreon; /** * Check current_path. * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_FAILURE); try { std::string path(io::directory_entry::current_path()); if (path.empty()) throw(basic_error() << "invalid current_path"); ret = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } return (ret); } centreon-clib-21.04.2/test/io/directory_entry/filter.cc000066400000000000000000000031571407153644500230320ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/directory_entry.hh" using namespace com::centreon; /** * Check if filter work. * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_FAILURE); try { { io::directory_entry entry("."); std::list lst_all(entry.entry_list()); std::list lst_point(entry.entry_list(".*")); std::list lst_de(entry.entry_list("io_directory_entry*")); if (lst_all.size() < lst_point.size() + lst_de.size()) throw(basic_error() << "invalid result size: list all"); if (lst_point.size() < 2) throw(basic_error() << "invalid result size: list point"); if (lst_de.size() < 2) throw(basic_error() << "invalid result size: list directory entry"); } ret = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } return (ret); } centreon-clib-21.04.2/test/io/file_entry/000077500000000000000000000000001407153644500201435ustar00rootroot00000000000000centreon-clib-21.04.2/test/io/file_entry/copy.cc000066400000000000000000000024471407153644500214330ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_entry.hh" using namespace com::centreon; /** * Check copy object. * * @return EXIT_SUCCESS on success. */ int main(int argc, char* argv[]) { (void)argc; int ret(EXIT_FAILURE); try { io::file_entry e1(argv[0]); io::file_entry e2(e1); if (e1 != e2) throw(basic_error() << "copy constuctor failed"); io::file_entry e3 = e1; if (e1 != e3) throw(basic_error() << "copy operator failed"); ret = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } return (ret); } centreon-clib-21.04.2/test/io/file_entry/ctor_default.cc000066400000000000000000000025741407153644500231350ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_entry.hh" using namespace com::centreon; /** * Check that class can be created. * * @return EXIT_SUCCESS on success. */ int main(int argc, char* argv[]) { (void)argc; int ret(EXIT_FAILURE); try { { io::file_entry entry(NULL); if (!entry.path().empty()) throw(basic_error() << "invalid constructor: path is not empty"); } { io::file_entry entry(argv[0]); if (entry.path().empty()) throw(basic_error() << "invalid constructor: path is empty"); } ret = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } return (ret); } centreon-clib-21.04.2/test/io/file_entry/pathinfo.cc000066400000000000000000000047541407153644500222740ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_entry.hh" #include "com/centreon/io/file_stream.hh" unsigned int const DATA_SIZE = 42; using namespace com::centreon; /** * Create temporary file. * * @param[in] path The temporary file path. */ static void create_fake_file(std::string const& path) { if (!io::file_stream::exists(path)) { io::file_stream fs; fs.open(path, "w"); fs.close(); } } /** * Check path information. * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_FAILURE); std::string p1("/tmp/test.ext"); std::string p2("/tmp/.test"); std::string p3("/tmp/test"); try { create_fake_file(p1); create_fake_file(p2); create_fake_file(p3); io::file_entry e1(p1); if (e1.base_name() != "test") throw(basic_error() << "invalid base name"); if (e1.file_name() != "test.ext") throw(basic_error() << "invalid file name"); if (e1.directory_name() != "/tmp") throw(basic_error() << "invalid directory name"); io::file_entry e2(p2); if (e2.base_name() != ".test") throw(basic_error() << "invalid base name"); if (e2.file_name() != ".test") throw(basic_error() << "invalid file name"); if (e2.directory_name() != "/tmp") throw(basic_error() << "invalid directory name"); io::file_entry e3(p3); if (e3.base_name() != "test") throw(basic_error() << "invalid base name"); if (e3.file_name() != "test") throw(basic_error() << "invalid file name"); if (e3.directory_name() != "/tmp") throw(basic_error() << "invalid directory name"); ret = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } io::file_stream::remove(p1); io::file_stream::remove(p2); io::file_stream::remove(p3); return (ret); } centreon-clib-21.04.2/test/io/file_entry/permission.cc000066400000000000000000000026131407153644500226440ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_entry.hh" using namespace com::centreon; /** * Check permission is valid. * * @return EXIT_SUCCESS on success. */ int main(int argc, char* argv[]) { (void)argc; int ret(EXIT_FAILURE); try { io::file_entry entry(argv[0]); if (entry.is_directory()) throw(basic_error() << "permission failed: is not a directory"); if (entry.is_link()) throw(basic_error() << "permission failed: is not a link"); if (!entry.is_regular()) throw(basic_error() << "permission failed: is a regular file"); ret = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } return (ret); } centreon-clib-21.04.2/test/io/file_entry/size.cc000066400000000000000000000034361407153644500214320ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_entry.hh" #include "com/centreon/io/file_stream.hh" unsigned int const DATA_SIZE = 42; using namespace com::centreon; /** * Check size is valid. * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_FAILURE); std::string temp(io::file_stream::temp_path()); try { { io::file_stream fs; fs.open(temp, "w"); fs.close(); } io::file_entry entry(temp); if (entry.size()) throw(basic_error() << "invalid file size: not empty"); { std::string data(DATA_SIZE, ' '); io::file_stream fs; fs.open(temp, "w"); fs.write(data.c_str(), data.size()); fs.close(); } if (entry.size()) throw(basic_error() << "invalid file size: not empty"); entry.refresh(); if (entry.size() != DATA_SIZE) throw(basic_error() << "invalid file size: is empty"); ret = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } if (io::file_stream::exists(temp)) io::file_stream::remove(temp); return (ret); } centreon-clib-21.04.2/test/io/file_stream/000077500000000000000000000000001407153644500202755ustar00rootroot00000000000000centreon-clib-21.04.2/test/io/file_stream/create_exists_remove.cc000066400000000000000000000037011407153644500250240ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_stream.hh" using namespace com::centreon; /** * Check that file can be created, checked for and removed properly. * * @return EXIT_SUCCESS on success. */ int main() { // Return value. int retval(EXIT_FAILURE); try { // Temporary path. char* path(io::file_stream::temp_path()); // Remove old file. io::file_stream::remove(path); // File must not exists. if (io::file_stream::exists(path)) throw(basic_error() << "file '" << path << "' exists whereas it should not"); // Create file. { io::file_stream fs; fs.open(path, "w"); fs.close(); } // File must exists. if (!io::file_stream::exists(path)) throw(basic_error() << "file '" << path << "' does not exist whereas it should"); // Remove file. // File must not exists. if (!io::file_stream::remove(path) || io::file_stream::exists(path)) throw(basic_error() << "file '" << path << "' exists whereas it should not"); // Success. retval = EXIT_SUCCESS; } catch (std::exception const& e) { std::cout << e.what() << std::endl; } return (retval); } centreon-clib-21.04.2/test/io/file_stream/ctor_default.cc000066400000000000000000000016211407153644500232570ustar00rootroot00000000000000/* ** Copyright 2012-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/io/file_stream.hh" using namespace com::centreon; /** * Check that file_stream is properly default constructed. * * @return 0 on success. */ int main() { io::file_stream fs; return (fs.get_native_handle() != native_handle_null); } centreon-clib-21.04.2/test/io/file_stream/read.cc000066400000000000000000000031661407153644500215250ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_stream.hh" using namespace com::centreon; /** * Check that file_stream can be read from. * * @return 0 on success. */ int main() { // Generate temporary file name. char const* tmp_file_name(io::file_stream::temp_path()); // Open temporary file. io::file_stream tmp_file_stream; tmp_file_stream.open(tmp_file_name, "w"); // Return value. int retval(0); // Write. char const* data("some data"); if (tmp_file_stream.write(data, static_cast(strlen(data))) == 0) retval = 1; else { // NULL-read. try { tmp_file_stream.read(NULL, 1); retval = 1; } catch (exceptions::basic const& e) { (void)e; } // Real read. char buffer[1024]; tmp_file_stream.close(); tmp_file_stream.open(tmp_file_name, "r"); retval |= (tmp_file_stream.read(buffer, sizeof(buffer)) == 0); } return (retval); } centreon-clib-21.04.2/test/io/file_stream/rename.cc000066400000000000000000000041661407153644500220620ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_stream.hh" using namespace com::centreon; /** * Check that file_stream can be rename file. * * @return 0 on success. */ int main() { int ret(1); // Generate temporary file name. char const* file_name("./rename_file_stream.test"); char const* new_file_name("./new_rename_file_stream.test"); char data[] = "some data"; try { // Write data. { // Open file. io::file_stream file(NULL, true); file.open(file_name, "w"); // Write. if (!file.write(data, sizeof(data))) throw(basic_error() << "write data failed"); } // Rename file. if (!io::file_stream::rename(file_name, new_file_name)) throw(basic_error() << "rename failed"); // Read data. { // Open file. io::file_stream file(NULL, true); file.open(new_file_name, "r"); // Read. char buffer[64]; if (file.read(buffer, sizeof(buffer)) != sizeof(data)) throw(basic_error() << "read failed"); if (strncmp(buffer, data, sizeof(data))) throw(basic_error() << "invalid data"); } ret = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; } catch (...) { std::cerr << "error: catch all" << std::endl; } // Remove temporary file. io::file_stream::remove(file_name); io::file_stream::remove(new_file_name); return (ret); } centreon-clib-21.04.2/test/io/file_stream/write.cc000066400000000000000000000025611407153644500217420ustar00rootroot00000000000000/* ** Copyright 2012-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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_stream.hh" using namespace com::centreon; /** * Check that file_stream can be written to. * * @return 0 on success. */ int main() { // Generate temporary file name. char const* tmp_file_name(io::file_stream::temp_path()); // Open temporary file. io::file_stream tmp_file_stream; tmp_file_stream.open(tmp_file_name, "w"); // NULL write. try { tmp_file_stream.write(NULL, 1); } catch (exceptions::basic const& e) { (void)e; } // Real write. char const* data("some data"); return (tmp_file_stream.write(data, static_cast(strlen(data))) == 0); } centreon-clib-21.04.2/test/library_load.cc000066400000000000000000000033601407153644500203500ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/library.hh" using namespace com::centreon; /** * Check load library with a valid file. */ void load_library_success() { // create library object. library lib("./libshared_testing_library.so"); if (lib.is_loaded()) throw(basic_error() << "constructor failed"); // load library. lib.load(); if (!lib.is_loaded()) throw(basic_error() << "load failed"); // unload library. lib.unload(); if (lib.is_loaded()) throw(basic_error() << "unload failed"); } /** * load library without a valid file. */ void load_library_failed() { try { // create library object. library lib("libnot_found.so"); lib.load(); throw(basic_error() << "load failed: lib dosn't exist"); } catch (std::exception const& e) { (void)e; } } /** * Check the load symbole. * * @return 0 on success. */ int main() { try { load_library_success(); load_library_failed(); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/library_resolve.cc000066400000000000000000000036351407153644500211150ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/library.hh" using namespace com::centreon; /** * Check the resolve symbole. * * @return 0 on success. */ int main() { try { // create library object. library lib("./libshared_testing_library.so"); // load library. lib.load(); if (!lib.is_loaded()) throw(basic_error() << "load failed"); // load a "add" symbole. int (*my_add)(int, int); my_add = (int (*)(int, int))lib.resolve_proc("add"); if ((*my_add)(21, 21) != 42) throw(basic_error() << "resolve failed: invalid call result"); // load a "export_lib_name" symbole. char const* lib_name(*(char**)lib.resolve("export_lib_name")); if (lib_name != std::string("shared_testing_library")) throw(basic_error() << "resolve failed: invalid string"); // load a "export_lib_version" symbole. int lib_version(*(int*)lib.resolve("export_lib_version")); if (lib_version != 42) throw(basic_error() << "resolve failed: invalid value"); // unload library. lib.unload(); if (lib.is_loaded()) throw(basic_error() << "unload failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/logging/000077500000000000000000000000001407153644500170225ustar00rootroot00000000000000centreon-clib-21.04.2/test/logging/CMakeLists.txt000066400000000000000000000213161407153644500215650ustar00rootroot00000000000000## ## 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 ## # Set directories. set(TEST_DIR "${TEST_DIR}/logging") # backend_copy set(TEST_NAME "backend_copy") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # backend_with_pid set(TEST_NAME "backend_with_pid") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # backend_with_timestamp set(TEST_NAME "backend_with_timestamp") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # backend_with_thread_id set(TEST_NAME "backend_with_thread_id") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # engine_add set(TEST_NAME "engine_add") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # engine_is_log set(TEST_NAME "engine_is_log") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # engine_log set(TEST_NAME "engine_log") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # engine_remove_by_backend set(TEST_NAME "engine_remove_by_backend") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # engine_remove_by_id set(TEST_NAME "engine_remove_by_id") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # file_log set(TEST_NAME "file_log") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # file_log_multiline set(TEST_NAME "file_log_multiline") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # engine_with_thread set(TEST_NAME "engine_with_thread") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_copy set(TEST_NAME "temp_logger_copy") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_constructor set(TEST_NAME "temp_logger_constructor") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_char set(TEST_NAME "temp_logger_do_nothing_char") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_double set(TEST_NAME "temp_logger_do_nothing_double") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_int set(TEST_NAME "temp_logger_do_nothing_int") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_long set(TEST_NAME "temp_logger_do_nothing_long") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_long_long set(TEST_NAME "temp_logger_do_nothing_long_long") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_pvoid set(TEST_NAME "temp_logger_do_nothing_pvoid") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_std_string set(TEST_NAME "temp_logger_do_nothing_std_string") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_string set(TEST_NAME "temp_logger_do_nothing_string") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_uint set(TEST_NAME "temp_logger_do_nothing_uint") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_ulong set(TEST_NAME "temp_logger_do_nothing_ulong") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_do_nothing_ulong_long set(TEST_NAME "temp_logger_do_nothing_ulong_long") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_char set(TEST_NAME "temp_logger_log_char") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_double set(TEST_NAME "temp_logger_log_double") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_int set(TEST_NAME "temp_logger_log_int") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_long set(TEST_NAME "temp_logger_log_long") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_long_long set(TEST_NAME "temp_logger_log_long_long") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_pvoid set(TEST_NAME "temp_logger_log_pvoid") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_std_string set(TEST_NAME "temp_logger_log_std_string") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_string set(TEST_NAME "temp_logger_log_string") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_uint set(TEST_NAME "temp_logger_log_uint") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_ulong set(TEST_NAME "temp_logger_log_ulong") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # temp_logger_log_ulong_long set(TEST_NAME "temp_logger_log_ulong_long") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") centreon-clib-21.04.2/test/logging/backend_copy.cc000066400000000000000000000034721407153644500217600ustar00rootroot00000000000000/* ** 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 #include #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check if backend is equal. * * @param[in] b1 first backend to compare. * @param[in] b2 second backend to compare. * * @return True if equal, otherwise false. */ static bool is_same(backend const& b1, backend const& b2) { return (b1.enable_sync() == b2.enable_sync() && b1.show_pid() == b2.show_pid() && b1.show_timestamp() == b2.show_timestamp() && b1.show_thread_id() == b2.show_thread_id()); } /** * Check copy backend. * * @return 0 on success. */ int main() { int retval(0); try { backend_test ref(false, true, none, false); backend_test c1(ref); if (!is_same(ref, c1)) throw(basic_error() << "invalid copy constructor"); backend_test c2 = ref; if (!is_same(ref, c2)) throw(basic_error() << "invalid copy operator"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/backend_test.hh000066400000000000000000000036401407153644500217740ustar00rootroot00000000000000/* ** 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 CC_TEST_LOGGING_BACKEND_TEST_HH #define CC_TEST_LOGGING_BACKEND_TEST_HH #include "com/centreon/logging/backend.hh" CC_BEGIN() namespace logging { /** * @class backend_test * @brief litle implementation of backend to test logging engine. */ class backend_test : public backend { public: backend_test(bool is_sync = false, bool show_pid = false, time_precision show_timestamp = none, bool show_thread_id = false) : backend(is_sync, show_pid, show_timestamp, show_thread_id), _nb_call(0) {} ~backend_test() noexcept {} void close() noexcept {} std::string const& data() const noexcept { return _buffer; } void log(uint64_t types, uint32_t verbose, char const* msg, uint32_t size) noexcept { std::lock_guard lock(_lock); (void)types; (void)verbose; misc::stringifier header; _build_header(header); _buffer.append(header.data(), header.size()); _buffer.append(msg, size); ++_nb_call; } uint32_t get_nb_call() const noexcept { return _nb_call; } void open() {} void reopen() {} void reset() noexcept { _buffer.clear(); } private: std::string _buffer; uint32_t _nb_call; }; } CC_END() #endif // !CC_TEST_LOGGING_BACKEND_TEST_HH centreon-clib-21.04.2/test/logging/backend_with_pid.cc000066400000000000000000000036671407153644500226230ustar00rootroot00000000000000/* ** 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 #include #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check pid. * * @return True on success, otherwise false. */ static bool check_pid(std::string const& data, char const* msg) { if (data[0] != '[' || data.size() < 4) return (false); unsigned int pid_size( static_cast(data.size() - strlen(msg) - 1 - 3)); for (unsigned int i(1); i < pid_size; ++i) if (!isdigit(data[i])) return (false); if (data.compare(3 + pid_size, strlen(msg), msg)) return (false); return (true); } /** * Check add backend on to the logging engine. * * @return 0 on success. */ int main() { static char msg[] = "Centreon Clib test"; int retval; try { engine& e(engine::instance()); std::unique_ptr obj( new backend_test(false, true, none, false)); e.add(obj.get(), 1, 0); e.log(1, 0, msg, sizeof(msg)); if (!check_pid(obj->data(), msg)) throw(basic_error() << "log with pid failed"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/backend_with_thread_id.cc000066400000000000000000000035051407153644500237610ustar00rootroot00000000000000/* ** 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 #include #include #include #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check thread id. * * @return True on success, otherwise false. */ static bool check_thread_id(std::string const& data, char const* msg) { void* ptr(NULL); char message[1024]; int ret(sscanf(data.c_str(), "[%p] %s\n", &ptr, message)); return (ret == 2 && !strncmp(msg, message, strlen(msg))); } /** * Check add backend on to the logging engine. * * @return 0 on success. */ int main() { static char msg[] = "Centreon_Clib_test"; int retval; try { engine& e(engine::instance()); std::unique_ptr obj( new backend_test(false, false, none, true)); e.add(obj.get(), 1, 0); e.log(1, 0, msg, sizeof(msg)); if (!check_thread_id(obj->data(), msg)) throw(basic_error() << "log with thread id failed"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/backend_with_timestamp.cc000066400000000000000000000047321407153644500240440ustar00rootroot00000000000000/* ** 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 #include #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check time. * * @return True on success, otherwise false. */ static bool check_time(std::string const& data, char const* msg) { if (data[0] != '[' || data.size() < 4) return (false); unsigned int time_size( static_cast(data.size() - strlen(msg) - 1 - 3)); for (unsigned int i(1); i < time_size; ++i) if (!isdigit(data[i])) return (false); if (data.compare(3 + time_size, strlen(msg), msg)) return (false); return (true); } /** * Check add backend on to the logging engine. * * @return 0 on success. */ int main() { static char msg[] = "Centreon Clib test"; int retval; try { engine& e(engine::instance()); std::unique_ptr obj( new backend_test(false, false, none, false)); e.add(obj.get(), 1, 0); obj->show_timestamp(second); e.log(1, 0, msg, sizeof(msg)); if (!check_time(obj->data(), msg)) throw(basic_error() << "log with timestamp in second failed"); obj->reset(); obj->show_timestamp(millisecond); e.log(1, 0, msg, sizeof(msg)); if (!check_time(obj->data(), msg)) throw(basic_error() << "log with timestamp in millisecond " "failed"); obj->reset(); obj->show_timestamp(microsecond); e.log(1, 0, msg, sizeof(msg)); if (!check_time(obj->data(), msg)) throw(basic_error() << "log with timestamp in microsecond " "failed"); obj->reset(); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/engine_add.cc000066400000000000000000000032431407153644500214100ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check add backend with null pointer. * * @return True on success, otherwise false. */ static bool null_pointer() { try { engine& e(engine::instance()); e.add(NULL, 0, 0); } catch (std::exception const& e) { (void)e; return (true); } return (false); } /** * Check add backend on to the logging engine. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); if (!null_pointer()) throw(basic_error() << "try to add null pointer"); std::unique_ptr obj(new backend_test); unsigned long id(e.add(obj.get(), 0, 0)); if (!id) throw(basic_error() << "add backend failed, invalid id"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/engine_is_log.cc000066400000000000000000000036421407153644500221370ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check is log. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); unsigned int limits(sizeof(unsigned int) * CHAR_BIT); for (unsigned int i(0); i < 3; ++i) { for (unsigned int j(0); j < limits; ++j) { unsigned long id(e.add(obj.get(), 1 << j, i)); for (unsigned int k(0); k < limits; ++k) { if (e.is_log(1 << k, i) != (k == j)) throw(basic_error() << "is log failed with types(" << j << ") verbose(" << i << ")"); for (unsigned int k(0); k < 3; ++k) { if (e.is_log(1 << j, k) != (i >= k)) throw(basic_error() << "is log failed with types(" << j << ") verbose(" << i << ")"); } } if (!e.remove(id)) throw(basic_error() << "remove id failed"); } } retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/engine_log.cc000066400000000000000000000032571407153644500214460ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check if log message works. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.log(1, 0, NULL, 0); unsigned int limits(sizeof(unsigned int) * CHAR_BIT); for (unsigned int i(0); i < 3; ++i) { for (unsigned int j(0); j < limits; ++j) { unsigned long id(e.add(obj.get(), 1 << j, i)); for (unsigned int k(0); k < limits; ++k) e.log(1 << k, i, "", 0); if (!e.remove(id)) throw(basic_error() << "remove id failed"); } } if (obj->get_nb_call() != 3 * limits) throw(basic_error() << "invalid number of call log function"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/engine_remove_by_backend.cc000066400000000000000000000037121407153644500243170ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check remove by backend the null pointer argument. * * @return True on success, otherwise false. */ static bool null_pointer() { try { engine& e(engine::instance()); e.remove(static_cast(NULL)); } catch (std::exception const& e) { (void)e; return (true); } return (false); } /** * Check remove backend on to the logging engine. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); if (!null_pointer()) throw(basic_error() << "try to remove with null pointer"); std::unique_ptr obj(new backend_test); e.add(obj.get(), 1, 0); if (e.remove(obj.get()) != 1) throw(basic_error() << "remove one backend failed"); static unsigned int const nb_backend(1000); for (unsigned int i(1); i < nb_backend; ++i) e.add(obj.get(), i, 0); if (e.remove(obj.get()) != nb_backend - 1) throw(basic_error() << "remove " << nb_backend << " backend failed"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/engine_remove_by_id.cc000066400000000000000000000027611407153644500233270ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check add backend on to the logging engine. * * @return 0 on success. */ int main() { // Return value. int retval; try { engine& e(engine::instance()); if (e.remove(1) || e.remove(42)) throw(basic_error() << "try to remove invalid id"); std::unique_ptr obj(new backend_test); unsigned long id(e.add(obj.get(), 1, 0)); if (!e.remove(id)) throw(basic_error() << "remove id failed"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } catch (...) { std::cerr << "unknown error" << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/engine_with_thread.cc000066400000000000000000000037601407153644500231660ustar00rootroot00000000000000/* ** 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 #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check add backend on to the logging engine. * * @return 0 on success. */ int main() { static uint32_t const nb_writter(10); int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 1, 0); std::vector threads; for (uint32_t i = 0; i < nb_writter; ++i) threads.push_back(std::thread([]() { engine& e(engine::instance()); for (uint32_t i = 0; i < nb_writter; ++i) { std::ostringstream oss; oss << std::this_thread::get_id() << ":" << i; e.log(1, 0, oss.str().c_str(), oss.str().size()); } })); for (auto& t : threads) t.join(); for (uint32_t i(0); i < nb_writter; ++i) { for (uint32_t j(0); j < nb_writter; ++j) { std::ostringstream oss; oss << &threads[i] << ":" << j << "\n"; if (!obj->data().find(oss.str())) throw basic_error() << "pattern not found"; } } retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/file_log.cc000066400000000000000000000037471407153644500211240ustar00rootroot00000000000000/* ** 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 #include #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_stream.hh" #include "com/centreon/logging/file.hh" using namespace com::centreon::logging; static bool check_log_message(std::string const& path, std::string const& msg) { std::ifstream stream(path.c_str()); char buffer[1024]; stream.get(buffer, sizeof(buffer)); return (buffer == msg); } /** * Check file constructor. * * @return 0 on success. */ int main() { static char msg[] = "Centreon Clib test"; int retval; try { char* tmp(com::centreon::io::file_stream::temp_path()); { file f(tmp, false, false, none, false); f.log(1, 0, msg, sizeof(msg)); } if (!check_log_message(tmp, msg)) throw(basic_error() << "log message failed"); { FILE* out(NULL); if (!(out = fopen(tmp, "w"))) throw(basic_error() << "failed to open file \"" << tmp << "\":" << strerror(errno)); file f(out, false, false, none, false); f.log(1, 0, msg, sizeof(msg)); } if (!check_log_message(tmp, msg)) throw(basic_error() << "log message failed"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return (retval); } centreon-clib-21.04.2/test/logging/file_log_multiline.cc000066400000000000000000000040341407153644500231740ustar00rootroot00000000000000/* ** 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 #include #include #include #include #include #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/io/file_stream.hh" #include "com/centreon/logging/file.hh" using namespace com::centreon; using namespace com::centreon::logging; static bool check_log_message(std::string const& path, std::string const& msg) { std::ifstream stream(path.c_str()); char buffer[32 * 1024]; memset(buffer, 0, sizeof(buffer)); stream.read(buffer, sizeof(buffer)); return buffer == msg; } /** * Check if log message works. * * @return 0 on success. */ int main() { static unsigned int const nb_line(1024); int retval; try { char* tmpfile(com::centreon::io::file_stream::temp_path()); std::ostringstream tmp; std::ostringstream tmpref; for (unsigned int i(0); i < nb_line; ++i) { tmp << i << "\n"; tmpref << "[" << std::this_thread::get_id() << "] " << i << "\n"; } std::string msg(tmp.str()); std::string ref(tmpref.str()); { file f(tmpfile, false, false, none, true); f.log(1, 0, msg.c_str(), msg.size()); } if (!check_log_message(tmpfile, ref)) throw(basic_error() << "log message failed"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_constructor.cc000066400000000000000000000030301407153644500242760ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check add backend on to the logging engine. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); temp_logger(0, 0) << "Centreon Clib test"; if (obj->get_nb_call() != 0) throw(basic_error() << "invalid number of call log"); temp_logger(1, 0) << "Centreon Clib test"; if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_copy.cc000066400000000000000000000027171407153644500226760ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check add backend on to the logging engine. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); temp_logger tmp(1, 0); tmp << "Centreon Clib test"; temp_logger(tmp) << " copy"; if (obj->data().find("copy") == std::string::npos) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_char.cc000066400000000000000000000025571407153644500250530ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); temp_logger(1, 2) << 'c'; if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_double.cc000066400000000000000000000025711407153644500254040ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); temp_logger(1, 2) << double(42.42); if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_int.cc000066400000000000000000000025631407153644500247250ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); temp_logger(1, 2) << int(42); if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_long.cc000066400000000000000000000025571407153644500250750ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); temp_logger(1, 2) << 42L; if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_long_long.cc000066400000000000000000000025601407153644500261060ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); temp_logger(1, 2) << 42LL; if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_pvoid.cc000066400000000000000000000025651407153644500252560ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); temp_logger(1, 2) << obj.get(); if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_std_string.cc000066400000000000000000000026151407153644500263110ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); temp_logger(1, 2) << std::string("Centreon Clib test"); if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_string.cc000066400000000000000000000026001407153644500254310ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); temp_logger(1, 2) << "Centreon Clib test"; if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_uint.cc000066400000000000000000000026071407153644500251110ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); unsigned int ui(42); temp_logger(1, 2) << ui; if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_ulong.cc000066400000000000000000000026101407153644500252500ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); unsigned long ul(42); temp_logger(1, 2) << ul; if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_do_nothing_ulong_long.cc000066400000000000000000000026171407153644500262760ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 2, 0); unsigned long long ull(42); temp_logger(1, 2) << ull; if (obj->get_nb_call()) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_char.cc000066400000000000000000000025641407153644500235020ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); temp_logger(1, 0) << 'c'; if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_double.cc000066400000000000000000000025761407153644500240420ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); temp_logger(1, 0) << double(42.42); if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_int.cc000066400000000000000000000025701407153644500233540ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); temp_logger(1, 0) << int(42); if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_long.cc000066400000000000000000000025641407153644500235240ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); temp_logger(1, 0) << 42L; if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_long_long.cc000066400000000000000000000025651407153644500245440ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); temp_logger(1, 0) << 42LL; if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_pvoid.cc000066400000000000000000000025721407153644500237050ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); temp_logger(1, 0) << obj.get(); if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_std_string.cc000066400000000000000000000026221407153644500247400ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); temp_logger(1, 0) << std::string("Centreon Clib test"); if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_string.cc000066400000000000000000000026051407153644500240670ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); temp_logger(1, 0) << "Centreon Clib test"; if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_uint.cc000066400000000000000000000026141407153644500235400ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); unsigned int ui(42); temp_logger(1, 0) << ui; if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_ulong.cc000066400000000000000000000026151407153644500237060ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); unsigned long ul(42); temp_logger(1, 0) << ul; if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/logging/temp_logger_log_ulong_long.cc000066400000000000000000000026241407153644500247250ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/engine.hh" #include "com/centreon/logging/temp_logger.hh" #include "./backend_test.hh" using namespace com::centreon::logging; /** * Check temp logger with nothing to do. * * @return 0 on success. */ int main() { int retval; try { engine& e(engine::instance()); std::unique_ptr obj(new backend_test); e.add(obj.get(), 3, 0); unsigned long long ull(42); temp_logger(1, 0) << ull; if (obj->get_nb_call() != 1) throw(basic_error() << "invalid number of call log"); retval = 0; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; retval = 1; } return retval; } centreon-clib-21.04.2/test/misc/000077500000000000000000000000001407153644500163275ustar00rootroot00000000000000centreon-clib-21.04.2/test/misc/CMakeLists.txt000066400000000000000000000226031407153644500210720ustar00rootroot00000000000000## ## 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 ## # Set directories. set(TEST_DIR "${TEST_DIR}/misc") # argument_constructor set(TEST_NAME "argument_constructor") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # argument_copy set(TEST_NAME "argument_copy") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # argument_equal set(TEST_NAME "argument_equal") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # argument_not_equal set(TEST_NAME "argument_not_equal") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # argument_set_description set(TEST_NAME "argument_set_description") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # argument_set_is_set set(TEST_NAME "argument_set_is_set") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # argument_set_has_value set(TEST_NAME "argument_set_has_value") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # argument_set_long_name set(TEST_NAME "argument_set_long_name") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # argument_set_name set(TEST_NAME "argument_set_name") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # argument_set_value set(TEST_NAME "argument_set_value") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # command_line_constructor set(TEST_NAME "command_line_constructor") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # command_line_copy set(TEST_NAME "command_line_copy") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # command_line_equal set(TEST_NAME "command_line_equal") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # command_line_get_argc set(TEST_NAME "command_line_get_argc") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # command_line_get_argv set(TEST_NAME "command_line_get_argv") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # command_line_not_equal set(TEST_NAME "command_line_not_equal") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # command_line_parse set(TEST_NAME "command_line_parse") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # get_options_constructor set(TEST_NAME "get_options_constructor") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # get_options_constructor_invalid set(TEST_NAME "get_options_constructor_invalid") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # get_options_copy set(TEST_NAME "get_options_copy") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # get_options_get_argument_by_long_name set(TEST_NAME "get_options_get_argument_by_long_name") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # get_options_get_argument_by_name set(TEST_NAME "get_options_get_argument_by_name") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_append set(TEST_NAME "stringifier_append") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_constructor set(TEST_NAME "stringifier_constructor") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_copy set(TEST_NAME "stringifier_copy") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_bool set(TEST_NAME "stringifier_insert_bool") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_char set(TEST_NAME "stringifier_insert_char") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_double set(TEST_NAME "stringifier_insert_double") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_long set(TEST_NAME "stringifier_insert_long") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_pchar set(TEST_NAME "stringifier_insert_pchar") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_std_string set(TEST_NAME "stringifier_insert_std_string") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_pvoid set(TEST_NAME "stringifier_insert_pvoid") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_ulong set(TEST_NAME "stringifier_insert_ulong") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_int set(TEST_NAME "stringifier_insert_int") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_longlong set(TEST_NAME "stringifier_insert_longlong") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_many_data set(TEST_NAME "stringifier_insert_many_data") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_uint set(TEST_NAME "stringifier_insert_uint") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_insert_ulonglong set(TEST_NAME "stringifier_insert_ulonglong") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") # stringifier_reset set(TEST_NAME "stringifier_reset") add_executable("${TEST_NAME}" "${TEST_DIR}/${TEST_NAME}.cc") target_link_libraries("${TEST_NAME}" "${DEFAULT_LINK_NAME}") add_test("${TEST_NAME}" "${TEST_NAME}") centreon-clib-21.04.2/test/misc/argument_constructor.cc000066400000000000000000000034551407153644500231340ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Check the argument constructor. * * @return 0 on success. */ int main() { try { std::string long_name("help"); char name('h'); std::string description("this help"); bool has_value(true); bool is_set(true); std::string value("help:\n --help, -h this help"); argument arg(long_name, name, description, has_value, is_set, value); if (arg.get_long_name() != long_name) throw(basic_error() << "invalid long name"); if (arg.get_name() != name) throw(basic_error() << "invalid name"); if (arg.get_description() != description) throw(basic_error() << "invalid description"); if (arg.get_has_value() != has_value) throw(basic_error() << "invalid has value"); if (arg.get_is_set() != is_set) throw(basic_error() << "invalid is set"); if (arg.get_value() != value) throw(basic_error() << "invalid value"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/argument_copy.cc000066400000000000000000000037111407153644500215140ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Compare two argument. * * @param[in] a1 The first argument to check. * @param[in] a2 The second argument to check. */ static void check_argument(argument const& a1, argument const& a2) { if (a1.get_long_name() != a2.get_long_name()) throw(basic_error() << "invalid long name"); if (a1.get_description() != a2.get_description()) throw(basic_error() << "invalid description"); if (a1.get_name() != a2.get_name()) throw(basic_error() << "invalid name"); if (a1.get_has_value() != a2.get_has_value()) throw(basic_error() << "invalid has value"); if (a1.get_is_set() != a2.get_is_set()) throw(basic_error() << "invalid is set"); if (a1.get_value() != a2.get_value()) throw(basic_error() << "invalid value"); } /** * Check the argument copy. * * @return 0 on success. */ int main() { try { argument ref( "help", 'c', "this help", true, true, "help:\n --help, -h this help"); argument arg1(ref); check_argument(ref, arg1); argument arg2 = ref; check_argument(ref, arg1); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/argument_equal.cc000066400000000000000000000024771407153644500216610ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Check the argument equal operator. * * @return 0 on success. */ int main() { try { argument ref( "help", 'c', "this help", true, true, "help:\n --help, -h this help"); argument arg1(ref); if (!(ref == arg1)) throw(basic_error() << "copy constructor failed"); argument arg2 = ref; if (!(ref == arg2)) throw(basic_error() << "copy operator failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/argument_not_equal.cc000066400000000000000000000024751407153644500225370ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Check the argument not equal operator. * * @return 0 on success. */ int main() { try { argument ref( "help", 'c', "this help", true, true, "help:\n --help, -h this help"); argument arg1(ref); if (ref != arg1) throw(basic_error() << "copy constructor failed"); argument arg2 = ref; if (ref != arg2) throw(basic_error() << "copy operator failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/argument_set_description.cc000066400000000000000000000023101407153644500237320ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Check the set description. * * @return 0 on success. */ int main() { try { std::string description("this help"); argument arg; arg.set_description(description); if (arg.get_description() != description) throw(basic_error() << "invalid description"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/argument_set_has_value.cc000066400000000000000000000022541407153644500233650ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Check the set has_value. * * @return 0 on success. */ int main() { try { bool has_value(true); argument arg; arg.set_has_value(has_value); if (arg.get_has_value() != has_value) throw(basic_error() << "invalid has value"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/argument_set_is_set.cc000066400000000000000000000022271407153644500227040ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Check the set is set. * * @return 0 on success. */ int main() { try { bool is_set(true); argument arg; arg.set_is_set(is_set); if (arg.get_is_set() != is_set) throw(basic_error() << "invalid is set"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/argument_set_long_name.cc000066400000000000000000000022651407153644500233570ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Check the set long name. * * @return 0 on success. */ int main() { try { std::string long_name("help"); argument arg; arg.set_long_name(long_name); if (arg.get_long_name() != long_name) throw(basic_error() << "invalid long name"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/argument_set_name.cc000066400000000000000000000022101407153644500223260ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Check the set name. * * @return 0 on success. */ int main() { try { char name('h'); argument arg; arg.set_name(name); if (arg.get_name() != name) throw(basic_error() << "invalid name"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/argument_set_value.cc000066400000000000000000000022631407153644500225320ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/argument.hh" using namespace com::centreon::misc; /** * Check the set value. * * @return 0 on success. */ int main() { try { std::string value("help:\n --help, -h this help."); argument arg; arg.set_value(value); if (arg.get_value() != value) throw(basic_error() << "invalid value"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/command_line_constructor.cc000066400000000000000000000022541407153644500237330ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/command_line.hh" using namespace com::centreon::misc; /** * Check the command line constructor. * * @return 0 on success. */ int main() { try { command_line cmd; if (cmd.get_argc()) throw(basic_error() << "invalid argc value"); if (cmd.get_argv()) throw(basic_error() << "invalid argv value"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/command_line_copy.cc000066400000000000000000000035671407153644500223300ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/command_line.hh" using namespace com::centreon::misc; /** * Compare command line. * * @param[in] cmd1 Command line. * @param[in] cmd2 Command line. * * @return True on success, otherwise false. */ static bool compare(command_line const& cmd1, command_line const& cmd2) { if (cmd1.get_argc() != cmd2.get_argc()) return (false); char** argv1(cmd1.get_argv()); char** argv2(cmd2.get_argv()); for (int i(0), end(cmd1.get_argc()); i < end; ++i) if (strcmp(argv1[i], argv2[i])) return (false); if (argv1[cmd1.get_argc()] != argv2[cmd2.get_argc()]) return (false); return (true); } /** * Check the command line not equal operator. * * @return 0 on success. */ int main() { try { std::string cmdline("1 2 3 4 5"); command_line ref(cmdline); command_line cmd1(ref); if (!compare(ref, cmd1)) throw(basic_error() << "copy constructor failed"); command_line cmd2 = ref; if (!compare(ref, cmd2)) throw(basic_error() << "copy operator failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/command_line_equal.cc000066400000000000000000000023071407153644500224540ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/command_line.hh" using namespace com::centreon::misc; /** * Check the command line not equal operator. * * @return 0 on success. */ int main() { try { std::string cmdline(" 1 2 3 4 5 6 7 8 9 0 "); command_line cmd1(cmdline); command_line cmd2(cmdline); if (!(cmd1 == cmd2)) throw(basic_error() << "operator equal failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/command_line_get_argc.cc000066400000000000000000000024151407153644500231200ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/command_line.hh" using namespace com::centreon::misc; /** * Check the command line not equal operator. * * @return 0 on success. */ int main() { try { std::string cmdline(" 1 2 3 4 5 6 7 8 9 0 "); command_line cmd; if (cmd.get_argc()) throw(basic_error() << "invalid argc value: not null"); cmd.parse(cmdline); if (cmd.get_argc() != 10) throw(basic_error() << "invalid argc value"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/command_line_get_argv.cc000066400000000000000000000025311407153644500231420ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/command_line.hh" using namespace com::centreon::misc; /** * Check the command line not equal operator. * * @return 0 on success. */ int main() { try { std::string cmdline("123456"); command_line cmd; if (cmd.get_argv()) throw(basic_error() << "invalid argv value: not null"); cmd.parse(cmdline); if (!cmd.get_argv()) throw(basic_error() << "invalid argv value: null"); if (cmd.get_argv()[0] != cmdline) throw(basic_error() << "invalid argv value"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/command_line_not_equal.cc000066400000000000000000000023041407153644500233310ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/command_line.hh" using namespace com::centreon::misc; /** * Check the command line equal operator. * * @return 0 on success. */ int main() { try { std::string cmdline(" 1 2 3 4 5 6 7 8 9 0 "); command_line cmd1(cmdline); command_line cmd2(cmdline); if (cmd1 != cmd2) throw(basic_error() << "operator not equal failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/command_line_parse.cc000066400000000000000000000133761407153644500224670ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/command_line.hh" using namespace com::centreon::misc; /** * Check command line parsing. * * @param[in] cmdline The command line to parse. * @param[in] res List of result to compare. * * @return True on success, otherwise false. */ static bool check(std::string const& cmdline, std::vector const& res) { try { command_line cmd; cmd.parse(cmdline); if (cmd.get_argc() != static_cast(res.size())) return (false); char** argv(cmd.get_argv()); for (int i(0), end(cmd.get_argc()); i < end; ++i) if (argv[i] != res[i]) return (false); if (argv[cmd.get_argc()]) return (false); } catch (std::exception const& e) { (void)e; return (false); } return (true); } /** * Check with invalid command line. * * @return True on success, otherwise false. */ static bool check_invalid_cmdline() { try { command_line cmd; cmd.parse("'12 12"); } catch (std::exception const& e) { (void)e; return (true); } return (false); } /** * Check the set description. * * @return 0 on success. */ int main() { int ret(0); try { if (!check_invalid_cmdline()) throw( basic_error() << "parsing error: try to parse invalid command line"); { std::string cmdline("\\ echo -n \"test\""); std::vector res; res.push_back(" echo"); res.push_back("-n"); res.push_back("test"); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline("test \"|\" \"\" \"|\""); std::vector res; res.push_back("test"); res.push_back("|"); res.push_back(""); res.push_back("|"); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline(""); std::vector res; if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline(" \t\t\t\t\t "); std::vector res; if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline("aa\tbbb c\tdd ee"); std::vector res; res.push_back("aa"); res.push_back("bbb"); res.push_back("c"); res.push_back("dd"); res.push_back("ee"); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline(" aa bbb \t c dd ee \t"); std::vector res; res.push_back("aa"); res.push_back("bbb"); res.push_back("c"); res.push_back("dd"); res.push_back("ee"); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline(" 'aa bbb cc' dddd "); std::vector res; res.push_back("aa bbb cc"); res.push_back("dddd"); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline(" \" aa bbb cc \" dddd"); std::vector res; res.push_back(" aa bbb cc "); res.push_back("dddd"); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline(" ' \" aa bbb bbb cc ' "); std::vector res; res.push_back(" \" aa bbb bbb cc "); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline(" \" '\\n aaa 42 ' \" 4242 "); std::vector res; res.push_back(" '\n aaa 42 ' "); res.push_back("4242"); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline("\\\\\" 1 2 \""); std::vector res; res.push_back("\\ 1 2 "); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline("\\\\\\\" 1 2 \\\""); std::vector res; res.push_back("\\\""); res.push_back("1"); res.push_back("2"); res.push_back("\""); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline(" '12\\t ''34 56' \t \" 12 12 12 \" '99 9 9'"); std::vector res; res.push_back("12\t 34 56"); res.push_back(" 12 12 12 "); res.push_back("99 9 9"); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } { std::string cmdline("\\.\\/\\-\\*\\1"); std::vector res; res.push_back("./-*1"); if (!check(cmdline, res)) throw(basic_error() << "parsing error: " << cmdline); } } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; ret = 1; } return (ret); } centreon-clib-21.04.2/test/misc/get_options_constructor.cc000066400000000000000000000037301407153644500236400ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/get_options.hh" using namespace com::centreon::misc; /** * @class my_options * @brief litle implementation of get_options to test it. */ class my_options : public get_options { public: my_options(std::vector const& args) : get_options() { _arguments['a'] = argument("arg", 'a', "", true); _arguments['c'] = argument("cold", 'c', "", true); _arguments['t'] = argument("test", 't', "", true); _arguments['h'] = argument("help", 'h'); _arguments['d'] = argument("default", 'd', "", true, true, "def"); _parse_arguments(args); } ~my_options() throw() {} }; /** * Check the get_options constructor. * * @return 0 on success. */ int main() { try { std::vector args; args.push_back("-c1"); args.push_back("--test=1"); args.push_back("-h"); args.push_back("--arg"); args.push_back("2"); args.push_back("param1"); args.push_back("param2"); args.push_back("param3"); my_options opt(args); if (opt.get_parameters().size() != 3 || opt.get_arguments().size() != 5) throw(basic_error() << "constructor failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/get_options_constructor_invalid.cc000066400000000000000000000052761407153644500253550ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/get_options.hh" using namespace com::centreon::misc; /** * @class my_options * @brief litle implementation of get_options to test it. */ class my_options : public get_options { public: my_options(std::vector const& args) : get_options() { _arguments['a'] = argument("arg", 'a', "", true); _arguments['t'] = argument("test", 't', "", true); _arguments['h'] = argument("help", 'h'); _arguments['d'] = argument("default", 'd', "", true, true, "def"); _parse_arguments(args); } ~my_options() throw() {} }; /** * Check the get options with unknown option. * * @return True on success, otherwise false. */ static bool check_unknown_option() { try { std::vector args; args.push_back("--test=1"); args.push_back("-h"); args.push_back("--arg"); args.push_back("2"); args.push_back("--failed=42"); args.push_back("param1"); args.push_back("param2"); args.push_back("param3"); my_options opt(args); } catch (std::exception const& e) { (void)e; return (true); } return (false); } /** * Check the get options without require argument. * * @return True on success, otherwise false. */ static bool check_require_argument() { try { std::vector args; args.push_back("-h"); args.push_back("--arg"); args.push_back("2"); args.push_back("--test"); my_options opt(args); } catch (std::exception const& e) { (void)e; return (true); } return (false); } /** * Check the get_options constructor. * * @return 0 on success. */ int main() { try { if (!check_unknown_option()) throw(basic_error() << "constructor failed with unknown option"); if (!check_require_argument()) throw(basic_error() << "constructor failed with " "require argument"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/get_options_copy.cc000066400000000000000000000036621407153644500222310ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/get_options.hh" using namespace com::centreon::misc; /** * @class my_options * @brief litle implementation of get_options to test it. */ class my_options : public get_options { public: my_options(std::vector const& args) : get_options() { _arguments['a'] = argument("arg", 'a', "", true); _arguments['t'] = argument("test", 't', "", true); _arguments['h'] = argument("help", 'h'); _arguments['d'] = argument("default", 'd', "", true, true, "def"); _parse_arguments(args); } my_options(my_options const& right) : get_options(right) {} ~my_options() throw() {} my_options& operator=(my_options const& right) { get_options::operator=(right); return (*this); } }; /** * Check the get_options copy. * * @return 0 on success. */ int main() { try { std::vector args; my_options ref(args); my_options opt1(ref); if (!(ref == opt1)) throw(basic_error() << "copy constructor failed"); my_options opt2 = ref; if (ref != opt2) throw(basic_error() << "copy operator failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/get_options_get_argument_by_long_name.cc000066400000000000000000000047551407153644500264550ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/get_options.hh" using namespace com::centreon::misc; /** * @class my_options * @brief litle implementation of get_options to test it. */ class my_options : public get_options { public: my_options(std::vector const& args) : get_options() { _arguments['a'] = argument("arg", 'a', "", true); _arguments['t'] = argument("test", 't', "", true); _arguments['h'] = argument("help", 'h'); _arguments['d'] = argument("default", 'd', "", true, true, "def"); _parse_arguments(args); } ~my_options() throw() {} }; /** * Check with invalid long name. * * @return True on success, otherwise false. */ static bool invalid_long_name() { try { std::vector args; my_options opt(args); opt.get_argument("unknown"); } catch (std::exception const& e) { (void)e; return (true); } return (false); } /** * Check with valide long name. * * @return True on success, otherwise false. */ static bool valid_long_name() { try { std::vector args; my_options opt(args); argument& a1(opt.get_argument("help")); argument const& a2(opt.get_argument("help")); (void)a1; (void)a2; } catch (std::exception const& e) { (void)e; return (false); } return (true); } /** * Check the get argument by long name. * * @return 0 on success. */ int main() { try { if (!invalid_long_name()) throw(basic_error() << "get argument with invalid " "long name failed"); if (!valid_long_name()) throw(basic_error() << "get argument with valid " "long name failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/get_options_get_argument_by_name.cc000066400000000000000000000046641407153644500254350ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/misc/get_options.hh" using namespace com::centreon::misc; /** * @class my_options * @brief litle implementation of get_options to test it. */ class my_options : public get_options { public: my_options(std::vector const& args) : get_options() { _arguments['a'] = argument("arg", 'a', "", true); _arguments['t'] = argument("test", 't', "", true); _arguments['h'] = argument("help", 'h'); _arguments['d'] = argument("default", 'd', "", true, true, "def"); _parse_arguments(args); } ~my_options() throw() {} }; /** * Check with invalid name. * * @return True on success, otherwise false. */ static bool invalid_name() { try { std::vector args; my_options opt(args); opt.get_argument('*'); } catch (std::exception const& e) { (void)e; return (true); } return (false); } /** * Check with valide name. * * @return True on success, otherwise false. */ static bool valid_name() { try { std::vector args; my_options opt(args); argument& a1(opt.get_argument('h')); argument const& a2(opt.get_argument('h')); (void)a1; (void)a2; } catch (std::exception const& e) { (void)e; return (false); } return (true); } /** * Check the get argument by name. * * @return 0 on success. */ int main() { try { if (!invalid_name()) throw(basic_error() << "get argument with invalid " "name failed"); if (!valid_name()) throw(basic_error() << "get argument with valid " "name failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/misc/stringifier_append.cc000066400000000000000000000024421407153644500225140ustar00rootroot00000000000000/* ** 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 #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier append data. * * @return 0 on success. */ int main() { { stringifier buffer; buffer.append(__FILE__, sizeof(__FILE__)); if (strcmp(buffer.data(), __FILE__)) return (1); } { stringifier buffer; buffer.append(__FILE__, sizeof(__FILE__) - 3); if (strncmp(buffer.data(), __FILE__, sizeof(__FILE__) - 3)) return (1); } { char ref[] = "**\0**"; stringifier buffer; buffer.append(ref, sizeof(ref)); if (memcmp(buffer.data(), ref, 3)) return (1); } return (0); } centreon-clib-21.04.2/test/misc/stringifier_constructor.cc000066400000000000000000000016051407153644500236320ustar00rootroot00000000000000/* ** 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 #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier constructor. * * @return 0 on success. */ int main() { stringifier buffer; return (strcmp(buffer.data(), "")); } centreon-clib-21.04.2/test/misc/stringifier_copy.cc000066400000000000000000000017121407153644500222160ustar00rootroot00000000000000/* ** 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 #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier copy. * * @return 0 on success. */ int main() { static char const message[] = "Centreon Clib"; stringifier buffer; buffer << message; return (strcmp(buffer.data(), message)); } centreon-clib-21.04.2/test/misc/stringifier_insert_bool.cc000066400000000000000000000016751407153644500235730ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert bool. * * @return 0 on success. */ int main() { stringifier buffer; buffer << false << true; return (strcmp(buffer.data(), "falsetrue")); } centreon-clib-21.04.2/test/misc/stringifier_insert_char.cc000066400000000000000000000020251407153644500235430ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert char. * * @return 0 on success. */ int main() { stringifier buffer; buffer << static_cast(CHAR_MIN); buffer << static_cast(CHAR_MAX); char ref[] = {CHAR_MIN, CHAR_MAX, 0}; return (strcmp(buffer.data(), ref)); } centreon-clib-21.04.2/test/misc/stringifier_insert_double.cc000066400000000000000000000027631407153644500241110ustar00rootroot00000000000000/* ** 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 #include #include #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check that double are properly written by stringifier. * * @param[in] d Double to write and test. * * @return true if check succeed. */ static bool check_double(double d) { stringifier buffer; buffer << d; char* ptr(NULL); double converted(strtod(buffer.data(), &ptr)); return (ptr && !*ptr && (fabs(d - converted) // Roughly 0.1% error margin. <= (fabs(d / 1000) + 2 * DBL_EPSILON))); } /** * Check the stringifier insert double. * * @return 0 on success. */ int main() { return (!check_double(DBL_MIN) || !check_double(DBL_MAX) || !check_double(0.0) || !check_double(1.1) || !check_double(-1.456657563)); } centreon-clib-21.04.2/test/misc/stringifier_insert_int.cc000066400000000000000000000021001407153644500234120ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert int. * * @return 0 on success. */ int main() { stringifier buffer; buffer << static_cast(INT_MIN); buffer << static_cast(INT_MAX); std::ostringstream oss; oss << INT_MIN << INT_MAX; return (strcmp(buffer.data(), oss.str().c_str())); } centreon-clib-21.04.2/test/misc/stringifier_insert_long.cc000066400000000000000000000021071407153644500235660ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert long. * * @return 0 on success. */ int main() { stringifier buffer; buffer << static_cast(LONG_MIN); buffer << static_cast(LONG_MAX); std::ostringstream oss; oss << LONG_MIN << LONG_MAX; return (strcmp(buffer.data(), oss.str().c_str())); } centreon-clib-21.04.2/test/misc/stringifier_insert_longlong.cc000066400000000000000000000021321407153644500244440ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert long long. * * @return 0 on success. */ int main() { stringifier buffer; buffer << static_cast(LLONG_MIN); buffer << static_cast(LLONG_MAX); std::ostringstream oss; oss << LLONG_MIN << LLONG_MAX; return (strcmp(buffer.data(), oss.str().c_str())); } centreon-clib-21.04.2/test/misc/stringifier_insert_many_data.cc000066400000000000000000000022141407153644500245630ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert string. * * @return 0 on success. */ int main() { static unsigned int const nb_msg(1024); static unsigned int const size_msg(512); stringifier buffer; std::string msg(size_msg, '*'); for (unsigned int i(0); i < nb_msg; ++i) buffer << msg.c_str(); std::string ref(nb_msg * size_msg, '*'); return (strcmp(buffer.data(), ref.c_str())); } centreon-clib-21.04.2/test/misc/stringifier_insert_pchar.cc000066400000000000000000000016431407153644500237300ustar00rootroot00000000000000/* ** 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 #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert string. * * @return 0 on success. */ int main() { stringifier buffer; buffer << __FILE__; return (strcmp(buffer.data(), __FILE__)); } centreon-clib-21.04.2/test/misc/stringifier_insert_pvoid.cc000066400000000000000000000017641407153644500237600ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert pointer address. * * @return 0 on success. */ int main() { stringifier buffer; buffer << &buffer; std::ostringstream oss; oss << &buffer; return (strcmp(buffer.data(), oss.str().c_str())); } centreon-clib-21.04.2/test/misc/stringifier_insert_std_string.cc000066400000000000000000000017511407153644500250130ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert std string. * * @return 0 on success. */ int main() { std::string str(__FILE__); stringifier buffer; buffer << str; return (strcmp(buffer.data(), str.c_str())); } centreon-clib-21.04.2/test/misc/stringifier_insert_uint.cc000066400000000000000000000021211407153644500236020ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert unsigned int. * * @return 0 on success. */ int main() { stringifier buffer; buffer << static_cast(0); buffer << static_cast(UINT_MAX); std::ostringstream oss; oss << 0 << UINT_MAX; return (strcmp(buffer.data(), oss.str().c_str())); } centreon-clib-21.04.2/test/misc/stringifier_insert_ulong.cc000066400000000000000000000021261407153644500237540ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert unsigned long. * * @return 0 on success. */ int main() { stringifier buffer; buffer << static_cast(0); buffer << static_cast(ULONG_MAX); std::ostringstream oss; oss << 0 << ULONG_MAX; return (strcmp(buffer.data(), oss.str().c_str())); } centreon-clib-21.04.2/test/misc/stringifier_insert_ulonglong.cc000066400000000000000000000021471407153644500246370ustar00rootroot00000000000000/* ** 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 #include #include #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert unsigned long long. * * @return 0 on success. */ int main() { stringifier buffer; buffer << static_cast(0); buffer << static_cast(ULLONG_MAX); std::ostringstream oss; oss << 0 << ULLONG_MAX; return (strcmp(buffer.data(), oss.str().c_str())); } centreon-clib-21.04.2/test/misc/stringifier_reset.cc000066400000000000000000000016541407153644500223730ustar00rootroot00000000000000/* ** 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 #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier constructor. * * @return 0 on success. */ int main() { stringifier buffer; buffer << &buffer; buffer.reset(); return (strcmp(buffer.data(), "")); } centreon-clib-21.04.2/test/process_env.cc000066400000000000000000000026621407153644500202370ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/clib.hh" #include "com/centreon/exceptions/basic.hh" #include "com/centreon/process.hh" using namespace com::centreon; /** * Check class process (environement). * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_SUCCESS); try { process p; char* env[] = {(char*)"key1=value1", (char*)"key2=value2", (char*)"key3=value3", NULL}; p.exec( "./bin_test_process_output check_env " "key1=value1 key2=value2 key3=value3", env); p.wait(); if (p.exit_code() != EXIT_SUCCESS) throw(basic_error() << "check environment failed"); } catch (std::exception const& e) { ret = EXIT_FAILURE; std::cerr << "error: " << e.what() << std::endl; } return ret; } centreon-clib-21.04.2/test/process_kill.cc000066400000000000000000000025561407153644500204040ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/clib.hh" #include "com/centreon/exceptions/basic.hh" #include "com/centreon/process.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check class process (kill). * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_SUCCESS); try { process p; p.exec("./bin_test_process_output check_sleep 1"); p.kill(); timestamp start(timestamp::now()); p.wait(); timestamp end(timestamp::now()); if ((end - start).to_seconds() != 0) throw(basic_error() << "kill failed"); } catch (std::exception const& e) { ret = EXIT_FAILURE; std::cerr << "error: " << e.what() << std::endl; } return ret; } centreon-clib-21.04.2/test/process_output.cc000066400000000000000000000044611407153644500210060ustar00rootroot00000000000000/* ** 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 #include #include #include #include "com/centreon/clib.hh" #include "com/centreon/exceptions/basic.hh" #include "com/centreon/process.hh" using namespace com::centreon; /** * Check class process (read stdout/stderr). * * @return EXIT_SUCCESS on success. */ int main(int argc, char** argv) { int ret(EXIT_SUCCESS); try { if (argc != 2 || (strcmp(argv[1], "err") && strcmp(argv[1], "out"))) { std::cerr << "usage: " << argv[0] << " err|out" << std::endl; return (EXIT_FAILURE); } std::string cmd("./bin_test_process_output check_output "); cmd += argv[1]; process p; p.exec(cmd); char buffer_write[16 * 1024]; std::string buffer_read; for (unsigned int i(0); i < sizeof(buffer_write); ++i) buffer_write[i] = static_cast(i); unsigned int total_read(0); unsigned int total_write(0); do { if (total_write < sizeof(buffer_write)) total_write += p.write(buffer_write, sizeof(buffer_write) - total_write); if (!strcmp(argv[1], "out")) p.read(buffer_read); else p.read_err(buffer_read); total_read += buffer_read.size(); } while (total_read < sizeof(buffer_write)); p.update_ending_process(0); p.wait(); if (p.exit_code() != EXIT_SUCCESS) throw basic_error() << "invalid return"; if (total_write != sizeof(buffer_write)) throw basic_error() << "invalid data write"; if (total_write != total_read) throw basic_error() << "invalid data read"; } catch (std::exception const& e) { ret = EXIT_FAILURE; std::cerr << "error: " << e.what() << std::endl; } return ret; } centreon-clib-21.04.2/test/process_return.cc000066400000000000000000000023521407153644500207620ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/clib.hh" #include "com/centreon/exceptions/basic.hh" #include "com/centreon/process.hh" using namespace com::centreon; /** * Check class process (return). * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_SUCCESS); try { process p; p.exec("./bin_test_process_output check_return 42"); p.wait(); if (p.exit_code() != 42) throw(basic_error() << "invalid return"); } catch (std::exception const& e) { ret = EXIT_FAILURE; std::cerr << "error: " << e.what() << std::endl; } return ret; } centreon-clib-21.04.2/test/process_terminate.cc000066400000000000000000000025751407153644500214420ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/clib.hh" #include "com/centreon/exceptions/basic.hh" #include "com/centreon/process.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check class process (terminate). * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_SUCCESS); try { process p; p.exec("./bin_test_process_output check_sleep 1"); p.terminate(); timestamp start(timestamp::now()); p.wait(); timestamp end(timestamp::now()); if ((end - start).to_seconds() != 0) throw(basic_error() << "terminate failed"); } catch (std::exception const& e) { ret = EXIT_FAILURE; std::cerr << "error: " << e.what() << std::endl; } return ret; } centreon-clib-21.04.2/test/process_timeout.cc000066400000000000000000000025201407153644500211260ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/clib.hh" #include "com/centreon/exceptions/basic.hh" #include "com/centreon/process.hh" using namespace com::centreon; /** * Check class process (wait timeout). * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_SUCCESS); try { process p; p.exec("./bin_test_process_output check_sleep 5", NULL, 1); p.wait(); timestamp exectime(p.end_time() - p.start_time()); if (exectime.to_seconds() > 1) throw(basic_error() << "timeout failed: " << exectime.to_useconds()); } catch (std::exception const& e) { ret = EXIT_FAILURE; std::cerr << "error: " << e.what() << std::endl; } return ret; } centreon-clib-21.04.2/test/process_wait_timeout.cc000066400000000000000000000026371407153644500221630ustar00rootroot00000000000000/* ** 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 #include #include "com/centreon/clib.hh" #include "com/centreon/exceptions/basic.hh" #include "com/centreon/process.hh" using namespace com::centreon; /** * Check class process (wait timeout). * * @return EXIT_SUCCESS on success. */ int main() { int ret(EXIT_SUCCESS); try { process p; p.exec("./bin_test_process_output check_sleep 1"); if (p.wait(500)) throw basic_error() << "wait timeout failed: " "waiting more than necessary"; if (!p.wait(1500)) throw basic_error() << "wait timeout failed: " "waiting less than necessary"; } catch (std::exception const& e) { ret = EXIT_FAILURE; std::cerr << "error: " << e.what() << std::endl; } return ret; } centreon-clib-21.04.2/test/shared_testing_library.cc000066400000000000000000000016251407153644500224360ustar00rootroot00000000000000/* ** 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 */ int export_lib_version = 42; char const* export_lib_name = "shared_testing_library"; /** * Addition function. * * @param[in] i1 first integer. * @param[in] i2 second integer. * * @return i1 + i2. */ extern "C" int add(int i1, int i2) { return (i1 + i2); } centreon-clib-21.04.2/test/task_manager_add.cc000066400000000000000000000027301407153644500211510ustar00rootroot00000000000000/* ** Copyright 2011-2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; /** * @class task_test * @brief litle implementation of task to test task manager. */ class task_test : public task { public: task_test() : task() {} ~task_test() noexcept {} void run() {} }; /** * Check the task manager add. * * @return 0 on success. */ int main() { try { task_manager tm; task_test* t1 = new task_test; tm.add(t1, timestamp::now(), true, true); if (!tm.next_execution_time().to_useconds()) throw basic_error() << "add failed"; task_test* t2 = new task_test; tm.add(t2, timestamp::now(), false, false); delete t2; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return 1; } return 0; } centreon-clib-21.04.2/test/task_manager_add_recurring.cc000066400000000000000000000027501407153644500232330ustar00rootroot00000000000000/* ** Copyright 2011-2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; /** * @class task_test * @brief litle implementation of task to test task manager. */ class task_test : public task { public: task_test() : task() {} ~task_test() noexcept {} void run() {} }; /** * Check the task manager add recurring. * * @return 0 on success. */ int main() { try { task_manager tm; task_test* t1(new task_test); tm.add(t1, timestamp::now(), 10, true, true); if (!tm.next_execution_time().to_useconds()) throw basic_error() << "add failed"; task_test* t2(new task_test); tm.add(t2, timestamp::now(), 10, false, false); delete t2; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return 1; } return 0; } centreon-clib-21.04.2/test/task_manager_execute.cc000066400000000000000000000041111407153644500220560ustar00rootroot00000000000000/* ** Copyright 2011-2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; /** * @class task_test * @brief litle implementation of task to test task manager. */ class task_test : public task { public: task_test() : task() {} ~task_test() noexcept {} void run() {} }; /** * Check the task manager execute. * * @return 0 on success. */ int main() { try { task_manager tm; if (tm.execute(timestamp::now())) throw basic_error() << "execute no task failed"; task_test* t1(new task_test); tm.add(t1, timestamp::now(), true, true); if (!tm.next_execution_time().to_useconds()) throw basic_error() << "add failed"; if (tm.execute(timestamp::now()) != 1) throw basic_error() << "execute one task failed"; task_test* t2(new task_test); tm.add(t2, timestamp(), false, false); tm.add(t2, timestamp(), false, false); tm.add(t2, timestamp(), false, false); tm.add(t2, timestamp(), false, false); if (tm.execute(timestamp::now()) != 4) throw basic_error() << "execute four task failed"; timestamp future(timestamp::now()); future.add_seconds(42); tm.add(t2, future, false, false); if (tm.execute(timestamp::now())) throw basic_error() << "execute future task failed"; delete t2; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return 1; } return 0; } centreon-clib-21.04.2/test/task_manager_execute_recurring.cc000066400000000000000000000047631407153644500241530ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; /** * @class task_test * @brief litle implementation of task to test task manager. */ class task_test : public task { public: task_test() : task() {} ~task_test() noexcept {} void run() {} }; /** * Check the task manager execute recurring. * * @return 0 on success. */ int main() { try { { task_manager tm; task_test* t1(new task_test); tm.add(t1, timestamp(), 1, true, true); if (tm.execute(timestamp::now()) != 1) throw basic_error() << "execute one task failed"; if (tm.execute(timestamp::now()) != 1) throw basic_error() << "execute one task failed"; if (tm.execute(timestamp::now()) != 1) throw basic_error() << "execute one task failed"; } { task_manager tm; task_test* t2(new task_test); tm.add(t2, timestamp(), 1, false, false); tm.add(t2, timestamp(), 1, false, false); tm.add(t2, timestamp(), 1, false, false); tm.add(t2, timestamp(), 1, false, false); if (tm.execute(timestamp::now()) != 4) throw basic_error() << "execute four task failed"; if (tm.execute(timestamp::now()) != 4) throw basic_error() << "execute four task failed"; if (tm.execute(timestamp::now()) != 4) throw basic_error() << "execute four task failed"; delete t2; } { task_manager tm; timestamp future(timestamp::now()); future.add_seconds(42); task_test* t2(new task_test); tm.add(t2, future, 0, false, false); if (tm.execute(timestamp::now())) throw(basic_error() << "execute future task failed"); delete t2; } } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return 1; } return 0; } centreon-clib-21.04.2/test/task_manager_next_execution_time.cc000066400000000000000000000031521407153644500244770ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; /** * @class task_test * @brief litle implementation of task to test task manager. */ class task_test : public task { public: task_test() : task() {} ~task_test() noexcept {} void run() {} }; /** * Check the task manager next execution time. * * @return 0 on success. */ int main() { try { task_manager tm; timestamp now(timestamp::now()); timestamp max_time(timestamp::max_time()); if (tm.next_execution_time() != max_time) throw basic_error() << "bad initialization of " \ "next_execution_time"; task_test* t1(new task_test); tm.add(t1, now, true, true); if (tm.next_execution_time() != now) throw basic_error() << "next_execution_time failed"; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return 1; } return 0; } centreon-clib-21.04.2/test/task_manager_remove_by_id.cc000066400000000000000000000035521407153644500230670ustar00rootroot00000000000000/* ** Copyright 2011-2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; /** * @class task_test * @brief litle implementation of task to test task manager. */ class task_test : public task { public: task_test() : task() {} ~task_test() noexcept {} void run() {} }; /** * Check the task manager remove by id. * * @return 0 on success. */ int main() { try { task_manager tm; task_test* t1(new task_test); unsigned long id1(tm.add(t1, timestamp::now(), true, true)); if (tm.remove(42)) throw basic_error() << "try to remove invalid id"; if (!tm.remove(id1)) throw basic_error() << "remove one task failed"; task_test* t2(new task_test); unsigned long id2(tm.add(t2, timestamp::now(), false, false)); if (!tm.remove(id2)) throw basic_error() << "remove one other task failed"; delete t2; if (tm.remove(42)) throw basic_error() << "remove invalid id failed"; if (tm.next_execution_time() != timestamp::max_time()) throw basic_error() << "invalid next_execution_time"; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return 1; } return 0; } centreon-clib-21.04.2/test/task_manager_remove_by_task.cc000066400000000000000000000040101407153644500234230ustar00rootroot00000000000000/* ** Copyright 2011-2019 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include #include "com/centreon/exceptions/basic.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; /** * @class task_test * @brief litle implementation of task to test task manager. */ class task_test : public task { public: task_test() : task() {} ~task_test() noexcept {} void run() {} }; /** * Check the task manager remove by task. * * @return 0 on success. */ int main() { try { task_manager tm; task_test* t1(new task_test); tm.add(t1, timestamp::now(), true, true); task_test none; if (tm.remove(&none)) throw basic_error() << "remove invalid task"; if (tm.remove(t1) != 1) throw basic_error() << "remove one task failed"; 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); if (tm.remove(t2) != 4) throw basic_error() << "remove four task failed"; delete t2; if (tm.remove(reinterpret_cast(0x4242))) throw basic_error() << "remove invalid task failed"; if (tm.next_execution_time() != timestamp::max_time()) throw basic_error() << "invalid next_execution_time"; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return 1; } return 0; } centreon-clib-21.04.2/test/task_manager_remove_self.cc000066400000000000000000000031371407153644500227310ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/task_manager.hh" using namespace com::centreon; // Global task manager. task_manager tm; /** * @class task_test * @brief litle implementation of task to test task manager. */ class task_test : public task { public: task_test() : task() {} ~task_test() noexcept {} void run() { tm.remove(this); } }; /** * Check the task manager remove by task. * * @return 0 on success. */ int main() { try { task_test* t1(new task_test); tm.add(t1, timestamp::now(), true, true); tm.execute(); 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); tm.execute(); delete t2; } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return 1; } return 0; } centreon-clib-21.04.2/test/timestamp_add.cc000066400000000000000000000030301407153644500205120ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp add. * * @return 0 on success. */ int main() { try { timestamp t1(1, 42); timestamp t2(2, 24); timestamp t3(t1 + t2); if (t3.to_useconds() != 3000066) throw(basic_error() << "operator+ failed"); timestamp t4(-1, -24); timestamp t5(t2 + t4); if (t5.to_useconds() != 1000000) throw(basic_error() << "operator+ failed"); timestamp t6(1, 42); t6 += t2; if (t6.to_useconds() != 3000066) throw(basic_error() << "operator+= failed"); timestamp t7(2, 24); t7 += t4; if (t7.to_useconds() != 1000000) throw(basic_error() << "operator+= failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_add_mseconds.cc000066400000000000000000000024071407153644500224140ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp add milliseconds. * * @return 0 on success. */ int main() { try { timestamp t1(1, 42); t1.add_mseconds(2000); if (t1.to_mseconds() != 3000) throw(basic_error() << "add_mseconds failed"); timestamp t2(1, 42); t2.add_mseconds(-1000); if (t2.to_mseconds() != 0) throw(basic_error() << "add_mseconds failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_add_seconds.cc000066400000000000000000000023611407153644500222360ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp add seconds. * * @return 0 on success. */ int main() { try { timestamp t1(1, 42); t1.add_seconds(2); if (t1.to_seconds() != 3) throw(basic_error() << "add_second failed"); timestamp t2(1, 42); t2.add_seconds(-1); if (t2.to_seconds() != 0) throw(basic_error() << "add_second failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_add_useconds.cc000066400000000000000000000024171407153644500224250ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp add microseconds. * * @return 0 on success. */ int main() { try { timestamp t1(1, 42); t1.add_useconds(2000000); if (t1.to_useconds() != 3000042) throw(basic_error() << "add_usecond failed"); timestamp t2(1, 42); t2.add_useconds(-1000000); if (t2.to_useconds() != 42) throw(basic_error() << "add_usecond failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_clear.cc000066400000000000000000000021401407153644500210510ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp equal operator. * * @return 0 on success. */ int main() { try { timestamp t(42, 24); t.clear(); if (t != timestamp()) throw(basic_error() << "clear failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_constructor.cc000066400000000000000000000025331407153644500223560ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp constructor. * * @return 0 on success. */ int main() { try { timestamp t1; if (t1.to_mseconds() || t1.to_seconds() || t1.to_useconds()) throw(basic_error() << "default constructor failed"); timestamp t2(42); if (t2.to_seconds() != 42) throw(basic_error() << "constructor failed"); timestamp t3(42, 24); if (t3.to_useconds() != 42000024) throw(basic_error() << "constructor failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_copy.cc000066400000000000000000000023101407153644500207340ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp copy. * * @return 0 on success. */ int main() { try { timestamp t1(42, 24); timestamp t2(t1); if (!(t1 == t2)) throw(basic_error() << "copy constructor failed"); timestamp t3 = t1; if (!(t1 == t3)) throw(basic_error() << "copy operator failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_equal.cc000066400000000000000000000025031407153644500210750ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp equal operator. * * @return 0 on success. */ int main() { try { timestamp t1(42, 24); timestamp t2(42, 24); if (!(t1 == t2)) throw(basic_error() << "operator== failed"); timestamp t3(41, 1000024); if (!(t3 == t2)) throw(basic_error() << "operator== failed"); timestamp t4(43, -1000000 + 24); if (!(t4 == t2)) throw(basic_error() << "operator== failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_greater.cc000066400000000000000000000026141407153644500214220ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp greater operator. * * @return 0 on success. */ int main() { try { timestamp t1(2, 0); timestamp t2(1, 0); if (!(t1 > t2)) throw(basic_error() << "operator> failed"); timestamp t3(3, -1000); if (!(t3 > t2)) throw(basic_error() << "operator> failed"); timestamp t4(1, -1); if (!(t2 > t4)) throw(basic_error() << "operator> failed"); timestamp t5(-1, 0); if (!(t1 > t5)) throw(basic_error() << "operator> failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_greater_or_equal.cc000066400000000000000000000031451407153644500233110ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp greater or equal operator. * * @return 0 on success. */ int main() { try { timestamp t1(2, 0); timestamp t2(1, 0); if (!(t1 >= t2)) throw(basic_error() << "operator>= failed"); timestamp t3(3, -1000); if (!(t3 >= t2)) throw(basic_error() << "operator>= failed"); timestamp t4(1, -1); if (!(t2 >= t4)) throw(basic_error() << "operator>= failed"); timestamp t5(-1, 0); if (!(t1 >= t5)) throw(basic_error() << "operator>= failed"); timestamp t6(0, 1000000); if (!(t6 >= t2)) throw(basic_error() << "operator>= failed"); timestamp t7(1, 0); if (!(t7 >= t2)) throw(basic_error() << "operator>= failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_less.cc000066400000000000000000000025751407153644500207450ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp less operator. * * @return 0 on success. */ int main() { try { timestamp t1(2, 0); timestamp t2(1, 0); if (t1 < t2) throw(basic_error() << "operator< failed"); timestamp t3(3, -1000); if (t3 < t2) throw(basic_error() << "operator< failed"); timestamp t4(1, -1); if (t2 < t4) throw(basic_error() << "operator< failed"); timestamp t5(-1, 0); if (t1 < t5) throw(basic_error() << "operator< failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_less_or_equal.cc000066400000000000000000000031261407153644500226250ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp less or equal operator. * * @return 0 on success. */ int main() { try { timestamp t1(2, 0); timestamp t2(1, 0); if (t1 <= t2) throw(basic_error() << "operator<= failed"); timestamp t3(3, -1000); if (t3 <= t2) throw(basic_error() << "operator<= failed"); timestamp t4(1, -1); if (t2 <= t4) throw(basic_error() << "operator<= failed"); timestamp t5(-1, 0); if (t1 <= t5) throw(basic_error() << "operator<= failed"); timestamp t6(0, 1000000); if (!(t6 <= t2)) throw(basic_error() << "operator<= failed"); timestamp t7(1, 0); if (!(t7 <= t2)) throw(basic_error() << "operator<= failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_not_equal.cc000066400000000000000000000021611407153644500217550ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp not equal operator. * * @return 0 on success. */ int main() { try { timestamp t1(42, 24); timestamp t2(42, 42); if (!(t1 != t2)) throw(basic_error() << "operator!= failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_sub.cc000066400000000000000000000030451407153644500205610ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp substract operator. * * @return 0 on success. */ int main() { try { timestamp t1(1, 42); timestamp t2(2, 24); timestamp t3(t2 - t1); if (t3.to_useconds() != 999982) throw(basic_error() << "operator- failed"); timestamp t4(-1, -24); timestamp t5(t2 - t4); if (t5.to_useconds() != 3000048) throw(basic_error() << "operator- failed"); timestamp t6(2, 24); t6 -= t1; if (t6.to_useconds() != 999982) throw(basic_error() << "operator-= failed"); timestamp t7(2, 24); t7 -= t4; if (t7.to_useconds() != 3000048) throw(basic_error() << "operator-= failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_sub_mseconds.cc000066400000000000000000000024161407153644500224550ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp substract milliseconds. * * @return 0 on success. */ int main() { try { timestamp t1(2, 42); t1.sub_mseconds(1000); if (t1.to_mseconds() != 1000) throw(basic_error() << "sub_msecond failed"); timestamp t2(1, 42); t2.sub_mseconds(-1000); if (t2.to_mseconds() != 2000) throw(basic_error() << "sub_msecond failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_sub_seconds.cc000066400000000000000000000023671407153644500223050ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp substract seconds. * * @return 0 on success. */ int main() { try { timestamp t1(2, 42); t1.sub_seconds(1); if (t1.to_seconds() != 1) throw(basic_error() << "sub_second failed"); timestamp t2(1, 42); t2.sub_seconds(-1); if (t2.to_seconds() != 2) throw(basic_error() << "sub_second failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_sub_useconds.cc000066400000000000000000000024321407153644500224630ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp substract microseconds. * * @return 0 on success. */ int main() { try { timestamp t1(2, 42); t1.sub_useconds(1000000); if (t1.to_useconds() != 1000042) throw(basic_error() << "sub_usecond failed"); timestamp t2(1, 42); t2.sub_useconds(-1000000); if (t2.to_useconds() != 2000042) throw(basic_error() << "sub_usecond failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_to_mseconds.cc000066400000000000000000000030361407153644500223050ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp to milliseconds. * * @return 0 on success. */ int main() { try { timestamp t1(1, 42); if (t1.to_mseconds() != 1000) throw(basic_error() << "to_msecond failed"); timestamp t2(-1, 0); if (t2.to_mseconds() != -1000) throw(basic_error() << "to_msecond failed"); timestamp t3(0, -42); if (t3.to_mseconds() != -1) throw(basic_error() << "to_msecond failed"); timestamp t4(-1, -42); if (t4.to_mseconds() != -1001) throw(basic_error() << "to_msecond failed"); timestamp t5(1, -42); if (t5.to_mseconds() != 999) throw(basic_error() << "to_msecond failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_to_seconds.cc000066400000000000000000000030041407153644500221230ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp to seconds. * * @return 0 on success. */ int main() { try { timestamp t1(1, 42); if (t1.to_seconds() != 1) throw(basic_error() << "to_second failed"); timestamp t2(-1, 0); if (t2.to_seconds() != -1) throw(basic_error() << "to_second failed"); timestamp t3(0, -42); if (t3.to_seconds() != -1) throw(basic_error() << "to_second failed"); timestamp t4(-1, -42); if (t4.to_seconds() != -2) throw(basic_error() << "to_second failed"); timestamp t5(1, -42); if (t5.to_seconds() != 0) throw(basic_error() << "to_second failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); } centreon-clib-21.04.2/test/timestamp_to_useconds.cc000066400000000000000000000030531407153644500223140ustar00rootroot00000000000000/* ** 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 #include "com/centreon/exceptions/basic.hh" #include "com/centreon/timestamp.hh" using namespace com::centreon; /** * Check the timestamp to microseconds. * * @return 0 on success. */ int main() { try { timestamp t1(1, 42); if (t1.to_useconds() != 1000042) throw(basic_error() << "to_usecond failed"); timestamp t2(-1, 0); if (t2.to_useconds() != -1000000) throw(basic_error() << "to_usecond failed"); timestamp t3(0, -42); if (t3.to_useconds() != -42) throw(basic_error() << "to_usecond failed"); timestamp t4(-1, -42); if (t4.to_useconds() != -1000042) throw(basic_error() << "to_usecond failed"); timestamp t5(1, -42); if (t5.to_useconds() != 999958) throw(basic_error() << "to_usecond failed"); } catch (std::exception const& e) { std::cerr << "error: " << e.what() << std::endl; return (1); } return (0); }