enh(ci): add pipeline for as400 using nfpm (#5167)

This commit is contained in:
tuntoja 2024-09-23 16:12:58 +02:00 committed by GitHub
parent a8a0d03a8a
commit 53afb6ee11
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
100 changed files with 8668 additions and 0 deletions

View File

@ -0,0 +1,29 @@
ARG REGISTRY_URL
FROM ${REGISTRY_URL}/almalinux:8
RUN bash -e <<EOF
dnf install -y \
git \
wget \
zstd \
https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.rpm
cd /usr/local/src
wget https://dlcdn.apache.org/maven/maven-3/3.8.8/binaries/apache-maven-3.8.8-bin.tar.gz
tar zxf apache-maven-3.8.8-bin.tar.gz
ln -s /usr/local/src/apache-maven-3.8.8/bin/mvn /usr/bin/mvn
rm -f apache-maven-3.8.8-bin.tar.gz
echo '[goreleaser]
name=GoReleaser
baseurl=https://repo.goreleaser.com/yum/
enabled=1
gpgcheck=0' | tee /etc/yum.repos.d/goreleaser.repo
dnf install -y nfpm
dnf clean all
EOF
WORKDIR /src

View File

@ -0,0 +1,29 @@
ARG REGISTRY_URL
FROM ${REGISTRY_URL}/almalinux:9
RUN bash -e <<EOF
dnf install -y \
git \
wget \
zstd \
https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.rpm
cd /usr/local/src
wget https://dlcdn.apache.org/maven/maven-3/3.8.8/binaries/apache-maven-3.8.8-bin.tar.gz
tar zxf apache-maven-3.8.8-bin.tar.gz
ln -s /usr/local/src/apache-maven-3.8.8/bin/mvn /usr/bin/mvn
rm -f apache-maven-3.8.8-bin.tar.gz
echo '[goreleaser]
name=GoReleaser
baseurl=https://repo.goreleaser.com/yum/
enabled=1
gpgcheck=0' | tee /etc/yum.repos.d/goreleaser.repo
dnf install -y nfpm
dnf clean all
EOF
WORKDIR /src

View File

@ -0,0 +1,24 @@
ARG REGISTRY_URL
FROM ${REGISTRY_URL}/debian:bookworm
RUN bash -e <<EOF
apt-get update
apt-get install -y \
ca-certificates \
git \
zstd \
maven=3.8.7-1 \
openjdk-17-jdk
echo 'deb [trusted=yes] https://repo.goreleaser.com/apt/ /' | tee /etc/apt/sources.list.d/goreleaser.list
apt-get update
apt-get install -y nfpm
apt-get clean all
EOF
WORKDIR /src

View File

@ -0,0 +1,24 @@
ARG REGISTRY_URL
FROM ${REGISTRY_URL}/debian:bullseye
RUN bash -e <<EOF
apt-get update
apt-get install -y \
ca-certificates \
git \
zstd \
maven=3.6.3-5 \
openjdk-17-jdk
echo 'deb [trusted=yes] https://repo.goreleaser.com/apt/ /' | tee /etc/apt/sources.list.d/goreleaser.list
apt-get update
apt-get install -y nfpm
apt-get clean all
EOF
WORKDIR /src

View File

@ -0,0 +1,30 @@
ARG REGISTRY_URL
FROM ${REGISTRY_URL}/ubuntu:jammy
RUN bash -e <<EOF
apt-get update
apt-get install -y \
ca-certificates \
git \
wget \
zstd \
openjdk-17-jdk
cd /usr/local/src
wget https://dlcdn.apache.org/maven/maven-3/3.8.8/binaries/apache-maven-3.8.8-bin.tar.gz
tar zxf apache-maven-3.8.8-bin.tar.gz
ln -s /usr/local/src/apache-maven-3.8.8/bin/mvn /usr/bin/mvn
rm -f apache-maven-3.8.8-bin.tar.gz
echo 'deb [trusted=yes] https://repo.goreleaser.com/apt/ /' | tee /etc/apt/sources.list.d/goreleaser.list
apt-get update
apt-get install -y nfpm
apt-get clean all
EOF
WORKDIR /src

149
.github/workflows/as400.yml vendored Normal file
View File

@ -0,0 +1,149 @@
name: as400
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
on:
workflow_dispatch:
pull_request:
paths:
- 'as400/packaging/**'
push:
branches:
- develop
- master
paths:
- 'as400/packaging/**'
jobs:
get-environment:
uses: ./.github/workflows/get-environment.yml
with:
version_file: as400/packaging/centreon-as400-daemon.yaml
package:
needs: [get-environment]
runs-on: ubuntu-22.04
strategy:
fail-fast: false
matrix:
include:
- package_extension: rpm
image: packaging-plugins-java-alma8
distrib: el8
- package_extension: rpm
image: packaging-plugins-java-alma9
distrib: el9
- package_extension: deb
image: packaging-plugins-java-bullseye
distrib: bullseye
- package_extension: deb
image: packaging-plugins-java-bookworm
distrib: bookworm
- package_extension: deb
image: packaging-plugins-java-jammy
distrib: jammy
container:
image: ${{ vars.DOCKER_INTERNAL_REGISTRY_URL }}/${{ matrix.image }}
credentials:
username: ${{ secrets.DOCKER_REGISTRY_ID }}
password: ${{ secrets.DOCKER_REGISTRY_PASSWD }}
name: package ${{ matrix.distrib }}
steps:
- name: Checkout sources
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- name: Prepare files for packaging
run: |
find . \
-type f \
-exec grep -E '(@CONNECTOR_VERSION@)|(@CONNECTOR_HOME@)|(@CONNECTOR_ETC@)|(@CONNECTOR_LOG@)|(@CONNECTOR_USER@)|(@JAVA_BIN@)' {} ';' \
-exec sed -i \
-e 's|@CONNECTOR_VERSION@|'"%{version}"'|g' \
-e 's|@CONNECTOR_HOME@|'"%{_datadir}/centreon-as400"'|g' \
-e 's|@CONNECTOR_ETC@|'"/etc/centreon-as400/"'|g' \
-e 's|@CONNECTOR_LOG@|'"/var/log/centreon-as400/"'|g' \
-e 's|@CONNECTOR_USER@|'"centreon-as400"'|g' \
-e 's|@JAVA_BIN@|'"/usr/bin/java"'|g' \
{} ';'
shell: bash
- name: Set JAVA_HOME
run: export JAVA_HOME=$( java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home' | tr -s ' ' | cut -d ' ' -f 4)
- name: Build JAR using maven
run: mvn -version && mvn clean install -f as400/connector.as400/pom.xml
- name: Remove me after debug
run: find / -name "centreon-as400*.jar"
- name: Package
uses: ./.github/actions/package-nfpm
with:
nfpm_file_pattern: "as400/packaging/centreon-as400-daemon.yaml"
distrib: ${{ matrix.distrib }}
package_extension: ${{ matrix.package_extension }}
version: ${{ needs.get-environment.outputs.version }}
release: ${{ needs.get-environment.outputs.release }}
arch: all
commit_hash: ${{ github.sha }}
cache_key: ${{ github.sha }}-${{ github.run_id }}-${{ matrix.package_extension }}-as400-${{ matrix.distrib }}
rpm_gpg_key: ${{ secrets.RPM_GPG_SIGNING_KEY }}
rpm_gpg_signing_key_id: ${{ secrets.RPM_GPG_SIGNING_KEY_ID }}
rpm_gpg_signing_passphrase: ${{ secrets.RPM_GPG_SIGNING_PASSPHRASE }}
stability: ${{ needs.get-environment.outputs.stability }}
- name: Save to cache
uses: actions/cache/save@704facf57e6136b1bc63b828d79edcd491f0ee84 # v3.3.2
with:
path: ./*.${{ matrix.package_extension }}
key: ${{ github.sha }}-${{ github.run_id }}-${{ matrix.package_extension }}-${{ matrix.distrib }}
deliver-rpm:
needs: [get-environment, package]
if: ${{ contains(fromJson('["stable", "testing", "unstable"]'), needs.get-environment.outputs.stability) }}
runs-on: [self-hosted, common]
strategy:
matrix:
distrib: [el8, el9]
steps:
- name: Checkout sources
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- name: Delivery
uses: ./.github/actions/rpm-delivery
with:
module_name: as400
distrib: ${{ matrix.distrib }}
cache_key: ${{ github.sha }}-${{ github.run_id }}-rpm-${{ matrix.distrib }}
stability: ${{ needs.get-environment.outputs.stability }}
artifactory_token: ${{ secrets.ARTIFACTORY_ACCESS_TOKEN }}
deliver-deb:
needs: [get-environment, package]
if: ${{ contains(fromJson('["stable", "testing", "unstable"]'), needs.get-environment.outputs.stability) }}
runs-on: [self-hosted, common]
strategy:
matrix:
distrib: [bullseye, bookworm, jammy]
steps:
- name: Checkout sources
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- name: Delivery
uses: ./.github/actions/deb-delivery
with:
module_name: as400
distrib: ${{ matrix.distrib }}
cache_key: ${{ github.sha }}-${{ github.run_id }}-deb-${{ matrix.distrib }}
stability: ${{ needs.get-environment.outputs.stability }}
artifactory_token: ${{ secrets.ARTIFACTORY_ACCESS_TOKEN }}

View File

@ -28,6 +28,12 @@ jobs:
- runner: ubuntu-22.04 - runner: ubuntu-22.04
dockerfile: packaging-plugins-alma9 dockerfile: packaging-plugins-alma9
image: packaging-plugins-alma9 image: packaging-plugins-alma9
- runner: ubuntu-22.04
dockerfile: packaging-plugins-java-alma8
image: packaging-plugins-java-alma8
- runner: ubuntu-22.04
dockerfile: packaging-plugins-java-alma9
image: packaging-plugins-java-alma9
- runner: ubuntu-22.04 - runner: ubuntu-22.04
dockerfile: packaging-plugins-bullseye dockerfile: packaging-plugins-bullseye
image: packaging-plugins-bullseye image: packaging-plugins-bullseye
@ -37,9 +43,18 @@ jobs:
- runner: ubuntu-22.04 - runner: ubuntu-22.04
dockerfile: packaging-plugins-bookworm dockerfile: packaging-plugins-bookworm
image: packaging-plugins-bookworm image: packaging-plugins-bookworm
- runner: ubuntu-22.04
dockerfile: packaging-plugins-java-bullseye
image: packaging-plugins-java-bullseye
- runner: ubuntu-22.04
dockerfile: packaging-plugins-java-bookworm
image: packaging-plugins-java-bookworm
- runner: ubuntu-22.04 - runner: ubuntu-22.04
dockerfile: packaging-plugins-jammy dockerfile: packaging-plugins-jammy
image: packaging-plugins-jammy image: packaging-plugins-jammy
- runner: ubuntu-22.04
dockerfile: packaging-plugins-java-jammy
image: packaging-plugins-java-jammy
runs-on: ${{ matrix.runner }} runs-on: ${{ matrix.runner }}

202
as400/LICENSE Normal file
View File

@ -0,0 +1,202 @@
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.

5
as400/changelog Normal file
View File

@ -0,0 +1,5 @@
2021-12-31 Quentin Garnier <qgarnier@centreon.com> - 2.0.1
* Use log4j 2.17.1
2021-10-13 Quentin Garnier <qgarnier@centreon.com> - 2.0.0
* New release

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>as400.install</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>

View File

@ -0,0 +1,39 @@
daemonListenerHost=localhost
#as400 login timeout for nagios check (ms)
as400LoginTimeout=10000
#as400 read timeout for nagios check (ms)
as400ReadTimeout=300000
#Time before cleaning an unused as400 resource (ms)
as400ResourceDuration=7200000
#time before killing a dead as400 connection (s)
as400SoLinger=1
#Duration of the job & (ms)
cacheTimeout=60000
daemonNoRequestTimeout=5000
daemonRequestParseTimeout=5000
#time before killing a dead as400 connection (s)
daemonSoLinger=1
#Time before discaring a check in queue (ms)
workerQueueTimeout=360000
# active debug
debug=false
# active exception
exception=false
# active trace (in /tmp/trace.log)
trace=false
# MessageQueueDB Base path
pathMsgQDB=/tmp/

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="console" target="System.err">
<PatternLayout pattern="[%-20d{dd/MM/yyyy HH:mm:ss}] [%-6p] %m %n"/>
</Console>
<RollingFile name="RollingFile">
<FileName>${sys:CONNECTOR_LOG}/connector.log</FileName>
<FilePattern>${sys:CONNECTOR_LOG}/connector.%d{yyyy-MM-dd}.log</FilePattern>
<PatternLayout>
<Pattern>[%-20d{dd/MM/yyyy HH:mm:ss}] [%-6p] %m %n</Pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="5MB" />
</Policies>
<DefaultRolloverStrategy max="10" />
</RollingFile>
</Appenders>
<Loggers>
<Logger name="org.apache.log4j.xml" level="info"/>
<Root level="error">
<AppenderRef ref="RollingFile"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,8 @@
# centreon-as400 command line options
JAVA_OPTS="-Xms128M -Xmx2G -XX:MaxPermSize=128m"
CONNECTOR_OPTS="--port 8091"
CONNECTOR_HOME=@CONNECTOR_HOME@
CONNECTOR_ETC=@CONNECTOR_ETC@
CONNECTOR_LOG=@CONNECTOR_LOG@
CONNECTOR_TMP=/tmp/
CONNECTOR_BIN=@CONNECTOR_HOME@/bin/centreon-as400-@CONNECTOR_VERSION@-jar-with-dependencies.jar

View File

@ -0,0 +1,29 @@
##
## Copyright 2019-2021 Centreon
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
## For more information : contact@centreon.com
##
[Unit]
Description=Centreon AS400
[Service]
EnvironmentFile=/etc/sysconfig/centreon-as400
ExecStart=@JAVA_BIN@ $JAVA_OPTS -DCONNECTOR_HOME=${CONNECTOR_HOME} -DCONNECTOR_ETC=${CONNECTOR_ETC} -DCONNECTOR_LOG=${CONNECTOR_LOG} -DCONNECTOR_TMP=${CONNECTOR_TMP} -jar $CONNECTOR_BIN $CONNECTOR_OPTS
Type=simple
User=centreon-as400
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,243 @@
#!/bin/bash
#################################################
##Functions and vars for actions results printing
#################################################
RES_COL=80
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_INFO="echo -en \\033[1;38m"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
function echo_success() {
echo -n "$1"
$MOVE_TO_COL
$SETCOLOR_SUCCESS
echo -n "$2"
$SETCOLOR_NORMAL
echo -e "\r"
echo ""
}
function echo_failure() {
echo -n "$1"
$MOVE_TO_COL
$SETCOLOR_FAILURE
echo -n "$2"
$SETCOLOR_NORMAL
echo -e "\r"
echo ""
}
function echo_passed() {
echo -n "$1"
$MOVE_TO_COL
$SETCOLOR_WARNING
echo -n "$2"
$SETCOLOR_NORMAL
echo -e "\r"
echo ""
}
##################
##Static variables
##################
INIT_FOLDER="init-script/"
INIT_FILE="centreon-as400.service"
SYSCONFIG_FILE="centreon-as400-sysconfig"
CONNECTOR_VERSION=2.0.0
CONNECTOR_HOME="/usr/share/centreon-as400/"
CONNECTOR_LOG="/var/log/centreon-as400/"
CONNECTOR_ETC="/etc/centreon-as400/"
LOG_ETC_FILE="log4j.xml"
CONNECTOR_USER="centreon-as400"
CONNECTOR_GROUP="centreon-as400"
JAVA_BIN=""
ETC_PASSWD="/etc/passwd"
ETC_GROUP="/etc/group"
ETC_INITD="/etc/systemd/system/"
ETC_SYSCONFIG="/etc/sysconfig/"
######
##INIT
######
$SETCOLOR_WARNING
echo "Starting setup..."
$SETCOLOR_NORMAL
echo ""
##############################
##Getting modules install path
##############################
DONE="no"
CREATE_HOME="no"
temp_folder="$CONNECTOR_HOME"
while [ "$DONE" = "no" ]; do
echo "Centreon AS400 home Directory [$CONNECTOR_HOME]? "
echo -n ">"
read temp_folder
if [ -z "$temp_folder" ]; then
temp_folder="$CONNECTOR_HOME"
fi
temp_folder=`echo "$temp_folder" | sed "s/$/\//"`
if [ -d "$temp_folder" ]; then
DONE="yes"
else
echo_failure "$temp does not exists" "CRITICAL"
echo "Specified path does not exists, do you want to create it ?[Y/n]"
echo -n ">"
read temp
if [ -z "$temp" ]; then
temp="Y"
fi
while [ "$temp" != "Y" ] && [ "$temp" != "y" ] && [ "$temp" != "n" ] && [ "$temp" != "N" ]; do
echo "Specified path does not exists, do you want to create it ?[Y/n]"
echo -n ">"
read temp
if [ -z "$temp" ]; then
temp="Y"
fi
done
if [ "$temp" = "Y" ] || [ "$temp" = "y" ]; then
DONE="yes"
CREATE_HOME="yes"
fi
fi
done
temp_folder=$(echo $temp_folder | sed "s/\/\/$/\//")
CONNECTOR_HOME=${temp_folder}
echo_success "Centreon AS400 home directory" "$CONNECTOR_HOME"
#############################
##Getting java home directory
#############################
JAVA_HOME="/usr/"
temp=$JAVA_HOME
while [ ! -x "$temp/bin/java" ]; do
echo_failure "Cannot find java binary" "FAILURE"
echo "Java home directory?"
echo -n ">"
read temp
if [ -z "$temp" ]; then
temp="$JAVA_HOME"
fi
done
temp=`echo "$temp" | sed "s/$/\//"`
JAVA_BIN=`echo $temp | sed "s/\/\/$/\//"`"bin/java"
echo_success "Java bin path :" "$JAVA_BIN"
###################
# CONNECTOR INIT SCRIPT
###################
echo "Do you want to install AS400 systemd script [y/N]?"
echo -n ">"
read response
if [ -z "$response" ]; then
response="N"
fi
while [ "$response" != "Y" ] && [ "$response" != "y" ] && [ "$response" != "N" ] && [ "$response" != "n" ]; do
echo "Do you want to install AS400 systemd script [y/N]?"
echo -n ">"
read response
if [ -z "$response" ]; then
response="N"
fi
done
INSTALL_CONNECTOR_INIT=$response
echo_success "CONNECTOR systemd script :" "$ETC_INITD/$INIT_FILE"
########################
## Centreon BI user and Group
########################
exists=`cat $ETC_PASSWD | grep "^$CONNECTOR_USER:"`
if [ -z "$exists" ]; then
useradd -m $CONNECTOR_USER -d $CONNECTOR_HOME
fi
echo_success "CONNECTOR run user :" "$CONNECTOR_USER"
exists=`cat $ETC_GROUP | grep "^$CONNECTOR_GROUP:"`
if [ -z "$exists" ]; then
groupadd $CONNECTOR_GROUP
fi
echo_success "CONNECTOR run group :" "$CONNECTOR_GROUP"
#######################
# DEPLOYING CENTREON BI
#######################
echo ""
echo_success "Creating directories and moving binaries..." "OK"
if [ ! -d "${CONNECTOR_HOME}" ]; then
mkdir -p $CONNECTOR_HOME
fi
if [ ! -d "${CONNECTOR_HOME}/bin" ]; then
mkdir ${CONNECTOR_HOME}/bin
fi
if [ -d bin/ ] ; then
cp -f bin/*.jar ${CONNECTOR_HOME}/bin/
fi
if [ ! -d "${CONNECTOR_LOG}" ]; then
mkdir -p ${CONNECTOR_LOG}
fi
if [ ! -d "${CONNECTOR_ETC}" ]; then
mkdir -p ${CONNECTOR_ETC}
fi
cp etc/log4j.xml ${CONNECTOR_ETC}
cp etc/config.properties ${CONNECTOR_ETC}
###################
##Macro replacement
###################
ETC_FILE=${CONNECTOR_ETC}${CONNECTOR_ETC_FILE}
if [ "$INSTALL_CONNECTOR_INIT" = "y" ] || [ "$INSTALL_CONNECTOR_INIT" = "Y" ]; then
echo_success "Copying CONNECTOR init script..." "OK"
sed -e 's|@JAVA_BIN@|'"$JAVA_BIN"'|g' \
$INIT_FOLDER/$INIT_FILE > $ETC_INITD/$INIT_FILE
chmod 644 $ETC_INITD/$INIT_FILE
sed -e 's|@CONNECTOR_HOME@|'"$CONNECTOR_HOME"'|g' \
-e 's|@JAVA_BIN@|'"$JAVA_BIN"'|g' \
-e 's|@CONNECTOR_USER@|'"$CONNECTOR_USER"'|g' \
-e 's|@CONNECTOR_ETC@|'"${CONNECTOR_ETC}"'|g' \
-e 's|@CONNECTOR_LOG@|'"${CONNECTOR_LOG}"'|g' \
-e 's|@CONNECTOR_VERSION@|'"${CONNECTOR_VERSION}"'|g' \
$INIT_FOLDER/$SYSCONFIG_FILE > $ETC_SYSCONFIG/centreon-as400
fi
echo_success "Deploying Centreon-AS400..." "OK"
###################################################
##Rights settings on install directory and binaries
###################################################
chown -R $CONNECTOR_USER.$CONNECTOR_GROUP $CONNECTOR_HOME
chown -R $CONNECTOR_USER.$CONNECTOR_GROUP $CONNECTOR_LOG
chown -R $CONNECTOR_USER.$CONNECTOR_GROUP $CONNECTOR_ETC
chmod -R 775 $CONNECTOR_HOME
echo_success "Rights settings..." "OK"
systemctl enable $INIT_FILE
#########
# THE END
#########
echo ""
$SETCOLOR_WARNING
echo "Setup finished."
echo ""

View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="target/generated-sources/annotations">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="ignore_optional_problems" value="true"/>
<attribute name="m2e-apt" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="target/generated-sources/test-annotations">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="ignore_optional_problems" value="true"/>
<attribute name="m2e-apt" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

2
as400/connector.as400/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.vscode
/target

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>as400</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.sonar.ide.eclipse.core.sonarNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,6 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/test/java=UTF-8
encoding//src/test/resources=UTF-8
encoding/<project>=UTF-8

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
org.eclipse.jdt.apt.aptEnabled=false

View File

@ -0,0 +1,7 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.processAnnotations=disabled
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.6

View File

@ -0,0 +1,5 @@
#Tue Nov 08 15:01:53 CET 2011
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@ -0,0 +1,8 @@
#Tue Nov 08 15:01:08 CET 2011
activeProfiles=
eclipse.preferences.version=1
fullBuildGoals=process-test-resources
resolveWorkspaceProjects=true
resourceFilterGoals=process-resources resources\:testResources
skipCompilerPlugin=true
version=1

View File

@ -0,0 +1,5 @@
eclipse.preferences.version=1
extraProperties=sonar.java.coveragePlugin\=jacoco\r\nsonar.language\=java\r\nsonar.jacoco.itReportPath\=/home/jblamotte/git/centreon-connector-as400/connector.as400/../target/jacoco-it.exec\r\nsonar.dynamicAnalysis\=reuseReports
projectKey=com.centreon.connector\:connector-as400
serverUrl=http\://localhost\:9000
version=2

View File

@ -0,0 +1,4 @@
#Thu Sep 22 10:02:29 CEST 2011
eclipse.preferences.version=1
projectArtifactId=connector-as400
projectGroupId=com.centreon.connector

View File

@ -0,0 +1,25 @@
# Tools
## Launch test
### Build
mvn clean package
### Execute
java \
-DCONNECTOR_ETC=target/test-classes/ \
-DCONNECTOR_HOME=target/test-classes/ \
-DCONNECTOR_LOG=target/test-classes/ \
-DCONNECTOR_TMP=target/test-classes/ \
-jar target/centreon-as400-2.0.0-jar-with-dependencies.jar \
--port 8091
### Test
curl -X POST -d '{"host": "test-as400", "login": "myuser", "password": "mypass", "command": "test" }' http://127.0.0.1:8091
## References
[IBM knowledge center example](https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_72/rzahh/pcsystemstatexample.htm)

View File

@ -0,0 +1,241 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.centreon.connector</groupId>
<artifactId>centreon-as400</artifactId>
<version>2.0.2</version>
<name>Centreon-AS/400</name>
<description>Connecteur AS/400</description>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.0.5.RELEASE</spring.version>
<java.version>17</java.version>
<log4j.version>2.17.1</log4j.version>
<!-- Sonar -->
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.itReportPath>${project.basedir}/../target/jacoco-it.exec</sonar.jacoco.itReportPath>
<sonar.language>java</sonar.language>
</properties>
<developers>
<developer>
<id>qgarnier</id>
<name>Quentin GARNIER</name>
<email>qgarnier@centreon.com</email>
<organization>Centreon</organization>
</developer>
<developer>
<id>jblamotte</id>
<name>Jean-Baptiste LAMOTTE</name>
<organization>Centreon</organization>
</developer>
</developers>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<!-- <descriptors> <descriptor>jar-with-dependencies-packed.xml</descriptor>
</descriptors> -->
<archive>
<manifest>
<mainClass>com.centreon.connector.as400.Main</mainClass>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
<plugin>
<groupId>org.fusesource.mvnplugins</groupId>
<artifactId>maven-graph-plugin</artifactId>
<version>1.35</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<!-- <includes> -->
<!-- <include>>com.centreon.**</include> -->
<!-- </includes> -->
<!-- <includes>com.centreon.*</includes> -->
</configuration>
<executions>
<execution>
<id>pre-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>post-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.12</version>
</plugin>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.jacoco</groupId>
<artifactId>
jacoco-maven-plugin
</artifactId>
<versionRange>
[0.8.2,)
</versionRange>
<goals>
<goal>prepare-agent</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencies>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.sf.jt400</groupId>
<artifactId>jt400</artifactId>
<version>10.7</version>
<type>jar</type>
<!-- <scope>compile</scope> -->
</dependency>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-core</artifactId>
<version>2.2.11.Final</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.13.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<reporting>
<plugins>
<!-- Normally, we take off the dependency report, saves time. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.7</version>
<configuration>
<dependencyLocationsEnabled>false</dependencyLocationsEnabled>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.6</version>
<configuration>
<formats>
<format>html</format>
<format>xml</format>
</formats>
</configuration>
</plugin>
</plugins>
</reporting>
</project>

View File

@ -0,0 +1,143 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author Lamotte Jean-Baptiste
*/
public class Conf {
public static void loadConfiguration(final InputStream in) throws IOException {
final Properties properties = new Properties();
properties.load(in);
String param;
Conf.debug = Boolean.parseBoolean("" + properties.get("debug"));
Conf.exception = Boolean.parseBoolean("" + properties.get("exception"));
Conf.trace = Boolean.parseBoolean("" + properties.get("trace"));
param = (String)properties.get("daemonListenerHost");
if (param != null) {
Conf.daemonListenerHost = param;
}
param = (String)properties.get("daemonNoRequestTimeout");
if (param != null) {
Conf.daemonNoRequestTimeout = Integer.parseInt(param);
}
param = (String)properties.get("daemonRequestParseTimeout");
if (param != null) {
Conf.daemonRequestParseTimeout = Integer.parseInt(param);
}
Conf.authUsername = (String)properties.get("authUsername");
Conf.authPassword = (String)properties.get("authPassword");
param = (String)properties.get("keyStoreType");
if (param != null) {
Conf.keyStoreType = param;
}
Conf.keyStoreFile = (String)properties.get("keyStoreFile");
Conf.keyStorePassword = (String)properties.get("keyStorePassword");
param = (String)properties.get("sslProtocol");
if (param != null) {
Conf.sslProtocol = param;
}
Conf.daemonSoLinger = Integer.parseInt("" + properties.get("daemonSoLinger"));
Conf.as400SoLinger = Integer.parseInt("" + properties.get("as400SoLinger"));
Conf.as400ReadTimeout = Integer.parseInt("" + properties.get("as400ReadTimeout"));
Conf.as400LoginTimeout = Integer.parseInt("" + properties.get("as400LoginTimeout"));
Conf.as400ResourceDuration = Integer.parseInt("" + properties.get("as400ResourceDuration"));
Conf.workerQueueTimeout = Integer.parseInt("" + properties.get("workerQueueTimeout"));
Conf.cacheTimeout = Integer.parseInt("" + properties.get("cacheTimeout"));
Conf.msgqDbPath = "" + properties.get("pathMsgQDB");
}
public static boolean debug = true;
static boolean exception = true;
static boolean trace = true;
public static String msgqDbPath = "/tmp/";
public static String daemonListenerHost = "localhost";
public static int daemonNoRequestTimeout = 5000;
public static int daemonRequestParseTimeout = 5000;
public static String authUsername = null;
public static String authPassword = null;
public static String keyStoreType = "PKCS12";
public static String keyStoreFile = null;
public static String keyStorePassword = null;
public static String sslProtocol = "TLS";
/**
* Delai avant fermeture force d'une connexion mal ferme par les plugins de
* check (en mode daemon) unite en seconde
*/
public static int daemonSoLinger = 1;
/**
* Delai avant fermeture force d'une connexion mal ferme par l'AS/400 unite en
* seconde
*/
public static int as400SoLinger = 1;
/**
* Timeout lors de la reception d'une reponse de l'AS400 unite en milliseconde
*/
public static int as400ReadTimeout = 5 * 60 * 1000;
/**
* Timeout lors de la connexion a un as/400 unite en milliseconde
*/
public static int as400LoginTimeout = 10 * 1000;
/**
* Delai avant de supprimer une connection inactive a un as/400 unite en
* millisecondes
*/
public static long as400ResourceDuration = 120 * 60 * 1000;
/**
* duree maximale d'attente d'un check dans une queue unite en millisecondes
*/
public static long workerQueueTimeout = 6 * 60 * 1000;
/**
* cache duration for disk and job (time before next refresh) duration in
* milliseconds
*/
public static long cacheTimeout = 60 * 1000;
}

View File

@ -0,0 +1,151 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import java.io.File;
/**
* @author Lamotte Jean-Baptiste
*/
public class ConnectorLogger {
private static ConnectorLogger instance = null;
public synchronized static final ConnectorLogger getInstance() {
if (ConnectorLogger.instance == null) {
ConnectorLogger.instance = new ConnectorLogger(Main.getEtcDir());
}
return ConnectorLogger.instance;
}
private Logger logger = null;
private ConnectorLogger(String etcDir) {
if ((etcDir != null) && (etcDir.length() > 0)) {
LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
File file = new File(etcDir + "log4j2.xml");
context.setConfigLocation(file.toURI());
} else {
// DOMConfigurator.configure("log4j.xml");
}
this.logger = LogManager.getRootLogger();
}
public synchronized void debug(final String log) {
this.logger.debug(log);
}
public synchronized void trace(final String log, final Throwable t) {
this.logger.trace(log, t);
}
public synchronized void trace(final String log) {
this.logger.trace(log);
}
public synchronized void debug(final String log, final Throwable t) {
if (Conf.exception) {
this.logger.debug(log, t);
} else {
this.logger.debug(log);
this.logger.debug(" --> Message: " + t.getMessage());
Throwable cause = null;
if ((cause = t.getCause()) != null) {
this.logger.debug(" --> Cause: " + cause.getMessage());
}
}
}
public synchronized void error(final String log) {
this.logger.error(log);
}
public void error(final String log, final Throwable t) {
if (Conf.exception) {
this.logger.error(log, t);
} else {
this.logger.error(log);
this.logger.error(" --> Message: " + t.getMessage());
Throwable cause = null;
if ((cause = t.getCause()) != null) {
this.logger.error(" --> Cause: " + cause.getMessage());
}
}
}
public synchronized void fatal(final String log) {
this.logger.fatal(log);
}
public synchronized void fatal(final String log, final Throwable t) {
if (Conf.exception) {
this.logger.fatal(log, t);
} else {
this.logger.fatal(log);
this.logger.fatal(" --> Message: " + t.getMessage());
Throwable cause = null;
if ((cause = t.getCause()) != null) {
this.logger.fatal(" --> Cause: " + cause.getMessage());
}
}
}
public synchronized Logger getLogger() {
return this.logger;
}
public synchronized void info(final String log) {
this.logger.info(log);
}
public synchronized void info(final String log, final Throwable t) {
if (Conf.exception) {
this.logger.info(log, t);
} else {
this.logger.info(log);
this.logger.info(" --> Message: " + t.getMessage());
Throwable cause = null;
if ((cause = t.getCause()) != null) {
this.logger.info(" --> Cause: " + cause.getMessage());
}
}
}
public synchronized void warn(final String log) {
this.logger.warn(log);
}
public synchronized void warn(final String log, final Throwable t) {
if (Conf.exception) {
this.logger.warn(log, t);
} else {
this.logger.warn(log);
this.logger.warn(" --> Message: " + t.getMessage());
Throwable cause = null;
if ((cause = t.getCause()) != null) {
this.logger.warn(" --> Cause: " + cause.getMessage());
}
}
}
}

View File

@ -0,0 +1,162 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.PosixParser;
import com.ibm.as400.access.Trace;
import com.centreon.connector.as400.daemon.Daemon;
import com.centreon.connector.as400.dispatcher.client.impl.ClientDispatcherImpl;
import com.centreon.connector.as400.parser.OptionFactory;
/**
* @author Lamotte Jean-Baptiste
*/
class Main {
static public final String CONNECTOR_LOG = "CONNECTOR_LOG";
static public final String CONNECTOR_ETC = "CONNECTOR_ETC";
static private String etcDir;
static public String getEtcDir() {
return etcDir;
}
private static void checkProperties() {
etcDir = System.getProperty(Main.CONNECTOR_ETC, "/etc/centreon-as400/");
String logDir = System.getProperty(Main.CONNECTOR_LOG, "/var/log/centreon-as400/");
try {
final File file = new File(etcDir + "log4j2.xml");
if (!file.exists()) {
ConnectorLogger.getInstance().fatal(etcDir + "log4j2.xml doesnt exist. Engine stopped");
System.exit(0);
}
ConnectorLogger.getInstance().info("[Logs] Logs configuration file : " + file.getAbsolutePath());
} catch (final Exception e) {
ConnectorLogger.getInstance().fatal("", e);
}
System.setErr(System.out);
try {
ConnectorLogger.getInstance().info("[Config] Configuration file : " + etcDir + "config.properties");
Conf.loadConfiguration(new FileInputStream(etcDir + "config.properties"));
} catch (final IOException e) {
ConnectorLogger.getInstance().fatal("", e);
System.exit(0);
}
if (Conf.trace == true) {
try {
final String traceLog = logDir + "/trace.log";
ConnectorLogger.getInstance().debug("Advanced trace log file : " + traceLog);
Trace.setFileName(traceLog);
Trace.setTraceAllOn(false);
Trace.setTraceOn(true);
Trace.setTraceErrorOn(true);
Trace.setTraceWarningOn(true);
Trace.setTraceInformationOn(true);
} catch (final Exception e) {
ConnectorLogger.getInstance().debug("", e);
}
}
}
private static void daemon(final CommandLine cmd) {
try {
int port = 8091;
if (cmd.hasOption("port")) {
port = Integer.parseInt(cmd.getOptionValue("port"));
}
final Daemon core = new Daemon();
core.start(port);
} catch (IOException ioe) {
System.out.println("Couldn't start server: " + ioe);
} catch (InterruptedException ie) {
System.out.println("Interrupted exception: " + ie);
} catch (final Exception e) {
ConnectorLogger.getInstance().fatal("Couldn't start server", e);
} finally {
System.exit(0);
}
}
/**
* Gets the help.
*
* @return the help
*/
private static String getHelp() {
final HelpFormatter formatter = new HelpFormatter();
String exemple = "--port <port>\n";
exemple += "\n";
formatter.printHelp(" ", exemple, OptionFactory.getOptions(), "");
return "";
}
/**
* The main method.
*
* @param args the arguments
*/
public static void main(final String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
ConnectorLogger.getInstance().info("Shutdown Centreon-Connector");
super.run();
}
});
Main.checkProperties();
try {
final CommandLineParser parser = new PosixParser();
final CommandLine cmd = parser.parse(OptionFactory.getOptions(), args);
Main.daemon(cmd);
} catch (final Exception e) {
ConnectorLogger.getInstance().fatal("", e);
Main.getHelp();
}
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400;
/**
* Launch the Engine from a variety of sources, either through a main() or
* invoked through Apache Daemon.
*/
public class WinService {
public static void main(final String[] args) throws Exception {
WinService.start(new String[] { "--port", "8091" });
}
public static void start(final String[] args) throws Exception {
final String[] tabArgs = new String[(args.length + 1)];
tabArgs[0] = "service";
int i = 1;
for (final String str : args) {
tabArgs[i] = str;
i++;
}
final Thread thread = new Thread() {
@Override
public void run() {
Main.main(tabArgs);
}
};
thread.setDaemon(false);
thread.start();
// Main.main(new String[] {"service", "--daemon", "8090"});
// System.out.println("Out:EngineLauncher#start");
// ConnectorLogger.getInstance().info("EngineLauncher#start");
/*
* Thread thread = new Thread() {
*
* @Override public void run() { while (true) { try { Thread.sleep(1000); }
* catch (InterruptedException e) { e.printStackTrace(); }
* System.out.println("Out:EngineLauncher#isRunning");
* ConnectorLogger.getInstance().info("EngineLauncher#isRunning"); } }
*
* };
*
* thread.start();
*/
}
public static void stop(final String[] args) throws Exception {
System.out.println("Out:EngineLauncher#stop");
ConnectorLogger.getInstance().info("EngineLauncher#stop");
System.exit(0);
}
}

View File

@ -0,0 +1,30 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
public interface ICachedMessageQueueHandler {
ResponseData getNewMessageInMessageQueue(String messageQueuePath, String messageIdfilterPattern, int minSeverityLevel,
int maxSeverityLevel) throws Exception;
}

View File

@ -0,0 +1,27 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
public interface ICommandHandler {
ResponseData executeCommand(String commandName) throws Exception;
}

View File

@ -0,0 +1,30 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public interface IDiskHandler {
ResponseData listDisks(String diskName) throws Exception;
}

View File

@ -0,0 +1,30 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public interface IJobHandler {
ResponseData listJobs() throws Exception;
}

View File

@ -0,0 +1,34 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler;
import java.util.List;
import java.util.Map;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public interface IJobQueueHandler {
ResponseData getJobQueues(List<Map<String , String>> queues) throws Exception;
}

View File

@ -0,0 +1,33 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public interface IMessageQueueHandler {
void dumpMessageQueue() throws Exception;
ResponseData getErrorMessageQueue(String messageQueuePath, String messageIdfilterPattern,
int minSeverityLevel, int maxSeverityLevel) throws Exception;
}

View File

@ -0,0 +1,33 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler;
import com.ibm.as400.access.Subsystem;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public interface ISubSystemHandler {
void dumpSubSystem(Subsystem subSystem) throws Exception;
ResponseData listSubsystems() throws Exception;
}

View File

@ -0,0 +1,37 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler;
import com.ibm.as400.access.SystemPool;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public interface ISystemHandler {
void dumpPool(SystemPool pool) throws Exception;
void dumpSystem() throws Exception;
ResponseData getPageFault() throws Exception;
ResponseData getSystem() throws Exception;
}

View File

@ -0,0 +1,98 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ConnectionEvent;
import com.ibm.as400.access.ConnectionListener;
import com.ibm.as400.access.SocketProperties;
import com.centreon.connector.as400.Conf;
import com.centreon.connector.as400.ConnectorLogger;
/**
* @author Lamotte Jean-Baptiste
*/
public abstract class AbstractHandler {
private static NumberFormat formatterNoDecimal;
private static NumberFormat formatterTreeDecimal;
protected String host = null;
protected String login = null;
protected String password = null;
public AbstractHandler(final String host, final String login, final String password) {
this.host = host;
this.login = login;
this.password = password;
}
static {
final DecimalFormat df0 = (DecimalFormat) NumberFormat.getNumberInstance(Locale.ENGLISH);
df0.applyPattern("#0");
AbstractHandler.formatterNoDecimal = df0;
final DecimalFormat df3 = (DecimalFormat) NumberFormat.getNumberInstance(Locale.ENGLISH);
df3.applyPattern("#0.###");
AbstractHandler.formatterTreeDecimal = df3;
}
static NumberFormat getFormatterNoDecimal() {
return AbstractHandler.formatterNoDecimal;
}
static NumberFormat getFormatterTreeDecimal() {
return AbstractHandler.formatterTreeDecimal;
}
protected AS400 getNewAs400() throws AS400SecurityException, IOException {
final SocketProperties properties = new SocketProperties();
properties.setSoLinger(1);
properties.setKeepAlive(false);
properties.setTcpNoDelay(true);
properties.setLoginTimeout(Conf.as400LoginTimeout);
properties.setSoTimeout(Conf.as400ReadTimeout);
final AS400 system = new AS400(this.host, this.login, this.password);
system.setSocketProperties(properties);
system.addConnectionListener(new ConnectionListener() {
@Override
public void connected(final ConnectionEvent event) {
ConnectorLogger.getInstance().getLogger().debug("Connect event service : " + event.getService());
}
@Override
public void disconnected(final ConnectionEvent event) {
ConnectorLogger.getInstance().getLogger().debug("Disconnect event service : " + event.getService());
}
});
system.validateSignon();
return system;
}
}

View File

@ -0,0 +1,74 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl;
import java.util.HashMap;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.access.CommandCall;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.check.handler.ICommandHandler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public class CommandHandler extends AbstractHandler implements ICommandHandler {
public CommandHandler(final String host, final String login, final String password) {
super(host, login, password);
}
@Override
public ResponseData executeCommand(final String commandName) throws Exception {
final ResponseData data = new ResponseData();
HashMap<String, Object> attrs = new HashMap<String, Object>();
attrs.put("cmdName", commandName);
attrs.put("status", "success");
final AS400 system = this.getNewAs400();
final CommandCall command = new CommandCall(system);
String output = "";
try {
if (!command.run(commandName)) {
attrs.put("status", "failed");
attrs.put("message", "command run failed");
}
for (final AS400Message message : command.getMessageList()) {
output += message.getText() + "\n";
}
} catch (final Exception e) {
attrs.put("status", "failed");
attrs.put("message", "exception: " + e.getMessage());
ConnectorLogger.getInstance().debug("", e);
}
attrs.put("output", output);
data.getResult().add(attrs);
// Done with the system.
system.disconnectService(AS400.COMMAND);
system.disconnectAllServices();
return data;
}
}

View File

@ -0,0 +1,93 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import com.ibm.as400.access.AS400SecurityException;
import com.centreon.connector.as400.check.handler.IDiskHandler;
import com.centreon.connector.as400.check.handler.impl.disk.QyaspolYasp0300PcmlHandler;
import com.centreon.connector.as400.check.handler.impl.disk.Yasp0300Data;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public class DiskHandler extends AbstractHandler implements IDiskHandler {
private QyaspolYasp0300PcmlHandler qyaspolPcmlHandler = null;
public DiskHandler(final String host, final String login, final String password)
throws AS400SecurityException, IOException {
super(host, login, password);
this.qyaspolPcmlHandler = new QyaspolYasp0300PcmlHandler(host, login, password);
}
@Override
public ResponseData listDisks(final String diskName) throws Exception {
final ResponseData data = new ResponseData();
List<Yasp0300Data> disks = null;
if (diskName == null) {
disks = this.qyaspolPcmlHandler.getDisksList();
} else {
final Yasp0300Data disk = this.qyaspolPcmlHandler.getDiskByResourceName(diskName);
if (disk == null) {
return new ResponseData(ResponseData.statusError, "Disk " + diskName + " not found");
}
disks = new ArrayList<Yasp0300Data>();
disks.add(disk);
}
/*
* 0 - There is no unit control value (noUnitControl)
* 1 - The disk unit is active (active)
* 2 - The disk unit has failed (failed)
* 3 - Some other disk unit in the disk subsystem has failed (otherDiskSubFailed)
* 4 - There is a hardware failure within the disk subsystem that affects performance, but does not affect the function of the disk unit (hwFailurePerf)
* 5 - There is a hardware failure within the disk subsystem that does not affect the function or performance of the disk unit (hwFailureOk)
* 6 - The disk unit's parity protection is being rebuilt (rebuilding)
* 7 - The disk unit is not ready (noReady)
* 8 - The disk unit is write protected (writeProtected)
* 9 - The disk unit is busy. (busy)
* 10 - The disk unit is not operational (notOperational)
* 11 - The disk unit has returned a status that is not recognizable by the system (unknownStatus)
* 12 - The disk unit cannot be accessed (noAccess)
* 13 - The disk unit is read/write protected (rwProtected)
*/
for (final Yasp0300Data disk : disks) {
HashMap<String, Object> attrs = new HashMap<String, Object>();
attrs.put("status", disk.getUnitControl());
attrs.put("name", disk.getResourceName());
attrs.put("totalSpace", disk.getDiskCapacity() * 1024d * 1024d);
attrs.put("reservedSpace", disk.getDiskStorageReservedForSystem() * 1024d * 1024d);
attrs.put("freeSpace", disk.getDiskStorageAvailable() * 1024d * 1024d);
data.getResult().add(attrs);
}
return data;
}
}

View File

@ -0,0 +1,37 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl;
/**
* @author Lamotte Jean-Baptiste
*/
public class FailedCheckException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1812060950998874570L;
public FailedCheckException(final String reason) {
super(reason);
}
}

View File

@ -0,0 +1,95 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedList;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.Job;
import com.ibm.as400.access.JobList;
import com.centreon.connector.as400.Conf;
import com.centreon.connector.as400.ConnectorLogger;
class JobCache {
private volatile LinkedList<Job> lastJobCache = null;
private long lastRefresh = 0;
JobHandler handler;
Exception lastFailException = new Exception("First check");
JobCache(final JobHandler handler) {
this.handler = handler;
}
Collection<Job> getJobListCache(final boolean forceRefresh) throws Exception {
this.refreshJobListCache(forceRefresh);
if (this.lastJobCache == null) {
throw this.lastFailException;
}
return new LinkedList<Job>(this.lastJobCache);
}
Collection<Job> getJobListCache() throws Exception {
return this.getJobListCache(false);
}
private void refreshJobListCache(final boolean forceRefresh) throws Exception {
if (!(((this.lastRefresh + Conf.cacheTimeout) < System.currentTimeMillis()) || forceRefresh)) {
return;
}
final AS400 system = this.handler.getNewAs400();
final JobList jobList = new JobList(system);
jobList.addJobAttributeToRetrieve(Job.ACTIVE_JOB_STATUS);
jobList.addJobAttributeToRetrieve(Job.SUBSYSTEM);
jobList.addJobAttributeToRetrieve(Job.JOB_NAME);
jobList.addJobSelectionCriteria(JobList.SELECTION_PRIMARY_JOB_STATUS_ACTIVE, Boolean.TRUE);
jobList.addJobSelectionCriteria(JobList.SELECTION_PRIMARY_JOB_STATUS_JOBQ, Boolean.FALSE);
jobList.addJobSelectionCriteria(JobList.SELECTION_PRIMARY_JOB_STATUS_OUTQ, Boolean.FALSE);
try {
@SuppressWarnings("unchecked")
final Enumeration<Job> enumeration = jobList.getJobs();
final LinkedList<Job> list = new LinkedList<Job>();
while (enumeration.hasMoreElements()) {
list.add(enumeration.nextElement());
}
this.lastJobCache = list;
} catch (final Exception e) {
this.lastFailException = new FailedCheckException("" + e.getMessage());
this.lastJobCache = null;
ConnectorLogger.getInstance().debug("", e);
} finally {
try {
jobList.close();
system.disconnectAllServices();
} catch (final Exception e) {
ConnectorLogger.getInstance().info("Job list close failed (" + system.getSystemName() + ")", e);
}
this.lastRefresh = System.currentTimeMillis();
}
}
}

View File

@ -0,0 +1,71 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl;
import java.util.Collection;
import java.util.HashMap;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.Job;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.check.handler.IJobHandler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public class JobHandler extends AbstractHandler implements IJobHandler {
private final JobCache jobCache;
public JobHandler(final String host, final String login, final String password) {
super(host, login, password);
this.jobCache = new JobCache(this);
}
@Override
public ResponseData listJobs() throws Exception {
final ResponseData data = new ResponseData();
Collection<Job> jobs = this.jobCache.getJobListCache();
for (final Job job : jobs) {
HashMap<String, Object> attrs = new HashMap<String, Object>();
attrs.put("name", job.getName());
attrs.put("subSystem", job.getSubsystem());
attrs.put("status", job.getStatus());
attrs.put("activeStatus", job.getValue(Job.ACTIVE_JOB_STATUS));
String currentLibrary = "";
try {
job.getCurrentLibrary();
} catch (final Exception e) {
attrs.put("currentLibraryException", e.getMessage());
}
attrs.put("currentLibrary", currentLibrary);
data.getResult().add(attrs);
}
return data;
}
}

View File

@ -0,0 +1,87 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import com.ibm.as400.access.AS400;
import com.centreon.connector.as400.check.handler.IJobQueueHandler;
import com.centreon.connector.as400.check.handler.impl.jobqueue.Jobq0100;
import com.centreon.connector.as400.check.handler.impl.jobqueue.Jobq0200;
import com.centreon.connector.as400.check.handler.impl.jobqueue.Qsprjobq100Handler;
import com.centreon.connector.as400.check.handler.impl.jobqueue.Qsprjobq200Handler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public class JobQueueHandler extends AbstractHandler implements IJobQueueHandler {
public JobQueueHandler(final String host, final String login, final String password) {
super(host, login, password);
}
@Override
public ResponseData getJobQueues(List<Map<String , String>> queues) throws Exception {
final ResponseData data = new ResponseData();
final AS400 system = this.getNewAs400();
final Qsprjobq200Handler qsprjobq200Handler = new Qsprjobq200Handler(system);
for (Map<String, String> queue : queues) {
String name = queue.get("name");
String library = queue.get("library");
if (name == null || library == null) {
return new ResponseData(ResponseData.statusError,
"JobQueue name/library attribute must be set");
}
Jobq0200 jobq0200 = null;
try {
jobq0200 = qsprjobq200Handler.loadJobq0200(name, library);
} catch (final Exception e) {
system.disconnectAllServices();
throw e;
}
if (jobq0200 == null) {
return new ResponseData(ResponseData.statusError,
"JobQueue " + name + " in library " + library + " not found");
}
HashMap<String, Object> attrs = new HashMap<String, Object>();
attrs.put("name", name);
attrs.put("library", library);
// RELEASED, HELD
attrs.put("status", jobq0200.getJobQueueStatus());
attrs.put("activeJob", jobq0200.getActiveJobTotal());
attrs.put("heldJobOnQueue", jobq0200.getHeldJobTotal());
attrs.put("scheduledJobOnQueue", jobq0200.getScheduledJobTotal());
data.getResult().add(attrs);
}
system.disconnectAllServices();
return data;
}
}

View File

@ -0,0 +1,101 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Exception;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDescription;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.ObjectList;
import com.ibm.as400.access.RequestNotSupportedException;
import com.ibm.as400.access.Subsystem;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.check.handler.ISubSystemHandler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public class SubSystemHandler extends AbstractHandler implements ISubSystemHandler {
public SubSystemHandler(final String host, final String login, final String password)
throws AS400SecurityException, IOException {
super(host, login, password);
}
@Override
public void dumpSubSystem(final Subsystem subSystem) throws AS400Exception, AS400SecurityException,
ErrorCompletingRequestException, InterruptedException, IOException, ObjectDoesNotExistException {
System.out.println("getCurrentActiveJobs : " + subSystem.getCurrentActiveJobs());
System.out.println("getDescriptionText : " + subSystem.getDescriptionText());
System.out.println("getDisplayFilePath : " + subSystem.getDisplayFilePath());
System.out.println("getLanguageLibrary : " + subSystem.getLanguageLibrary());
System.out.println("getLibrary : " + subSystem.getLibrary());
System.out.println("getMaximumActiveJobs : " + subSystem.getMaximumActiveJobs());
subSystem.getMonitorJob();
System.out.println("getName : " + subSystem.getName());
System.out.println("getObjectDescription : " + subSystem.getObjectDescription());
System.out.println("getPath : " + subSystem.getPath());
System.out.println("getPools (array count) : " + subSystem.getPools().length);
System.out.println("getStatus : " + subSystem.getStatus());
}
@Override
public ResponseData listSubsystems() throws Exception {
final ResponseData data = new ResponseData();
final AS400 system = this.getNewAs400();
try {
Subsystem[] list = Subsystem.listAllSubsystems(system);
for (int i = 0; i < list.length; i++) {
HashMap<String, Object> attrs = new HashMap<String, Object>();
list[i].refresh();
attrs.put("name", list[i].getName());
attrs.put("path", list[i].getPath());
attrs.put("library", list[i].getLibrary());
// *ACTIVE, *ENDING, *INACTIVE, *RESTRICTED, *STARTING
attrs.put("status", list[i].getStatus());
attrs.put("currentActiveJobs", list[i].getCurrentActiveJobs());
data.getResult().add(attrs);
}
} catch (final Exception e) {
ConnectorLogger.getInstance().error("", e);
try {
system.disconnectAllServices();
} catch (final Exception e1) {
ConnectorLogger.getInstance().debug("", e);
}
throw new Exception(e);
}
system.disconnectAllServices();
return data;
}
}

View File

@ -0,0 +1,221 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import com.ibm.as400.access.AS400Bin4;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.AS400Text;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
import com.ibm.as400.access.QSYSObjectPathName;
import com.ibm.as400.access.SystemPool;
import com.ibm.as400.access.SystemStatus;
import com.centreon.connector.as400.Conf;
import com.centreon.connector.as400.check.handler.ISystemHandler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public class SystemHandler extends AbstractHandler implements ISystemHandler {
private SystemStatus status = null;
public SystemHandler(final String host, final String login, final String password)
throws AS400SecurityException, IOException {
this(host, login, password, null);
}
public SystemHandler(final String host, final String login, final String password, SystemStatus as400Status)
throws AS400SecurityException, IOException {
super(host, login, password);
this.status = as400Status == null ? new SystemStatus(getNewAs400()) : as400Status;
}
@Override
@SuppressWarnings("deprecation")
public void dumpPool(final SystemPool pool) throws UnsupportedEncodingException, AS400SecurityException,
ErrorCompletingRequestException, InterruptedException, IOException, ObjectDoesNotExistException {
System.out.println("------------------------------------");
System.out.println("name : " + pool.getName() + " | " + pool.getDescription());
System.out.println("Identifier : " + pool.getIdentifier());
System.out.println("ActiveToIneligible : " + pool.getActiveToIneligible()
+ " transitions per minute, of transitions of threads from an active condition to an ineligible condition");
System.out.println("ActiveToWait : " + pool.getActiveToWait()
+ " transitions per minute, of transitions of threads from an active condition to a waiting condition");
System.out.println("WaitToIneligible : " + pool.getWaitToIneligible()
+ " transitions per minute, of transitions of threads from a waiting condition to an ineligible condition");
System.out.println("ActivityLevel : " + pool.getActivityLevel()
+ " maximum number of threads that can be active in the pool at any one time");
System.out.println("DatabaseFaults : " + pool.getDatabaseFaults() + " page faults per second");
System.out.println("DatabasePages : " + pool.getDatabasePages() + " page per second");
System.out.println("MaximumActiveThreads : " + pool.getMaximumActiveThreads() + "(deprecated)");
System.out.println("NonDatabaseFaults : " + pool.getNonDatabaseFaults() + " page faults per second");
System.out.println("NonDatabasePages : " + pool.getNonDatabasePages() + " page per second");
System.out.println("PagingOption : " + pool.getPagingOption());
System.out.println("PoolIdentifier : " + pool.getPoolIdentifier() + "(deprecated)");
System.out.println("PoolName : " + pool.getPoolName() + "(deprecated)");
System.out.println("PoolSize : " + pool.getPoolSize() + " (deprecated)");
System.out.println("ReservedSize : " + pool.getReservedSize() + " kilobytes,");
System.out.println("Size : " + pool.getSize() + " kilobytes");
System.out.println("SubsystemLibrary : " + pool.getSubsystemLibrary());
System.out.println("SubsystemName : " + pool.getSubsystemName());
System.out.println("System : " + pool.getSystem());
pool.getActiveToIneligible();
}
@Override
public void dumpSystem() throws AS400SecurityException, ErrorCompletingRequestException, InterruptedException,
IOException, ObjectDoesNotExistException {
System.out.println("ActiveJobsInSystem : " + this.status.getActiveJobsInSystem());
// System.out.println("PercentSystemASPUsed : " +
// status.getPercentSystemASPUsed() + "%"); //<== stockage
// System.out.println("getPercentProcessingUnitUsed : " +
// status.getPercentProcessingUnitUsed() + "%");
System.out.println("ActiveThreadsInSystem : " + this.status.getActiveThreadsInSystem() + "");
System.out.println("BatchJobsEndedWithPrinterOutputWaitingToPrint : "
+ this.status.getBatchJobsEndedWithPrinterOutputWaitingToPrint() + "");
System.out.println("BatchJobsEnding : " + this.status.getBatchJobsEnding() + "");
System.out.println("BatchJobsHeldOnJobQueue : " + this.status.getBatchJobsHeldOnJobQueue() + "");
System.out.println("BatchJobsHeldWhileRunning : " + this.status.getBatchJobsHeldWhileRunning() + "");
System.out.println("BatchJobsOnAHeldJobQueue : " + this.status.getBatchJobsOnAHeldJobQueue() + "");
System.out.println("BatchJobsOnUnassignedJobQueue : " + this.status.getBatchJobsOnUnassignedJobQueue() + "");
System.out.println("BatchJobsRunning : " + this.status.getBatchJobsRunning() + "");
System.out.println("BatchJobsWaitingForMessage : " + this.status.getBatchJobsWaitingForMessage() + "");
System.out.println(
"BatchJobsWaitingToRunOrAlreadyScheduled : " + this.status.getBatchJobsWaitingToRunOrAlreadyScheduled() + "");
System.out.println("CurrentProcessingCapacity : " + this.status.getCurrentProcessingCapacity() + "");
System.out.println("CurrentUnprotectedStorageUsed : " + this.status.getCurrentUnprotectedStorageUsed() + "");
System.out.println("DateAndTimeStatusGathered : " + this.status.getDateAndTimeStatusGathered() + "");
System.out.println("ElapsedTime : " + this.status.getElapsedTime() + "");
System.out.println("JobsInSystem : " + this.status.getJobsInSystem() + "");
System.out.println("MainStorageSize : " + this.status.getMainStorageSize() + "");
System.out.println("MaximumJobsInSystem : " + this.status.getMaximumJobsInSystem() + "");
System.out.println("MaximumUnprotectedStorageUsed : " + this.status.getMaximumUnprotectedStorageUsed() + "");
System.out.println("NumberOfPartitions : " + this.status.getNumberOfPartitions() + "");
System.out.println("NumberOfProcessors : " + this.status.getNumberOfProcessors() + "");
System.out.println("PartitionIdentifier : " + this.status.getPartitionIdentifier() + "");
System.out.println(
"PercentCurrentInteractivePerformance : " + this.status.getPercentCurrentInteractivePerformance() + "");
System.out.println("PercentDBCapability : " + this.status.getPercentDBCapability() + "");
System.out
.println("PercentPermanent256MBSegmentsUsed : " + this.status.getPercentPermanent256MBSegmentsUsed() + "");
System.out.println("PercentPermanent4GBSegmentsUsed : " + this.status.getPercentPermanent4GBSegmentsUsed() + "");
System.out.println("PercentPermanentAddresses : " + this.status.getPercentPermanentAddresses() + "");
System.out.println("PercentProcessingUnitUsed : " + this.status.getPercentProcessingUnitUsed() + "");
System.out.println("PercentSharedProcessorPoolUsed : " + this.status.getPercentSharedProcessorPoolUsed() + "");
System.out.println("PercentSystemASPUsed : " + this.status.getPercentSystemASPUsed() + "");
System.out
.println("PercentTemporary256MBSegmentsUsed : " + this.status.getPercentTemporary256MBSegmentsUsed() + "");
System.out.println("PercentTemporary4GBSegmentsUsed : " + this.status.getPercentTemporary4GBSegmentsUsed() + "");
System.out.println("PercentTemporaryAddresses : " + this.status.getPercentTemporaryAddresses() + "");
System.out.println("PercentUncappedCPUCapacityUsed : " + this.status.getPercentUncappedCPUCapacityUsed() + "");
System.out.println("PoolsNumber : " + this.status.getPoolsNumber() + "");
System.out.println("ProcessorSharingAttribute : " + this.status.getProcessorSharingAttribute() + "");
System.out.println("RestrictedStateFlag : " + this.status.getRestrictedStateFlag() + "");
System.out.println("System : " + this.status.getSystem() + "");
System.out.println("SystemASP : " + this.status.getSystemASP() + " Mbytes");
System.out.println("SystemName : " + this.status.getSystemName() + "");
System.out.println("TotalAuxiliaryStorage : " + this.status.getTotalAuxiliaryStorage() + "");
System.out.println("UsersCurrentSignedOn : " + this.status.getUsersCurrentSignedOn() + "");
System.out.println("UsersSignedOffWithPrinterOutputWaitingToPrint : "
+ this.status.getUsersSignedOffWithPrinterOutputWaitingToPrint() + "");
System.out.println("UsersSuspendedByGroupJobs : " + this.status.getUsersSuspendedByGroupJobs() + "");
System.out.println("UsersSuspendedBySystemRequest : " + this.status.getUsersSuspendedBySystemRequest() + "");
System.out.println("UsersTemporarilySignedOff : " + this.status.getUsersTemporarilySignedOff() + "");
final Enumeration<?> enumeration = this.status.getSystemPools();
while (enumeration.hasMoreElements()) {
this.dumpPool((SystemPool) enumeration.nextElement());
}
}
@Override
public ResponseData getSystem() throws Exception {
final ResponseData data = new ResponseData();
HashMap<String, Object> attrs = new HashMap<String, Object>();
attrs.put("percentProcessingUnitUsed", this.status.getPercentProcessingUnitUsed());
attrs.put("percentSystemASPUsed", this.status.getPercentSystemASPUsed());
attrs.put("maxJobInSystem", this.status.getMaximumJobsInSystem());
attrs.put("jobInSystem", this.status.getJobsInSystem());
attrs.put("activeJobInSystem", this.status.getActiveJobsInSystem());
attrs.put("activeThreadInSystem", this.status.getActiveThreadsInSystem());
attrs.put("batchJobsEndedWithPrinterOutputWaitingToPrint", this.status
.getBatchJobsEndedWithPrinterOutputWaitingToPrint());
attrs.put("batchJobEnding", this.status.getBatchJobsEnding());
attrs.put("batchJobHeldInJobQueue", this.status.getBatchJobsHeldOnJobQueue());
attrs.put("batchJobHeldWhileRunning", this.status.getBatchJobsHeldWhileRunning());
attrs.put("batchJobOnHeldJobQueue", this.status.getBatchJobsOnAHeldJobQueue());
attrs.put("batchJobOnUnassignedJobQueue", this.status.getBatchJobsOnUnassignedJobQueue());
attrs.put("batchJobRunning", this.status.getBatchJobsRunning());
attrs.put("batchJobWaitingForMessage", this.status.getBatchJobsWaitingForMessage());
attrs.put("batchJobWaitingToRunOrAlreadyScheduled", this.status.getBatchJobsWaitingToRunOrAlreadyScheduled());
data.getResult().add(attrs);
return data;
}
@Override
@SuppressWarnings("unchecked")
public ResponseData getPageFault() throws Exception {
final ResponseData data = new ResponseData();
for (final Enumeration<SystemPool> enumeration = this.status.getSystemPools(); enumeration.hasMoreElements();) {
final SystemPool pool = enumeration.nextElement();
HashMap<String, Object> attrs = new HashMap<String, Object>();
attrs.put("id", pool.getIdentifier());
attrs.put("name", pool.getPoolName());
attrs.put("dbPageFault", pool.getDatabaseFaults());
attrs.put("dbPage", pool.getDatabasePages());
attrs.put("nonDbPageFault", pool.getNonDatabaseFaults());
attrs.put("nonDbPage",pool.getNonDatabasePages());
data.getResult().add(attrs);
}
return data;
}
@SuppressWarnings("unchecked")
public SystemPool searchSystemPoolByName(final String poolName) throws AS400SecurityException,
ErrorCompletingRequestException, InterruptedException, IOException, ObjectDoesNotExistException {
for (final Enumeration<SystemPool> enumeration = this.status.getSystemPools(); enumeration.hasMoreElements();) {
final SystemPool pool = enumeration.nextElement();
System.out.println("poolName : " + pool.getName());
if (poolName.equalsIgnoreCase(pool.getName())) {
return pool;
}
}
return null;
}
}

View File

@ -0,0 +1,108 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.disk;
import java.io.IOException;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Exception;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.AS400Text;
import com.ibm.as400.access.BinaryConverter;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
/**
* @author Lamotte Jean-Baptiste
*/
public class DiskInfo {
AS400 system = null;
private static final ProgramParameter ERROR_CODE = new ProgramParameter(new byte[8]);
byte[][] receiverVariables_ = new byte[4][];
public DiskInfo(final AS400 system) {
this.system = system;
}
public void load() throws AS400SecurityException, ErrorCompletingRequestException, InterruptedException, IOException,
ObjectDoesNotExistException {
this.load(1);
}
// Retrieve Disk Information (QYASRDI) API
public void load(int format) throws AS400SecurityException, ErrorCompletingRequestException, InterruptedException,
IOException, ObjectDoesNotExistException {
// Check to see if the format has been loaded already.
if (this.receiverVariables_[format] != null) {
return;
}
if (format == 0) {
format = 1;
}
final int receiverVariableLength = format == 1 ? 80 : format == 2 ? 148 : 2048;
final AS400Text param3 = new AS400Text(8, this.system);
// AS400Array param4 = new AS400Array(param3., system);
final ProgramParameter[] parameters = new ProgramParameter[] {
// 1 Receiver variable Output Char(*)
new ProgramParameter(receiverVariableLength),
// 2 Length of receiver variable Input Binary(4)
new ProgramParameter(BinaryConverter.intToByteArray(receiverVariableLength)),
// 3 Format name Input Char(8)
new ProgramParameter(param3.toBytes("DMIN0100")),
// 4 Disk unit resource name array Input Array of CHAR(10)
new ProgramParameter(("*ALL ").getBytes("ASCII")),
// 5 Number of disk unit resource names Input Binary(4)
new ProgramParameter(BinaryConverter.intToByteArray(1)), DiskInfo.// 6
// Error
// code
// I/O
// Char(*)
ERROR_CODE };
final ProgramCall pc = new ProgramCall(this.system, "/QSYS.LIB/QYASRDI.PGM", parameters);
// QWCRSSTS is not thread safe.
boolean repeatRun;
do {
repeatRun = false;
if (!pc.run()) {
throw new AS400Exception(pc.getMessageList());
}
this.receiverVariables_[format] = parameters[0].getOutputData();
final int bytesAvailable = BinaryConverter.byteArrayToInt(this.receiverVariables_[format], 0);
final int bytesReturned = BinaryConverter.byteArrayToInt(this.receiverVariables_[format], 4);
if (bytesReturned < bytesAvailable) {
repeatRun = true;
parameters[0] = new ProgramParameter(bytesAvailable);
parameters[1] = new ProgramParameter(BinaryConverter.intToByteArray(bytesAvailable));
}
} while (repeatRun);
this.receiverVariables_[0] = this.receiverVariables_[format];
}
}

View File

@ -0,0 +1,109 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.disk;
import java.io.IOException;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Exception;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.AS400Text;
import com.ibm.as400.access.BinaryConverter;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
/**
* @author Lamotte Jean-Baptiste
*/
public class DiskManagement {
AS400 system = null;
DiskManagementSession session = null;
private static final ProgramParameter ERROR_CODE = new ProgramParameter(new byte[8]);
byte[][] receiverVariables_ = new byte[4][];
public DiskManagement(final AS400 system) {
this.system = system;
this.session = new DiskManagementSession(system);
}
public void load() throws AS400SecurityException, ErrorCompletingRequestException, InterruptedException, IOException,
ObjectDoesNotExistException {
this.load(1);
}
// Retrieve Disk Information (QYASRDI) API
public void load(int format) throws AS400SecurityException, ErrorCompletingRequestException, InterruptedException,
IOException, ObjectDoesNotExistException {
this.session.load();
// Check to see if the format has been loaded already.
if (this.receiverVariables_[format] != null) {
return;
}
if (format == 0) {
format = 1;
}
final int receiverVariableLength = format == 1 ? 80 : format == 2 ? 148 : 2048;
final AS400Text param3 = new AS400Text(8, this.system);
// AS400Array param4 = new AS400Array(param3., system);
final ProgramParameter[] parameters = new ProgramParameter[] {
// 1 Receiver variable Output Char(*)
new ProgramParameter(receiverVariableLength),
// 2 Length of receiver variable Input Binary(4)
new ProgramParameter(BinaryConverter.intToByteArray(receiverVariableLength)),
// 3 Format name Input Char(8)
new ProgramParameter(param3.toBytes("DMIN0100")),
// 4 Session handle Input Char(8)
new ProgramParameter(this.session.getHandle()), DiskManagement.// 5
// Error
// code
// I/O
// Char(*)a
ERROR_CODE };
final ProgramCall pc = new ProgramCall(this.system, "/QSYS.LIB/QYASRDI.PGM", parameters);
// QWCRSSTS is not thread safe.
boolean repeatRun;
do {
repeatRun = false;
if (!pc.run()) {
throw new AS400Exception(pc.getMessageList());
}
this.receiverVariables_[format] = parameters[0].getOutputData();
final int bytesAvailable = BinaryConverter.byteArrayToInt(this.receiverVariables_[format], 0);
final int bytesReturned = BinaryConverter.byteArrayToInt(this.receiverVariables_[format], 4);
if (bytesReturned < bytesAvailable) {
repeatRun = true;
parameters[0] = new ProgramParameter(bytesAvailable);
parameters[1] = new ProgramParameter(BinaryConverter.intToByteArray(bytesAvailable));
}
} while (repeatRun);
this.receiverVariables_[0] = this.receiverVariables_[format];
}
}

View File

@ -0,0 +1,64 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.disk;
import java.io.IOException;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
/**
* @author Lamotte Jean-Baptiste
*/
public class DiskManagementSession {
AS400 system = null;
byte[] session;
private static final ProgramParameter ERROR_CODE = new ProgramParameter(new byte[8]);
public DiskManagementSession(final AS400 system) {
this.system = system;
}
public byte[] getHandle() {
return this.session;
}
// Retrieve Disk Information (QYASRDI) API
public void load() throws AS400SecurityException, ErrorCompletingRequestException, InterruptedException, IOException,
ObjectDoesNotExistException {
final ProgramParameter[] parameters = new ProgramParameter[] {
// 1 Session handle Output Char(8)
new ProgramParameter(8), DiskManagementSession.// 2 Error code
// I/O Char(*)
ERROR_CODE };
new ProgramCall(this.system, "/QSYS.LIB/QYASSDMS.PGM", parameters);
this.session = parameters[0].getOutputData();
}
}

View File

@ -0,0 +1,136 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.disk;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.data.PcmlException;
import com.ibm.as400.data.ProgramCallDocument;
/**
* @author Lamotte Jean-Baptiste
*/
public class QyaspolYasp0100PcmlHandler {
AS400 system = null;
ProgramCallDocument pcml; // com.ibm.as400.data.ProgramCallDocument
HashMap<String, Yasp0100Data> disks = new HashMap<String, Yasp0100Data>();
long lastLoad = 0;
int totalRecord = -1;
int rcdsReturned = -1;
byte[] rqsHandle = null;
public QyaspolYasp0100PcmlHandler(final AS400 system) {
this.system = system;
}
public void addYasp0100Data(final Yasp0100Data data) {
this.disks.put(data.getResourceName(), data);
}
public boolean callProgram(final String programName) throws PcmlException {
// Request to call the API
final boolean rc = this.pcml.callProgram(programName);
if (rc == false) {
this.displayMessageError(this.pcml, programName);
return false;
}
return true;
}
public void displayMessageError(final ProgramCallDocument pcml, final String programmName) throws PcmlException {
// Retrieve list of server messages
final AS400Message[] msgs = pcml.getMessageList(programmName);
// Iterate through messages and write them to standard output
for (final AS400Message msg : msgs) {
final String msgId = msg.getID();
final String msgText = msg.getText();
System.out.println(" " + msgId + " - " + msgText);
}
}
public Yasp0100Data getDiskByResourceName(final String name) {
return this.disks.get(name);
}
public List<Yasp0100Data> getDisksList() {
final List<Yasp0100Data> list = new LinkedList<Yasp0100Data>();
list.addAll(this.disks.values());
return list;
}
public List<String> getResourceNameList() {
final LinkedList<String> list = new LinkedList<String>();
list.addAll(this.disks.keySet());
return list;
}
public synchronized void load() throws PcmlException {
if (System.currentTimeMillis() < (this.lastLoad + (10 * 1000))) {
return;
}
this.lastLoad = System.currentTimeMillis();
this.pcml = new ProgramCallDocument(this.system, "com.centreon.connector.as400.box.system.disk.qyaspol100.pcml");
this.callProgram("qyaspol");
this.loadListInfo("qyaspol");
this.addYasp0100Data(this.loadYasp0100(this.pcml, "qyaspol"));
if (this.totalRecord > 1) {
for (int i = 1; i <= this.totalRecord; i++) {
this.pcml.setValue("qgygtle.requestHandle", this.rqsHandle);
this.pcml.setIntValue("qgygtle.startingRcd", i);
this.callProgram("qgygtle");
this.addYasp0100Data(this.loadYasp0100(this.pcml, "qgygtle"));
}
}
this.pcml.setValue("qgyclst.requestHandle", this.rqsHandle);
this.callProgram("qgyclst");
}
public void loadListInfo(final String programName) throws PcmlException {
this.totalRecord = this.pcml.getIntValue(programName + ".listInfo.totalRcds");
this.rcdsReturned = this.pcml.getIntValue(programName + ".listInfo.rcdsReturned");
this.rqsHandle = (byte[]) this.pcml.getValue(programName + ".listInfo.rqsHandle");
}
public Yasp0100Data loadYasp0100(final ProgramCallDocument pcml, final String programName) throws PcmlException {
final int[] indices = new int[1];
indices[0] = 0;
final Yasp0100Data data = new Yasp0100Data();
data.setResourceName(pcml.getStringValue(programName + ".receiver.resourceName", indices));
return data;
}
}

View File

@ -0,0 +1,259 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.disk;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ConnectionEvent;
import com.ibm.as400.access.ConnectionListener;
import com.ibm.as400.access.SocketProperties;
import com.ibm.as400.data.PcmlException;
import com.ibm.as400.data.ProgramCallDocument;
import com.centreon.connector.as400.Conf;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.check.handler.impl.FailedCheckException;
/**
* @author Lamotte Jean-Baptiste
*/
public class QyaspolYasp0300PcmlHandler {
String pcmlFile = "qyaspol300.pcml";
// AS400 system = null;
ProgramCallDocument pcml; // com.ibm.as400.data.ProgramCallDocument
HashMap<String, Yasp0300Data> currentDiskLoad = new HashMap<String, Yasp0300Data>();
HashMap<String, Yasp0300Data> cachedDiskList = null;
Exception lastFailException = new Exception("First check");
long lastLoad = 0;
int totalRecord = -1;
int rcdsReturned = -1;
byte[] rqsHandle = null;
String host = null;
String login = null;
String password = null;
public QyaspolYasp0300PcmlHandler(final String host, final String login, final String password) {
this.host = host;
this.login = login;
this.password = password;
}
public void addYasp0300Data(final Yasp0300Data data) {
this.currentDiskLoad.put(data.getResourceName(), data);
}
public boolean callProgram(final String programName) throws PcmlException {
// Request to call the API
final boolean rc = this.pcml.callProgram(programName);
if (rc == false) {
this.displayMessageError(this.pcml, programName);
return false;
}
return true;
}
public void displayMessageError(final ProgramCallDocument pcml, final String programmName) throws PcmlException {
// Retrieve list of server messages
final AS400Message[] msgs = pcml.getMessageList(programmName);
// Iterate through messages and write them to standard output
for (final AS400Message msg : msgs) {
final String msgId = msg.getID();
final String msgText = msg.getText();
System.out.println(" " + msgId + " - " + msgText);
}
}
public Yasp0300Data getDiskByResourceName(final String name) throws Exception {
this.load();
if (this.cachedDiskList == null) {
throw this.lastFailException;
}
return this.cachedDiskList.get(name);
}
public List<Yasp0300Data> getDisksList() throws Exception {
this.load();
if (this.cachedDiskList == null) {
throw this.lastFailException;
}
final List<Yasp0300Data> list = new LinkedList<Yasp0300Data>();
list.addAll(this.cachedDiskList.values());
return list;
}
public List<String> getResourceNameList() throws Exception {
this.load();
if (this.cachedDiskList == null) {
throw this.lastFailException;
}
final LinkedList<String> list = new LinkedList<String>();
list.addAll(this.cachedDiskList.keySet());
return list;
}
public void load() throws PcmlException {
if (!((this.lastLoad + Conf.cacheTimeout) < System.currentTimeMillis())) {
return;
}
AS400 system = null;
try {
this.currentDiskLoad = new HashMap<String, Yasp0300Data>();
system = this.getNewAs400();
this.pcml = new ProgramCallDocument(system, this.pcmlFile);
this.callProgram("qyaspol");
this.loadListInfo("qyaspol");
this.addYasp0300Data(this.loadYasp0300(this.pcml, "qyaspol"));
if (this.totalRecord > 1) {
for (int i = 1; i <= this.totalRecord; i++) {
this.pcml.setValue("qgygtle.requestHandle", this.rqsHandle);
this.pcml.setIntValue("qgygtle.startingRcd", i);
this.callProgram("qgygtle");
this.addYasp0300Data(this.loadYasp0300(this.pcml, "qgygtle"));
}
}
this.pcml.setValue("qgyclst.requestHandle", this.rqsHandle);
this.callProgram("qgyclst");
this.cachedDiskList = this.currentDiskLoad;
this.lastLoad = System.currentTimeMillis();
} catch (final com.ibm.as400.data.PcmlException e) {
if (e.getCause() != null) {
new FailedCheckException("" + e.getCause().getMessage());
} else {
new FailedCheckException("" + e.getMessage());
}
this.cachedDiskList = null;
ConnectorLogger.getInstance().debug("", e);
} catch (final java.net.UnknownHostException e) {
this.lastFailException = new FailedCheckException("Invalid hostname for server: " + e.getMessage());
this.cachedDiskList = null;
ConnectorLogger.getInstance().debug("", e);
} catch (final Exception e) {
System.out.println("plop " + e.getMessage());
this.lastFailException = new FailedCheckException("" + e.getMessage());
this.cachedDiskList = null;
ConnectorLogger.getInstance().debug("", e);
} finally {
this.lastLoad = System.currentTimeMillis();
if (system != null) {
system.disconnectAllServices();
}
}
}
public void loadListInfo(final String programName) throws PcmlException {
this.totalRecord = this.pcml.getIntValue(programName + ".listInfo.totalRcds");
this.rcdsReturned = this.pcml.getIntValue(programName + ".listInfo.rcdsReturned");
this.rqsHandle = (byte[]) this.pcml.getValue(programName + ".listInfo.rqsHandle");
}
public Yasp0300Data loadYasp0300(final ProgramCallDocument pcml, final String programName) throws PcmlException {
final int[] indices = new int[1];
indices[0] = 0;
final Yasp0300Data data = new Yasp0300Data();
data.setAspNumber(pcml.getIntValue(programName + ".receiver.aspNumber", indices));
data.setDiskType(pcml.getStringValue(programName + ".receiver.diskType", indices));
data.setDiskModel(pcml.getStringValue(programName + ".receiver.diskModel", indices));
data.setDiskSerialNumber(pcml.getStringValue(programName + ".receiver.diskSerialNumber", indices));
data.setResourceName(pcml.getStringValue(programName + ".receiver.resourceName", indices));
data.setDiskUnitNumber(pcml.getIntValue(programName + ".receiver.diskUnitNumber", indices));
data.setDiskCapacity(pcml.getIntValue(programName + ".receiver.diskCapacity", indices));
data.setDiskStorageAvailable(pcml.getIntValue(programName + ".receiver.diskStorageAvailable", indices));
data.setDiskStorageReservedForSystem(
pcml.getIntValue(programName + ".receiver.diskStorageReservedForSystem", indices));
data.setMirroredUnitProtected(pcml.getStringValue(programName + ".receiver.mirroredUnitProtected", indices));
data.setMirroredUnitReported(pcml.getStringValue(programName + ".receiver.mirroredUnitReported", indices));
data.setMirroredUnitStatus(pcml.getStringValue(programName + ".receiver.mirroredUnitStatus", indices));
data.setReserved(pcml.getStringValue(programName + ".receiver.reserved", indices));
data.setUnitControl(pcml.getIntValue(programName + ".receiver.unitControl", indices));
data.setBlockTransferredToMainStorage(
pcml.getIntValue(programName + ".receiver.blockTransferredToMainStorage", indices));
data.setBlockTransferredFromMainStorage(
pcml.getIntValue(programName + ".receiver.blockTransferredFromMainStorage", indices));
data.setRequestForDataToMainStorage(
pcml.getIntValue(programName + ".receiver.requestForDataToMainStorage", indices));
data.setRequestForDataForMainStorage(
pcml.getIntValue(programName + ".receiver.requestForDataForMainStorage", indices));
data.setRequestForPermanentFromMainStorage(
pcml.getIntValue(programName + ".receiver.requestForPermanentFromMainStorage", indices));
data.setSampleCount(pcml.getIntValue(programName + ".receiver.sampleCount", indices));
data.setNotBusyCount(pcml.getIntValue(programName + ".receiver.notBusyCount", indices));
data.setCompressionStatus(pcml.getStringValue(programName + ".receiver.compressionStatus", indices));
data.setDiskProtectionType(pcml.getStringValue(programName + ".receiver.diskProtectionType", indices));
data.setCompressedUnit(pcml.getStringValue(programName + ".receiver.compressedUnit", indices));
data.setStorageAllocationRestrictedUnit(
pcml.getStringValue(programName + ".receiver.storageAllocationRestrictedUnit", indices));
data.setAvailabilityParitySetUnit(
pcml.getStringValue(programName + ".receiver.availabilityParitySetUnit", indices));
data.setMultipleConnectionUnit(pcml.getStringValue(programName + ".receiver.multipleConnectionUnit", indices));
return data;
}
protected AS400 getNewAs400() throws AS400SecurityException, IOException {
final SocketProperties properties = new SocketProperties();
properties.setSoLinger(1);
properties.setKeepAlive(false);
properties.setTcpNoDelay(true);
properties.setLoginTimeout(Conf.as400LoginTimeout);
properties.setSoTimeout(Conf.as400ReadTimeout);
final AS400 system = new AS400(this.host, this.login, this.password);
system.setSocketProperties(properties);
system.addConnectionListener(new ConnectionListener() {
@Override
public void connected(final ConnectionEvent event) {
ConnectorLogger.getInstance().getLogger().debug("Connect event service : " + event.getService());
}
@Override
public void disconnected(final ConnectionEvent event) {
ConnectorLogger.getInstance().getLogger().debug("Disconnect event service : " + event.getService());
}
});
system.validateSignon();
return system;
}
}

View File

@ -0,0 +1,46 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.disk;
/**
* @author Lamotte Jean-Baptiste
*/
class Yasp0100Data {
private int aspNumber;
String resourceName;
public int getAspNumber() {
return this.aspNumber;
}
public String getResourceName() {
return this.resourceName;
}
public void setAspNumber(final int aspNumber) {
this.aspNumber = aspNumber;
}
public void setResourceName(final String resourceName) {
this.resourceName = resourceName;
}
}

View File

@ -0,0 +1,317 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.disk;
/**
* @author Lamotte Jean-Baptiste
*/
public class Yasp0300Data {
private int aspNumber;
private String diskType;
private String diskModel;
private String diskSerialNumber;
private String resourceName;
private int diskUnitNumber;
private int diskCapacity;
private int diskStorageAvailable;
private int diskStorageReservedForSystem;
private String mirroredUnitProtected;
private String mirroredUnitReported;
private String mirroredUnitStatus;
private String reserved;
private int unitControl;
private int blockTransferredToMainStorage;
private int blockTransferredFromMainStorage;
private int requestForDataToMainStorage;
private int requestForDataForMainStorage;
private int requestForPermanentFromMainStorage;
private int sampleCount;
private int notBusyCount;
private String compressionStatus;
private String diskProtectionType;
private String compressedUnit;
private String storageAllocationRestrictedUnit;
private String availabilityParitySetUnit;
private String multipleConnectionUnit;
public int getAspNumber() {
return this.aspNumber;
}
public String getAvailabilityParitySetUnit() {
return this.availabilityParitySetUnit;
}
public int getBlockTransferredFromMainStorage() {
return this.blockTransferredFromMainStorage;
}
public int getBlockTransferredToMainStorage() {
return this.blockTransferredToMainStorage;
}
public String getCompressedUnit() {
return this.compressedUnit;
}
public String getCompressionStatus() {
return this.compressionStatus;
}
public int getDiskCapacity() {
return this.diskCapacity;
}
public String getDiskModel() {
return this.diskModel;
}
public String getDiskProtectionType() {
return this.diskProtectionType;
}
public String getDiskSerialNumber() {
return this.diskSerialNumber;
}
public int getDiskStorageAvailable() {
return this.diskStorageAvailable;
}
public int getDiskStorageReservedForSystem() {
return this.diskStorageReservedForSystem;
}
public String getDiskType() {
return this.diskType;
}
public int getDiskUnitNumber() {
return this.diskUnitNumber;
}
public String getMirroredUnitProtected() {
return this.mirroredUnitProtected;
}
public String getMirroredUnitReported() {
return this.mirroredUnitReported;
}
public String getMirroredUnitStatus() {
return this.mirroredUnitStatus;
}
public String getMultipleConnectionUnit() {
return this.multipleConnectionUnit;
}
public int getNotBusyCount() {
return this.notBusyCount;
}
public int getRequestForDataForMainStorage() {
return this.requestForDataForMainStorage;
}
public int getRequestForDataToMainStorage() {
return this.requestForDataToMainStorage;
}
public int getRequestForPermanentFromMainStorage() {
return this.requestForPermanentFromMainStorage;
}
public String getReserved() {
return this.reserved;
}
public String getResourceName() {
return this.resourceName;
}
public int getSampleCount() {
return this.sampleCount;
}
public String getStorageAllocationRestrictedUnit() {
return this.storageAllocationRestrictedUnit;
}
public int getUnitControl() {
return this.unitControl;
}
public String getUnitControlString() {
/*
* 0 There is no unit control value. 1 The disk unit is active. 2 The disk unit
* has failed. 3 Some other disk unit in the disk subsystem has failed. 4 There
* is a hardware failure within the disk subsystem that affects performance, but
* does not affect the function of the disk unit. 5 There is a hardware failure
* within the disk subsystem that does not affect the function or performance of
* the disk unit. 6 The disk unit's parity protection is being rebuilt. 7 The
* disk unit is not ready. 8 The disk unit is write protected. 9 The disk unit
* is busy. 10 The disk unit is not operational. 11 The disk unit has returned a
* status that is not recognizable by the system. 12 The disk unit cannot be
* accessed. 13 The disk unit is read/write protected.
*/
if (this.getUnitControl() == 0) {
return "There is no unit control value";
} else if (this.getUnitControl() == 1) {
return "The disk unit is active";
} else if (this.getUnitControl() == 2) {
return "The disk unit has failed";
} else if (this.getUnitControl() == 3) {
return "Some other disk unit in the disk subsystem has failed";
} else if (this.getUnitControl() == 4) {
return "There is a hardware failure within the disk subsystem that affects performance, but does not affect the function of the disk unit";
} else if (this.getUnitControl() == 5) {
return "There is a hardware failure within the disk subsystem that does not affect the function or performance of the disk unit";
} else if (this.getUnitControl() == 6) {
return "The disk unit's parity protection is being rebuilt";
} else if (this.getUnitControl() == 7) {
return "The disk unit is not ready";
} else if (this.getUnitControl() == 8) {
return "The disk unit is write protected";
} else if (this.getUnitControl() == 9) {
return "The disk unit is busy";
} else if (this.getUnitControl() == 10) {
return "The disk unit is not operational";
} else if (this.getUnitControl() == 11) {
return "The disk unit has returned a status that is not recognizable by the system";
} else if (this.getUnitControl() == 12) {
return "The disk unit cannot be accessed";
} else if (this.getUnitControl() == 13) {
return "The disk unit is read/write protected";
} else {
return "state unknown (" + this.getUnitControl() + ")";
}
}
public void setAspNumber(final int aspNumber) {
this.aspNumber = aspNumber;
}
public void setAvailabilityParitySetUnit(final String availabilityParitySetUnit) {
this.availabilityParitySetUnit = availabilityParitySetUnit;
}
public void setBlockTransferredFromMainStorage(final int blockTransferredFromMainStorage) {
this.blockTransferredFromMainStorage = blockTransferredFromMainStorage;
}
public void setBlockTransferredToMainStorage(final int blockTransferredToMainStorage) {
this.blockTransferredToMainStorage = blockTransferredToMainStorage;
}
public void setCompressedUnit(final String compressedUnit) {
this.compressedUnit = compressedUnit;
}
public void setCompressionStatus(final String compressionStatus) {
this.compressionStatus = compressionStatus;
}
public void setDiskCapacity(final int diskCapacity) {
this.diskCapacity = diskCapacity;
}
public void setDiskModel(final String diskModel) {
this.diskModel = diskModel;
}
public void setDiskProtectionType(final String diskProtectionType) {
this.diskProtectionType = diskProtectionType;
}
public void setDiskSerialNumber(final String diskSerialNumber) {
this.diskSerialNumber = diskSerialNumber;
}
public void setDiskStorageAvailable(final int diskStorageAvailable) {
this.diskStorageAvailable = diskStorageAvailable;
}
public void setDiskStorageReservedForSystem(final int diskStorageReservedForSystem) {
this.diskStorageReservedForSystem = diskStorageReservedForSystem;
}
public void setDiskType(final String diskType) {
this.diskType = diskType;
}
public void setDiskUnitNumber(final int diskUnitNumber) {
this.diskUnitNumber = diskUnitNumber;
}
public void setMirroredUnitProtected(final String mirroredUnitProtected) {
this.mirroredUnitProtected = mirroredUnitProtected;
}
public void setMirroredUnitReported(final String mirroredUnitReported) {
this.mirroredUnitReported = mirroredUnitReported;
}
public void setMirroredUnitStatus(final String mirroredUnitStatus) {
this.mirroredUnitStatus = mirroredUnitStatus;
}
public void setMultipleConnectionUnit(final String multipleConnectionUnit) {
this.multipleConnectionUnit = multipleConnectionUnit;
}
public void setNotBusyCount(final int notBusyCount) {
this.notBusyCount = notBusyCount;
}
public void setRequestForDataForMainStorage(final int requestForDataForMainStorage) {
this.requestForDataForMainStorage = requestForDataForMainStorage;
}
public void setRequestForDataToMainStorage(final int requestForDataToMainStorage) {
this.requestForDataToMainStorage = requestForDataToMainStorage;
}
public void setRequestForPermanentFromMainStorage(final int requestForPermanentFromMainStorage) {
this.requestForPermanentFromMainStorage = requestForPermanentFromMainStorage;
}
public void setReserved(final String reserved) {
this.reserved = reserved;
}
public void setResourceName(final String resourceName) {
this.resourceName = resourceName;
}
public void setSampleCount(final int sampleCount) {
this.sampleCount = sampleCount;
}
public void setStorageAllocationRestrictedUnit(final String storageAllocationRestrictedUnit) {
this.storageAllocationRestrictedUnit = storageAllocationRestrictedUnit;
}
public void setUnitControl(final int unitControl) {
this.unitControl = unitControl;
}
}

View File

@ -0,0 +1,153 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.jobqueue;
/**
* @author Lamotte Jean-Baptiste
*/
public class Jobq0100 {
private int bytesReturned;
private int bytesAvailable;
private String jobqName;
private String jobqLibName;
private String operatorControlled;
private String authorityCheck;
private int numberOfJob;
private String jobQueueStatus;
private String subSystemName;
private String textDescription;
private String subSystemLibName;
private int sequenceNumber;
private int maximumActive;
private int currentActive;
public int getBytesReturned() {
return this.bytesReturned;
}
public void setBytesReturned(final int bytesReturned) {
this.bytesReturned = bytesReturned;
}
public int getBytesAvailable() {
return this.bytesAvailable;
}
public void setBytesAvailable(final int bytesAvailable) {
this.bytesAvailable = bytesAvailable;
}
public String getJobqName() {
return this.jobqName;
}
public void setJobqName(final String jobqName) {
this.jobqName = jobqName;
}
public String getJobqLibName() {
return this.jobqLibName;
}
public void setJobqLibName(final String jobqLibName) {
this.jobqLibName = jobqLibName;
}
public String getOperatorControlled() {
return this.operatorControlled;
}
public void setOperatorControlled(final String operatorControlled) {
this.operatorControlled = operatorControlled;
}
public String getAuthorityCheck() {
return this.authorityCheck;
}
public void setAuthorityCheck(final String authorityCheck) {
this.authorityCheck = authorityCheck;
}
public int getNumberOfJob() {
return this.numberOfJob;
}
public void setNumberOfJob(final int numberOfJob) {
this.numberOfJob = numberOfJob;
}
public String getJobQueueStatus() {
return this.jobQueueStatus;
}
public void setJobQueueStatus(final String jobQueueStatus) {
this.jobQueueStatus = jobQueueStatus;
}
public String getSubSystemName() {
return this.subSystemName;
}
public void setSubSystemName(final String subSystemName) {
this.subSystemName = subSystemName;
}
public String getTextDescription() {
return this.textDescription;
}
public void setTextDescription(final String textDescription) {
this.textDescription = textDescription;
}
public String getSubSystemLibName() {
return this.subSystemLibName;
}
public void setSubSystemLibName(final String subSystemLibName) {
this.subSystemLibName = subSystemLibName;
}
public int getSequenceNumber() {
return this.sequenceNumber;
}
public void setSequenceNumber(final int sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
public int getMaximumActive() {
return this.maximumActive;
}
public void setMaximumActive(final int maximumActive) {
this.maximumActive = maximumActive;
}
public int getCurrentActive() {
return this.currentActive;
}
public void setCurrentActive(final int currentActive) {
this.currentActive = currentActive;
}
}

View File

@ -0,0 +1,403 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.jobqueue;
/**
* @author Lamotte Jean-Baptiste
*/
public class Jobq0200 extends Jobq0100 {
private int maxActiveJobPriority1;
private int maxActiveJobPriority2;
private int maxActiveJobPriority3;
private int maxActiveJobPriority4;
private int maxActiveJobPriority5;
private int maxActiveJobPriority6;
private int maxActiveJobPriority7;
private int maxActiveJobPriority8;
private int maxActiveJobPriority9;
private int activeJobPriority0;
private int activeJobPriority1;
private int activeJobPriority2;
private int activeJobPriority3;
private int activeJobPriority4;
private int activeJobPriority5;
private int activeJobPriority6;
private int activeJobPriority7;
private int activeJobPriority8;
private int activeJobPriority9;
private int scheduledJobOnQueuePriority0;
private int scheduledJobOnQueuePriority1;
private int scheduledJobOnQueuePriority2;
private int scheduledJobOnQueuePriority3;
private int scheduledJobOnQueuePriority4;
private int scheduledJobOnQueuePriority5;
private int scheduledJobOnQueuePriority6;
private int scheduledJobOnQueuePriority7;
private int scheduledJobOnQueuePriority8;
private int scheduledJobOnQueuePriority9;
private int heldJobOnQueuePriority0;
private int heldJobOnQueuePriority1;
private int heldJobOnQueuePriority2;
private int heldJobOnQueuePriority3;
private int heldJobOnQueuePriority4;
private int heldJobOnQueuePriority5;
private int heldJobOnQueuePriority6;
private int heldJobOnQueuePriority7;
private int heldJobOnQueuePriority8;
private int heldJobOnQueuePriority9;
public int getActiveJobTotal() {
return this.activeJobPriority0 + this.activeJobPriority1 + this.activeJobPriority2 + this.activeJobPriority3
+ this.activeJobPriority4 + this.activeJobPriority5 + this.activeJobPriority6 + this.activeJobPriority7
+ this.activeJobPriority8 + this.activeJobPriority9;
}
public int getScheduledJobTotal() {
return this.scheduledJobOnQueuePriority0 + this.scheduledJobOnQueuePriority1 + this.scheduledJobOnQueuePriority2
+ this.scheduledJobOnQueuePriority3 + this.scheduledJobOnQueuePriority4 + this.scheduledJobOnQueuePriority5
+ this.scheduledJobOnQueuePriority6 + this.scheduledJobOnQueuePriority7 + this.scheduledJobOnQueuePriority8
+ this.scheduledJobOnQueuePriority9;
}
public int getHeldJobTotal() {
return this.heldJobOnQueuePriority0 + this.heldJobOnQueuePriority1 + this.heldJobOnQueuePriority2
+ this.heldJobOnQueuePriority3 + this.heldJobOnQueuePriority4 + this.heldJobOnQueuePriority5
+ this.heldJobOnQueuePriority6 + this.heldJobOnQueuePriority7 + this.heldJobOnQueuePriority8
+ this.heldJobOnQueuePriority9;
}
public int getMaxActiveJobPriority1() {
return this.maxActiveJobPriority1;
}
public void setMaxActiveJobPriority1(final int maxActiveJobPriority1) {
this.maxActiveJobPriority1 = maxActiveJobPriority1;
}
public int getMaxActiveJobPriority2() {
return this.maxActiveJobPriority2;
}
public void setMaxActiveJobPriority2(final int maxActiveJobPriority2) {
this.maxActiveJobPriority2 = maxActiveJobPriority2;
}
public int getMaxActiveJobPriority3() {
return this.maxActiveJobPriority3;
}
public void setMaxActiveJobPriority3(final int maxActiveJobPriority3) {
this.maxActiveJobPriority3 = maxActiveJobPriority3;
}
public int getMaxActiveJobPriority4() {
return this.maxActiveJobPriority4;
}
public void setMaxActiveJobPriority4(final int maxActiveJobPriority4) {
this.maxActiveJobPriority4 = maxActiveJobPriority4;
}
public int getMaxActiveJobPriority5() {
return this.maxActiveJobPriority5;
}
public void setMaxActiveJobPriority5(final int maxActiveJobPriority5) {
this.maxActiveJobPriority5 = maxActiveJobPriority5;
}
public int getMaxActiveJobPriority6() {
return this.maxActiveJobPriority6;
}
public void setMaxActiveJobPriority6(final int maxActiveJobPriority6) {
this.maxActiveJobPriority6 = maxActiveJobPriority6;
}
public int getMaxActiveJobPriority7() {
return this.maxActiveJobPriority7;
}
public void setMaxActiveJobPriority7(final int maxActiveJobPriority7) {
this.maxActiveJobPriority7 = maxActiveJobPriority7;
}
public int getMaxActiveJobPriority8() {
return this.maxActiveJobPriority8;
}
public void setMaxActiveJobPriority8(final int maxActiveJobPriority8) {
this.maxActiveJobPriority8 = maxActiveJobPriority8;
}
public int getMaxActiveJobPriority9() {
return this.maxActiveJobPriority9;
}
public void setMaxActiveJobPriority9(final int maxActiveJobPriority9) {
this.maxActiveJobPriority9 = maxActiveJobPriority9;
}
public int getActiveJobPriority1() {
return this.activeJobPriority1;
}
public void setActiveJobPriority1(final int activeJobPriority1) {
this.activeJobPriority1 = activeJobPriority1;
}
public int getActiveJobPriority2() {
return this.activeJobPriority2;
}
public void setActiveJobPriority2(final int activeJobPriority2) {
this.activeJobPriority2 = activeJobPriority2;
}
public int getActiveJobPriority3() {
return this.activeJobPriority3;
}
public void setActiveJobPriority3(final int activeJobPriority3) {
this.activeJobPriority3 = activeJobPriority3;
}
public int getActiveJobPriority4() {
return this.activeJobPriority4;
}
public void setActiveJobPriority4(final int activeJobPriority4) {
this.activeJobPriority4 = activeJobPriority4;
}
public int getActiveJobPriority5() {
return this.activeJobPriority5;
}
public void setActiveJobPriority5(final int activeJobPriority5) {
this.activeJobPriority5 = activeJobPriority5;
}
public int getActiveJobPriority6() {
return this.activeJobPriority6;
}
public void setActiveJobPriority6(final int activeJobPriority6) {
this.activeJobPriority6 = activeJobPriority6;
}
public int getActiveJobPriority7() {
return this.activeJobPriority7;
}
public void setActiveJobPriority7(final int activeJobPriority7) {
this.activeJobPriority7 = activeJobPriority7;
}
public int getActiveJobPriority8() {
return this.activeJobPriority8;
}
public void setActiveJobPriority8(final int activeJobPriority8) {
this.activeJobPriority8 = activeJobPriority8;
}
public int getActiveJobPriority9() {
return this.activeJobPriority9;
}
public void setActiveJobPriority9(final int activeJobPriority9) {
this.activeJobPriority9 = activeJobPriority9;
}
public int getScheduledJobOnQueuePriority1() {
return this.scheduledJobOnQueuePriority1;
}
public void setScheduledJobOnQueuePriority1(final int scheduledJobOnQueuePriority1) {
this.scheduledJobOnQueuePriority1 = scheduledJobOnQueuePriority1;
}
public int getScheduledJobOnQueuePriority2() {
return this.scheduledJobOnQueuePriority2;
}
public void setScheduledJobOnQueuePriority2(final int scheduledJobOnQueuePriority2) {
this.scheduledJobOnQueuePriority2 = scheduledJobOnQueuePriority2;
}
public int getScheduledJobOnQueuePriority3() {
return this.scheduledJobOnQueuePriority3;
}
public void setScheduledJobOnQueuePriority3(final int scheduledJobOnQueuePriority3) {
this.scheduledJobOnQueuePriority3 = scheduledJobOnQueuePriority3;
}
public int getScheduledJobOnQueuePriority4() {
return this.scheduledJobOnQueuePriority4;
}
public void setScheduledJobOnQueuePriority4(final int scheduledJobOnQueuePriority4) {
this.scheduledJobOnQueuePriority4 = scheduledJobOnQueuePriority4;
}
public int getScheduledJobOnQueuePriority5() {
return this.scheduledJobOnQueuePriority5;
}
public void setScheduledJobOnQueuePriority5(final int scheduledJobOnQueuePriority5) {
this.scheduledJobOnQueuePriority5 = scheduledJobOnQueuePriority5;
}
public int getScheduledJobOnQueuePriority6() {
return this.scheduledJobOnQueuePriority6;
}
public void setScheduledJobOnQueuePriority6(final int scheduledJobOnQueuePriority6) {
this.scheduledJobOnQueuePriority6 = scheduledJobOnQueuePriority6;
}
public int getScheduledJobOnQueuePriority7() {
return this.scheduledJobOnQueuePriority7;
}
public void setScheduledJobOnQueuePriority7(final int scheduledJobOnQueuePriority7) {
this.scheduledJobOnQueuePriority7 = scheduledJobOnQueuePriority7;
}
public int getScheduledJobOnQueuePriority8() {
return this.scheduledJobOnQueuePriority8;
}
public void setScheduledJobOnQueuePriority8(final int scheduledJobOnQueuePriority8) {
this.scheduledJobOnQueuePriority8 = scheduledJobOnQueuePriority8;
}
public int getScheduledJobOnQueuePriority9() {
return this.scheduledJobOnQueuePriority9;
}
public void setScheduledJobOnQueuePriority9(final int scheduledJobOnQueuePriority9) {
this.scheduledJobOnQueuePriority9 = scheduledJobOnQueuePriority9;
}
public int getHeldJobOnQueuePriority1() {
return this.heldJobOnQueuePriority1;
}
public void setHeldJobOnQueuePriority1(final int heldJobOnQueuePriority1) {
this.heldJobOnQueuePriority1 = heldJobOnQueuePriority1;
}
public int getHeldJobOnQueuePriority2() {
return this.heldJobOnQueuePriority2;
}
public void setHeldJobOnQueuePriority2(final int heldJobOnQueuePriority2) {
this.heldJobOnQueuePriority2 = heldJobOnQueuePriority2;
}
public int getHeldJobOnQueuePriority3() {
return this.heldJobOnQueuePriority3;
}
public void setHeldJobOnQueuePriority3(final int heldJobOnQueuePriority3) {
this.heldJobOnQueuePriority3 = heldJobOnQueuePriority3;
}
public int getHeldJobOnQueuePriority4() {
return this.heldJobOnQueuePriority4;
}
public void setHeldJobOnQueuePriority4(final int heldJobOnQueuePriority4) {
this.heldJobOnQueuePriority4 = heldJobOnQueuePriority4;
}
public int getHeldJobOnQueuePriority5() {
return this.heldJobOnQueuePriority5;
}
public void setHeldJobOnQueuePriority5(final int heldJobOnQueuePriority5) {
this.heldJobOnQueuePriority5 = heldJobOnQueuePriority5;
}
public int getHeldJobOnQueuePriority6() {
return this.heldJobOnQueuePriority6;
}
public void setHeldJobOnQueuePriority6(final int heldJobOnQueuePriority6) {
this.heldJobOnQueuePriority6 = heldJobOnQueuePriority6;
}
public int getHeldJobOnQueuePriority7() {
return this.heldJobOnQueuePriority7;
}
public void setHeldJobOnQueuePriority7(final int heldJobOnQueuePriority7) {
this.heldJobOnQueuePriority7 = heldJobOnQueuePriority7;
}
public int getHeldJobOnQueuePriority8() {
return this.heldJobOnQueuePriority8;
}
public void setHeldJobOnQueuePriority8(final int heldJobOnQueuePriority8) {
this.heldJobOnQueuePriority8 = heldJobOnQueuePriority8;
}
public int getHeldJobOnQueuePriority9() {
return this.heldJobOnQueuePriority9;
}
public void setHeldJobOnQueuePriority9(final int heldJobOnQueuePriority9) {
this.heldJobOnQueuePriority9 = heldJobOnQueuePriority9;
}
public int getActiveJobPriority0() {
return this.activeJobPriority0;
}
public void setActiveJobPriority0(final int activeJobPriority0) {
this.activeJobPriority0 = activeJobPriority0;
}
public int getScheduledJobOnQueuePriority0() {
return this.scheduledJobOnQueuePriority0;
}
public void setScheduledJobOnQueuePriority0(final int scheduledJobOnQueuePriority0) {
this.scheduledJobOnQueuePriority0 = scheduledJobOnQueuePriority0;
}
public int getHeldJobOnQueuePriority0() {
return this.heldJobOnQueuePriority0;
}
public void setHeldJobOnQueuePriority0(final int heldJobOnQueuePriority0) {
this.heldJobOnQueuePriority0 = heldJobOnQueuePriority0;
}
}

View File

@ -0,0 +1,91 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.jobqueue;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.data.ProgramCallDocument;
/**
* @author Lamotte Jean-Baptiste
*/
public class Qsprjobq100Handler {
private final String pcmlFile = "qsprjobq100.pcml";
private AS400 system = null;
public Qsprjobq100Handler(final AS400 system) {
this.system = system;
}
private void displayMessageError(final ProgramCallDocument pcml, final String programmName) throws Exception {
final AS400Message[] msgs = pcml.getMessageList(programmName);
for (final AS400Message msg : msgs) {
final String msgId = msg.getID();
final String msgText = msg.getText();
throw new Exception("" + msgId + " - " + msgText);
}
}
public Jobq0100 loadJobq0100(final String jobqName, final String lib) throws Exception {
String qualifiedQueueName = jobqName;
while (qualifiedQueueName.length() < 10) {
qualifiedQueueName += " ";
}
qualifiedQueueName += lib;
final ProgramCallDocument pcml = new ProgramCallDocument(this.system, this.pcmlFile);
pcml.setValue("qsprjobq.receiverLength", pcml.getOutputsize("qsprjobq.receiver"));
pcml.setValue("qsprjobq.qualifiedJobQueueName", qualifiedQueueName);
// pcml.setValue("qsprjobq.qualifiedJobQueueName", jobqName);
// If return code is false, we received messages from the server
if (pcml.callProgram("qsprjobq") == false) {
this.displayMessageError(pcml, "qsprjobq");
} else {
final int[] indices = new int[1];
indices[0] = 0;
final Jobq0100 jobq0100 = new Jobq0100();
jobq0100.setAuthorityCheck(pcml.getStringValue("qsprjobq.receiver.authorityCheck", indices));
jobq0100.setBytesAvailable(pcml.getIntValue("qsprjobq.receiver.bytesAvailable", indices));
jobq0100.setBytesReturned(pcml.getIntValue("qsprjobq.receiver.bytesReturned", indices));
jobq0100.setCurrentActive(pcml.getIntValue("qsprjobq.receiver.currentActive", indices));
jobq0100.setJobqLibName(pcml.getStringValue("qsprjobq.receiver.jobqLibName", indices));
jobq0100.setJobqName(pcml.getStringValue("qsprjobq.receiver.jobqName", indices));
jobq0100.setJobQueueStatus(pcml.getStringValue("qsprjobq.receiver.jobQueueStatus", indices));
jobq0100.setMaximumActive(pcml.getIntValue("qsprjobq.receiver.maximumActive", indices));
jobq0100.setNumberOfJob(pcml.getIntValue("qsprjobq.receiver.numberOfJob", indices));
jobq0100.setOperatorControlled(pcml.getStringValue("qsprjobq.receiver.operatorControlled", indices));
jobq0100.setSequenceNumber(pcml.getIntValue("qsprjobq.receiver.sequenceNumber", indices));
jobq0100.setSubSystemLibName(pcml.getStringValue("qsprjobq.receiver.subSystemLibName", indices));
jobq0100.setSubSystemName(pcml.getStringValue("qsprjobq.receiver.subSystemName", indices));
jobq0100.setTextDescription(pcml.getStringValue("qsprjobq.receiver.textDescription", indices));
return jobq0100;
}
return null;
}
}

View File

@ -0,0 +1,144 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.impl.jobqueue;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.data.ProgramCallDocument;
/**
* @author Lamotte Jean-Baptiste
*/
public class Qsprjobq200Handler {
private final String pcmlFile = "qsprjobq200.pcml";
private AS400 system = null;
public Qsprjobq200Handler(final AS400 system) {
this.system = system;
}
private void displayMessageError(final ProgramCallDocument pcml, final String programmName) throws Exception {
final AS400Message[] msgs = pcml.getMessageList(programmName);
for (final AS400Message msg : msgs) {
final String msgId = msg.getID();
final String msgText = msg.getText();
throw new Exception("" + msgId + " - " + msgText);
}
}
public Jobq0200 loadJobq0200(final String jobqName, final String lib) throws Exception {
String qualifiedQueueName = jobqName;
while (qualifiedQueueName.length() < 10) {
qualifiedQueueName += " ";
}
qualifiedQueueName += lib;
final ProgramCallDocument pcml = new ProgramCallDocument(this.system, this.pcmlFile);
pcml.setValue("qsprjobq.receiverLength", pcml.getOutputsize("qsprjobq.receiver"));
pcml.setValue("qsprjobq.qualifiedJobQueueName", qualifiedQueueName);
// pcml.setValue("qsprjobq.qualifiedJobQueueName", jobqName);
// If return code is false, we received messages from the server
if (pcml.callProgram("qsprjobq") == false) {
this.displayMessageError(pcml, "qsprjobq");
} else {
final int[] indices = new int[1];
indices[0] = 0;
final Jobq0200 jobq0200 = new Jobq0200();
jobq0200.setBytesReturned(pcml.getIntValue("qsprjobq.receiver.bytesReturned", indices));
jobq0200.setBytesAvailable(pcml.getIntValue("qsprjobq.receiver.bytesAvailable", indices));
jobq0200.setJobqName(pcml.getStringValue("qsprjobq.receiver.jobqName", indices));
jobq0200.setJobqLibName(pcml.getStringValue("qsprjobq.receiver.jobqLibName", indices));
jobq0200.setOperatorControlled(pcml.getStringValue("qsprjobq.receiver.operatorControlled", indices));
jobq0200.setAuthorityCheck(pcml.getStringValue("qsprjobq.receiver.authorityCheck", indices));
jobq0200.setNumberOfJob(pcml.getIntValue("qsprjobq.receiver.numberOfJob", indices));
jobq0200.setJobQueueStatus(pcml.getStringValue("qsprjobq.receiver.jobQueueStatus", indices));
jobq0200.setSubSystemName(pcml.getStringValue("qsprjobq.receiver.subSystemName", indices));
jobq0200.setSubSystemLibName(pcml.getStringValue("qsprjobq.receiver.subSystemLibName", indices));
jobq0200.setTextDescription(pcml.getStringValue("qsprjobq.receiver.textDescription", indices));
jobq0200.setSequenceNumber(pcml.getIntValue("qsprjobq.receiver.sequenceNumber", indices));
jobq0200.setMaximumActive(pcml.getIntValue("qsprjobq.receiver.maximumActive", indices));
jobq0200.setCurrentActive(pcml.getIntValue("qsprjobq.receiver.currentActive", indices));
jobq0200.setMaxActiveJobPriority1(pcml.getIntValue("qsprjobq.receiver.maxActiveJobPriority1", indices));
jobq0200.setMaxActiveJobPriority2(pcml.getIntValue("qsprjobq.receiver.maxActiveJobPriority2", indices));
jobq0200.setMaxActiveJobPriority3(pcml.getIntValue("qsprjobq.receiver.maxActiveJobPriority3", indices));
jobq0200.setMaxActiveJobPriority4(pcml.getIntValue("qsprjobq.receiver.maxActiveJobPriority4", indices));
jobq0200.setMaxActiveJobPriority5(pcml.getIntValue("qsprjobq.receiver.maxActiveJobPriority5", indices));
jobq0200.setMaxActiveJobPriority6(pcml.getIntValue("qsprjobq.receiver.maxActiveJobPriority6", indices));
jobq0200.setMaxActiveJobPriority7(pcml.getIntValue("qsprjobq.receiver.maxActiveJobPriority7", indices));
jobq0200.setMaxActiveJobPriority8(pcml.getIntValue("qsprjobq.receiver.maxActiveJobPriority8", indices));
jobq0200.setMaxActiveJobPriority9(pcml.getIntValue("qsprjobq.receiver.maxActiveJobPriority9", indices));
jobq0200.setActiveJobPriority0(pcml.getIntValue("qsprjobq.receiver.activeJobPriority0", indices));
jobq0200.setActiveJobPriority1(pcml.getIntValue("qsprjobq.receiver.activeJobPriority1", indices));
jobq0200.setActiveJobPriority2(pcml.getIntValue("qsprjobq.receiver.activeJobPriority2", indices));
jobq0200.setActiveJobPriority3(pcml.getIntValue("qsprjobq.receiver.activeJobPriority3", indices));
jobq0200.setActiveJobPriority4(pcml.getIntValue("qsprjobq.receiver.activeJobPriority4", indices));
jobq0200.setActiveJobPriority5(pcml.getIntValue("qsprjobq.receiver.activeJobPriority5", indices));
jobq0200.setActiveJobPriority6(pcml.getIntValue("qsprjobq.receiver.activeJobPriority6", indices));
jobq0200.setActiveJobPriority7(pcml.getIntValue("qsprjobq.receiver.activeJobPriority7", indices));
jobq0200.setActiveJobPriority8(pcml.getIntValue("qsprjobq.receiver.activeJobPriority8", indices));
jobq0200.setActiveJobPriority9(pcml.getIntValue("qsprjobq.receiver.activeJobPriority9", indices));
jobq0200
.setScheduledJobOnQueuePriority0(pcml.getIntValue("qsprjobq.receiver.scheduledJobOnQueuePriority0", indices));
jobq0200
.setScheduledJobOnQueuePriority1(pcml.getIntValue("qsprjobq.receiver.scheduledJobOnQueuePriority1", indices));
jobq0200
.setScheduledJobOnQueuePriority2(pcml.getIntValue("qsprjobq.receiver.scheduledJobOnQueuePriority2", indices));
jobq0200
.setScheduledJobOnQueuePriority3(pcml.getIntValue("qsprjobq.receiver.scheduledJobOnQueuePriority3", indices));
jobq0200
.setScheduledJobOnQueuePriority4(pcml.getIntValue("qsprjobq.receiver.scheduledJobOnQueuePriority4", indices));
jobq0200
.setScheduledJobOnQueuePriority5(pcml.getIntValue("qsprjobq.receiver.scheduledJobOnQueuePriority5", indices));
jobq0200
.setScheduledJobOnQueuePriority6(pcml.getIntValue("qsprjobq.receiver.scheduledJobOnQueuePriority6", indices));
jobq0200
.setScheduledJobOnQueuePriority7(pcml.getIntValue("qsprjobq.receiver.scheduledJobOnQueuePriority7", indices));
jobq0200
.setScheduledJobOnQueuePriority8(pcml.getIntValue("qsprjobq.receiver.scheduledJobOnQueuePriority8", indices));
jobq0200
.setScheduledJobOnQueuePriority9(pcml.getIntValue("qsprjobq.receiver.scheduledJobOnQueuePriority9", indices));
jobq0200.setHeldJobOnQueuePriority0(pcml.getIntValue("qsprjobq.receiver.heldJobOnQueuePriority0", indices));
jobq0200.setHeldJobOnQueuePriority1(pcml.getIntValue("qsprjobq.receiver.heldJobOnQueuePriority1", indices));
jobq0200.setHeldJobOnQueuePriority2(pcml.getIntValue("qsprjobq.receiver.heldJobOnQueuePriority2", indices));
jobq0200.setHeldJobOnQueuePriority3(pcml.getIntValue("qsprjobq.receiver.heldJobOnQueuePriority3", indices));
jobq0200.setHeldJobOnQueuePriority4(pcml.getIntValue("qsprjobq.receiver.heldJobOnQueuePriority4", indices));
jobq0200.setHeldJobOnQueuePriority5(pcml.getIntValue("qsprjobq.receiver.heldJobOnQueuePriority5", indices));
jobq0200.setHeldJobOnQueuePriority6(pcml.getIntValue("qsprjobq.receiver.heldJobOnQueuePriority6", indices));
jobq0200.setHeldJobOnQueuePriority7(pcml.getIntValue("qsprjobq.receiver.heldJobOnQueuePriority7", indices));
jobq0200.setHeldJobOnQueuePriority8(pcml.getIntValue("qsprjobq.receiver.heldJobOnQueuePriority8", indices));
jobq0200.setHeldJobOnQueuePriority9(pcml.getIntValue("qsprjobq.receiver.heldJobOnQueuePriority9", indices));
return jobq0200;
}
return null;
}
}

View File

@ -0,0 +1,289 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.msgqueue;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.MessageQueue;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.QueuedMessage;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.check.handler.ICachedMessageQueueHandler;
import com.centreon.connector.as400.check.handler.impl.AbstractHandler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
import com.centreon.connector.as400.utils.BlowFishUtils;
public class CachedMessageQueueHandler extends AbstractHandler implements ICachedMessageQueueHandler {
static int PAGINATE_SIZE = 50;
private static Map<String, QueuedMessage> LAST_MESSAGES = java.util.Collections
.synchronizedMap(new HashMap<String, QueuedMessage>());
public static String dumpLightMessage(QueuedMessage m) {
StringBuilder sb = new StringBuilder();
sb.append("[").append(m.getDate().getTime()).append("] ").append("(").append(m.getSeverity()).append(") ")
.append(m.getID()).append(":").append(m.getText().replace('|', ' ')).append(" [JobName: ")
.append(m.getFromJobName()).append("][JobNumber: ").append(m.getFromJobNumber()).append("][User: ")
.append(m.getUser()).append("]");
return sb.toString();
}
public static String dumpMessage(QueuedMessage m) {
final String newLine = "\n";
StringBuilder sb = new StringBuilder();
sb.append("[").append(m.getDate().getTime()).append("] ").append("(").append(m.getSeverity()).append(") ")
.append(m.getID()).append(":").append(m.getText().replace('|', ' ')).append(" [JobName: ")
.append(m.getFromJobName()).append("][JobNumber: ").append(m.getFromJobNumber()).append("][User: ")
.append(m.getUser()).append("]");
sb.append("getModificationDate: ").append(m.getModificationDate()).append(newLine).append("getAlertOption: ")
.append(m.getAlertOption()).append(newLine).append("getCurrentUser: ").append(m.getCurrentUser())
.append(newLine).append("getDataCcsidConversionStatusIndicator: ")
.append(m.getDataCcsidConversionStatusIndicator()).append(newLine).append("getDefaultReply: ")
.append(m.getDefaultReply()).append(newLine).append("getFileName: ").append(m.getFileName()).append(newLine)
.append("getFromJobName: ").append(m.getFromJobName()).append(newLine).append("getFromJobNumber: ")
.append(m.getFromJobNumber()).append(newLine).append("getFromProgram: ").append(m.getFromProgram())
.append(newLine).append("getLibraryName: ").append(m.getLibraryName()).append(newLine).append("getQueue: ")
.append(m.getQueue()).append(newLine).append("getMessage: ").append(m.getMessage()).append(newLine)
.append("getMessageFileLibrarySpecified: ").append(m.getMessageFileLibrarySpecified()).append(newLine)
.append("getMessageHelp: ").append(m.getMessageHelp()).append(newLine).append("getMessageHelpFormat: ")
.append(m.getMessageHelpFormat()).append(newLine).append("getMessageHelpReplacement: ")
.append(m.getMessageHelpReplacement()).append(newLine).append("getMessageHelpReplacementandFormat: ")
.append(m.getMessageHelpReplacementandFormat()).append(newLine).append("getPath: ").append(m.getPath())
.append(newLine).append("getReceivingModuleName: ").append(m.getReceivingModuleName()).append(newLine)
.append("getReceivingProcedureName: ").append(m.getReceivingProcedureName()).append(newLine)
.append("getReceivingProgramInstructionNumber: ").append(m.getReceivingProgramInstructionNumber())
.append(newLine).append("getReceivingProgramName: ").append(m.getReceivingProgramName()).append(newLine)
.append("getReceivingType: ").append(m.getReceivingType()).append(newLine).append("getReplyStatus: ")
.append(m.getReplyStatus()).append(newLine).append("getRequestStatus: ").append(m.getRequestStatus())
.append(newLine).append("getReceiverStatementNumbers: ").append(m.getReceiverStatementNumbers()).append(newLine)
.append("getRequestLevel: ").append(m.getRequestLevel()).append(newLine).append("getSenderType: ")
.append(m.getSenderType()).append(newLine).append("getSendingModuleName: ").append(m.getSendingModuleName())
.append(newLine).append("getSendingProcedureName: ").append(m.getSendingProcedureName()).append(newLine)
.append("getSendingProgramInstructionNumber: ").append(m.getSendingProgramInstructionNumber()).append(newLine)
.append("getSendingProgramName: ").append(m.getSendingProgramName()).append(newLine).append("getSendingType: ")
.append(m.getSendingType()).append(newLine).append("getSendingUserProfile: ").append(m.getSendingUserProfile())
.append(newLine).append("getSendingStatementNumbers: ").append(m.getSendingStatementNumbers()).append(newLine)
.append("getSeverity: ").append(m.getSeverity()).append(newLine).append("getSubstitutionData: ")
.append(m.getSubstitutionData()).append(newLine).append("getCcsidCodedCharacterSetIdentifierForData: ")
.append(m.getCcsidCodedCharacterSetIdentifierForData()).append(newLine)
.append("getCcsidCodedCharacterSetIdentifierForText: ").append(m.getCcsidCodedCharacterSetIdentifierForText())
.append(newLine).append("getCcsidconversionStatusIndicatorForData: ")
.append(m.getCcsidconversionStatusIndicatorForData()).append(newLine)
.append("getCcsidConversionStatusIndicatorForText: ").append(m.getCcsidConversionStatusIndicatorForText())
.append(newLine);
return sb.toString();
}
public CachedMessageQueueHandler(final String host, final String login, final String password) {
super(host, login, password);
}
@Override
public ResponseData getNewMessageInMessageQueue(final String messageQueuePath, final String messageIdfilterPattern,
final int minSeverityLevel, final int maxSeverityLevel)
throws Exception {
StringBuilder dbIdentifier = new StringBuilder();
dbIdentifier.append(messageQueuePath).append(messageIdfilterPattern).append(minSeverityLevel)
.append(maxSeverityLevel);
final Collection<QueuedMessage> messages = this.synchronizeDB(messageQueuePath, dbIdentifier.toString());
if (messages == null) {
return new ResponseData(ResponseData.statusOk, "Initialisation of the local DB");
}
final ResponseData data = new ResponseData();
for (final QueuedMessage message : messages) {
if ((message.getSeverity() >= minSeverityLevel) && (message.getSeverity() < maxSeverityLevel)) {
if ("A".equals(message.getReplyStatus())) {
// The message has been acknowledge already and we don't take it into account
continue;
}
final String messageId = message.getID();
if (messageIdfilterPattern != null && !messageId.matches(messageIdfilterPattern)) {
continue;
}
HashMap<String, Object> attrs = new HashMap<String, Object>();
attrs.put("id", messageId);
attrs.put("text", message.getText());
attrs.put("severity", message.getSeverity());
attrs.put("date", message.getDate().getTimeInMillis());
attrs.put("jobName", message.getFromJobName());
attrs.put("jobNumber", message.getFromJobNumber());
attrs.put("user", message.getUser());
data.getResult().add(attrs);
}
}
return data;
}
/**
* Synchronize DB and return the new messages
*
* @param messageQueuePath
* @return the new messages
* @throws AS400SecurityException
* @throws IOException
* @throws ErrorCompletingRequestException
* @throws InterruptedException
* @throws ObjectDoesNotExistException
*/
private Collection<QueuedMessage> synchronizeDB(final String messageQueuePath, final String dbIdentifier)
throws AS400SecurityException, IOException, ErrorCompletingRequestException, InterruptedException,
ObjectDoesNotExistException {
String key = BlowFishUtils.encrypt(host + login + dbIdentifier);
QueuedMessage previousLastMessage = CachedMessageQueueHandler.LAST_MESSAGES.get(key);
final AS400 system = this.getNewAs400();
final MessageQueue queue = new MessageQueue(system, messageQueuePath);
queue.setListDirection(false);
Collection<QueuedMessage> newMessages = null;
if (previousLastMessage == null) {
final QueuedMessage[] messages = queue.getMessages(0, 1);
CachedMessageQueueHandler.LAST_MESSAGES.put(key, messages[0]);
} else {
newMessages = new LinkedList<QueuedMessage>();
int position = 0;
final int lenght = queue.getLength();
boolean foundMessage = false;
boolean firstLoop = true;
ConnectorLogger.getInstance().trace("*********************************************************");
ConnectorLogger.getInstance().trace(" Check message for key: " + key);
ConnectorLogger.getInstance().trace(" Last message was: ");
ConnectorLogger.getInstance().trace(CachedMessageQueueHandler.dumpLightMessage(previousLastMessage));
while (position < lenght && !foundMessage) {
final QueuedMessage[] messages = queue.getMessages(position, CachedMessageQueueHandler.PAGINATE_SIZE);
position += CachedMessageQueueHandler.PAGINATE_SIZE;
for (QueuedMessage message : messages) {
if (firstLoop) {
firstLoop = false;
CachedMessageQueueHandler.LAST_MESSAGES.put(key, message);
ConnectorLogger.getInstance().trace(" New message is:");
ConnectorLogger.getInstance().trace(CachedMessageQueueHandler.dumpLightMessage(message));
}
if (this.customMessageEquals(message, previousLastMessage)
|| message.getDate().before(previousLastMessage.getDate())) {
foundMessage = true;
break;
} else {
newMessages.add(message);
}
}
}
}
system.disconnectService(AS400.COMMAND);
system.disconnectAllServices();
return newMessages;
}
/**
*
* @param a Message to compare with
* @param b Message to compare to
* @return True if all the used fields are equals. False otherwise.
*/
private boolean customMessageEquals(QueuedMessage a, QueuedMessage b) {
if (a == null) {
if (b == null) {
return true;
} else {
return false;
}
}
if (b == null) {
return false;
}
if (a.getDate() == null) {
if (b.getDate() != null)
return false;
} else {
if (!a.getDate().equals(b.getDate()))
return false;
}
if (a.getSeverity() != b.getSeverity())
return false;
if (a.getID() == null) {
if (b.getID() != null)
return false;
} else {
if (!a.getID().equals(b.getID()))
return false;
}
if (a.getText() == null) {
if (b.getText() != null)
return false;
} else {
if (!a.getText().equals(b.getText()))
return false;
}
if (a.getFromJobName() == null) {
if (b.getFromJobName() != null)
return false;
} else {
if (!a.getFromJobName().equals(b.getFromJobName()))
return false;
}
if (a.getFromJobNumber() == null) {
if (b.getFromJobNumber() != null)
return false;
} else {
if (!a.getFromJobNumber().equals(b.getFromJobNumber()))
return false;
}
if (a.getUser() == null) {
if (b.getUser() != null)
return false;
} else {
if (!a.getUser().equals(b.getUser()))
return false;
}
return true;
}
}

View File

@ -0,0 +1,128 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.msgqueue;
import java.io.IOException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.HashMap;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.MessageQueue;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.QueuedMessage;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.check.handler.IMessageQueueHandler;
import com.centreon.connector.as400.check.handler.impl.AbstractHandler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public class MessageQueueHandler extends AbstractHandler implements IMessageQueueHandler {
public MessageQueueHandler(final String host, final String login, final String password) {
super(host, login, password);
}
@Override
public void dumpMessageQueue() throws AS400SecurityException, ErrorCompletingRequestException, InterruptedException,
IOException, ObjectDoesNotExistException {
final AS400 system = this.getNewAs400();
/*
* MessageQueue messageQueue = new MessageQueue(system);
* messageQueue.getHelpTextFormatting(); messageQueue.getLength();
* messageQueue.getListDirection(); messageQueue.getMessages();
* messageQueue.getMessages(-1, -1); messageQueue.getPath();
* messageQueue.getSelection(); messageQueue.getSeverity();
* messageQueue.getSort(); messageQueue.getSystem();
* messageQueue.getUserStartingMessageKey();
* messageQueue.getWorkstationStartingMessageKey();
*/
final MessageQueue queue = new MessageQueue(system, MessageQueue.CURRENT);
@SuppressWarnings("rawtypes")
final Enumeration e = queue.getMessages();
while (e.hasMoreElements()) {
final QueuedMessage message = (QueuedMessage) e.nextElement();
System.out.println(message.getText().replace('|', ' '));
}
}
@Override
public ResponseData getErrorMessageQueue(final String messageQueuePath, final String messageIdfilterPattern,
final int minSeverityLevel, final int maxSeverityLevel) throws Exception {
final ResponseData data = new ResponseData();
final AS400 system = this.getNewAs400();
try {
final Collection<QueuedMessage> messagesFound = new LinkedList<QueuedMessage>();
final MessageQueue queue = new MessageQueue(system, messageQueuePath);
@SuppressWarnings("rawtypes")
final Enumeration e = queue.getMessages();
long errorCount = 0;
while (e.hasMoreElements()) {
final QueuedMessage message = (QueuedMessage) e.nextElement();
ConnectorLogger.getInstance()
.debug("Message found : " + message.getID() + " - " + message.getText().replace('|', ' '));
if ((message.getSeverity() >= minSeverityLevel) && (message.getSeverity() < maxSeverityLevel)) {
if ("A".equals(message.getReplyStatus())) {
// The message has been acknowledge already and we don't take it into account
continue;
}
final String messageId = message.getID();
if (messageIdfilterPattern != null && !messageId.matches(messageIdfilterPattern)) {
continue;
}
HashMap<String, Object> attrs = new HashMap<String, Object>();
attrs.put("id", messageId);
attrs.put("text", message.getText());
attrs.put("severity", message.getSeverity());
attrs.put("date", message.getDate().getTimeInMillis());
attrs.put("jobName", message.getFromJobName());
attrs.put("jobNumber", message.getFromJobNumber());
attrs.put("user", message.getUser());
data.getResult().add(attrs);
}
}
} catch (final Exception e) {
system.disconnectService(AS400.COMMAND);
system.disconnectAllServices();
throw e;
}
system.disconnectService(AS400.COMMAND);
system.disconnectAllServices();
return data;
}
}

View File

@ -0,0 +1,142 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.wrkprb;
public class CheckAS400Lang {
// These constants are referenced during parsing so
// that the correct phrases are found.
// This is found at the bottom when you type dspjob (name of a job
// that exists)
public String SELECTION = "Selection";
// This is the status of job or sbs when you type dspjob or dspsbsd
public String ACTIVE = "ACTIVE";
// This is the "DB Capability" dsplay when you type wrksyssts
public String DB_CAPABILITY = "DB capability";
// This is le display for the login screen
public String LOGIN_SCREEN = "System . . . . .";
// Run dspmsg and it will display "No messages available" if there are no
// messages
public String NO_MESSAGES_AVAILABLE = "No messages available";
// The "password has expired"/"password expires" messages are the messages
// you get when you login with an account which has an expired/will expire
// password.
public String PASSWORD_HAS_EXPIRED = "Password has expired";
public String PASSWORD_EXPIRES = "password expires";
// The "Display Messages" is what you get after logging into an account
// which displays any messages before continuing to the menu.
public String DISPLAY_MESSAGES = "Display Messages";
// Run wrkoutq blah* and it will say "(No output queues)"
public String NO_OUTPUT_QUEUES = "No output queues";
// If you type dspsbsd blah it will say "...not found..."
public static String NOT_FOUND = "not found";
// If you type dspjob QINTER, it should complain that there are duplicate
// jobs and print at the bottom of the window "duplicate jobs found"
public String DUPLICATE = "Duplicate";
// if you type dspjob blah, it will respond Job //blah not found
// Only put the Job // part.
public String JOB = "Job //";
// If try and execute a command that you are not allowed it will say
// "library *LIBL not allowed"
public String LIBRARY_NOT_ALLOWED = "library *LIBL not allowed";
// On a login with an expired password we look for "Exit sign-on" on the
// screen before we send the F3 to exit and disconnect.
public static String EXIT_SIGNON = "Exit sign-on request";
// If you type WRKACTJOB it may respond "No active jobs to display"
// when there is no job like searched for in the sytem
public String NO_JOB_TO_DISPLAY = "No active jobs to display";
// Messages needing a reply OR Messages not needing a reply
public String MSG_NEED_REPLY = "Messages needing a reply";
public String MSG_NOT_NEED_REPLY = "Messages not needing a reply";
// WRKDSKSTS The "Request/Compression/Bottom" message.
public String REQUEST_WORD = "Request";
public String DSK_STS_COMPRESSION = "Compression";
public String LIST_END = "Bottom";
public CheckAS400Lang(String lang) {
if (lang != null && lang.equals("fr")) {
this.setLangFr();
} else {
this.setLangEn();
}
}
public void setLangFr() {
this.SELECTION = "Selection";
this.ACTIVE = "ACTIVE";
this.DB_CAPABILITY = "DB capability";
this.LOGIN_SCREEN = "System . . . . .";
this.NO_MESSAGES_AVAILABLE = "No messages available";
this.PASSWORD_HAS_EXPIRED = "Password has expired";
this.PASSWORD_EXPIRES = "password expires";
this.DISPLAY_MESSAGES = "Display Messages";
this.NO_OUTPUT_QUEUES = "No output queues";
this.NOT_FOUND = "not found";
this.DUPLICATE = "Duplicate";
this.JOB = "Job //";
this.LIBRARY_NOT_ALLOWED = "library *LIBL not allowed";
this.EXIT_SIGNON = "Exit sign-on request";
this.NO_JOB_TO_DISPLAY = "No active jobs to display";
this.MSG_NEED_REPLY = "Messages needing a reply";
this.MSG_NOT_NEED_REPLY = "Messages not needing a reply";
this.REQUEST_WORD = "Request";
this.DSK_STS_COMPRESSION = "Compression";
this.LIST_END = "Bottom";
}
public void setLangEn() {
this.SELECTION = "Selection";
this.ACTIVE = "ACTIVE";
this.DB_CAPABILITY = "DB capability";
this.LOGIN_SCREEN = "System . . . . .";
this.NO_MESSAGES_AVAILABLE = "No messages available";
this.PASSWORD_HAS_EXPIRED = "Password has expired";
this.PASSWORD_EXPIRES = "password expires";
this.DISPLAY_MESSAGES = "Display Messages";
this.NO_OUTPUT_QUEUES = "No output queues";
this.NOT_FOUND = "not found";
this.DUPLICATE = "Duplicate";
this.JOB = "Job //";
this.LIBRARY_NOT_ALLOWED = "library *LIBL not allowed";
this.EXIT_SIGNON = "Exit sign-on request";
this.NO_JOB_TO_DISPLAY = "No active jobs to display";
this.MSG_NEED_REPLY = "Messages needing a reply";
this.MSG_NOT_NEED_REPLY = "Messages not needing a reply";
this.REQUEST_WORD = "Request";
this.DSK_STS_COMPRESSION = "Compression";
this.LIST_END = "Bottom";
}
};

View File

@ -0,0 +1,109 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.wrkprb;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//Example Use
/*
* Color code format WITH background color -> :foreground,background:
* Color code format WITHOUT background color -> :foreground,N:
* Reset Color format -> [RC]
*
* Example Use:
* String ansiColoredString = ColorCodes.ParseColors("Hello, This :blue,n:is[RC] a :red,white:response[RC].");
* - or -
* String ansiColoredString = ColorCodes.RED + "Hello" + ColorCodes.WHITE + ". This is a " + ColorColorCodes.BLUE + "test";
*/
/**
* Class used for ANSI Color manipulation in a console supporting ANSI color
* codes
*/
public class ColorCodes {
public static final String RESET = "\u001B[0m";
public static final String BLACK = "\u001B[30;40;1m";
public static final String RED = "\u001B[31;40;1m";
public static final String GREEN = "\u001B[32;40;1m";
public static final String YELLOW = "\u001B[33;40;1m";
public static final String BLUE = "\u001B[34;40;1m";
public static final String PURPLE = "\u001B[35;40;1m";
public static final String CYAN = "\u001B[36;40;1m";
public static final String WHITE = "\u001B[37;40;1m";
/**
* Parses a string with ANSI color codes based on the input
*
* @param input the input string
* @return the parsed ANSI string
*/
public static String ParseColors(final String input) {
String ret = input;
Pattern regexChecker = Pattern.compile(":\\S+,\\S+:");
Matcher regexMatcher = regexChecker.matcher(input);
while (regexMatcher.find()) {
if (regexMatcher.group().length() != 0) {
String sub = regexMatcher.group().trim();
sub = sub.replace(":", "");
String[] colors = sub.split(",");
ret = (colors[1].equalsIgnoreCase("N"))
? ret.replace(regexMatcher.group().trim(), "\u001B[3" + getColorID(colors[0]) + ";1m")
: ret.replace(regexMatcher.group().trim(),
"\u001B[3" + getColorID(colors[0]) + ";4" + getColorID(colors[1]) + ";1m");
ret = ret.replace("[RC]", ColorCodes.WHITE);
}
}
ret = ret + ColorCodes.RESET;
return ret;
}
/**
* Internal function for getting a colors value
*
* @param color The color as test
* @return The colors integral value
*/
private static int getColorID(String color) {
if (color.equalsIgnoreCase("BLACK")) {
return 0;
} else if (color.equalsIgnoreCase("RED")) {
return 1;
} else if (color.equalsIgnoreCase("GREEN")) {
return 2;
} else if (color.equalsIgnoreCase("YELLOW")) {
return 3;
} else if (color.equalsIgnoreCase("BLUE")) {
return 4;
} else if (color.equalsIgnoreCase("MAGENTA")) {
return 5;
} else if (color.equalsIgnoreCase("CYAN")) {
return 6;
} else if (color.equalsIgnoreCase("WHITE")) {
return 7;
}
return 7;
}
}

View File

@ -0,0 +1,327 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.check.handler.wrkprb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;
import java.util.HashMap;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import com.centreon.connector.as400.check.handler.wrkprb.CheckAS400Lang;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.check.handler.impl.AbstractHandler;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
@SuppressWarnings("unused")
public class WorkWithProblemHandler extends AbstractHandler {
private static int INSTANCE_ID = 0;
private static long LOGIN_COUNT = 0;
private static long LOGOUT_COUNT = 0;
private static final int LOG_TRACE = 0;
private static final int LOG_DEBUG = 1;
private static final int LOG_WARN = 2;
private static final int LOG_ERROR = 3;
private static final int OK = 0;
private static final int WARN = 1;
private static final int CRITICAL = 2;
private static final int UNKNOWN = 3;
// These constants are for the wait recieve, controlling
// any other logic that it should turn on. For example checking
// for invalid login.
private final static int NONE = 0;
private final static int LOGIN = 1;
private final static int GETOUTQ = 2;
private final static int GETJOB = 3;
private final static int GETSBSD = 4;
private final static int GETFD = 5;
private CheckAS400Lang AS400Lang;
private SSLSocket sslSocket;
private Socket ioSocket;
private PrintWriter ioWriter;
private BufferedReader ioReader;
private final boolean SSL = false;
private final String logPrefix;
public WorkWithProblemHandler(final String host, final String login, final String password) {
super(host, login, password);
this.logPrefix = "[" + WorkWithProblemHandler.INSTANCE_ID++ + "]";
}
private synchronized static long getAndIncrementLoginCount() {
return WorkWithProblemHandler.LOGIN_COUNT++;
}
private synchronized static long getAndIncrementLogoutCount() {
return WorkWithProblemHandler.LOGOUT_COUNT++;
}
public ResponseData getProblems(String lang) {
ResponseData response = null;
this.AS400Lang = new CheckAS400Lang(lang);
ConnectorLogger.getInstance().debug(this.logPrefix + "Establishing connection to server...");
if (this.open()) {
ConnectorLogger.getInstance().debug(this.logPrefix + "done.\nLogging in...");
boolean loggedIn = false;
try {
loggedIn = this.login();
} catch (final Exception e) {
ConnectorLogger.getInstance().debug(this.logPrefix + e.getMessage(), e);
response = new ResponseData(ResponseData.statusError, e.getMessage());
this.close();
return response;
}
if (loggedIn) {
ConnectorLogger.getInstance()
.debug(this.logPrefix + "LoginCount = " + WorkWithProblemHandler.getAndIncrementLoginCount());
ConnectorLogger.getInstance().debug(this.logPrefix + "Login completed.\nSending command (WRKPRB)...");
this.send("WRKPRB\r");
String result = null;
try {
result = this.waitReceive("F3=", WorkWithProblemHandler.NONE);
} catch (final Exception e) {
this.logout();
response = new ResponseData(ResponseData.statusError, e.getMessage());
ConnectorLogger.getInstance().error(e.getMessage(), e);
return response;
}
if (result != null) {
HashMap<String, Object> attrs = new HashMap<String, Object>();
response = new ResponseData();
attrs.put("result", result);
response.getResult().add(attrs);
ConnectorLogger.getInstance().debug(this.logPrefix + "Finished.");
} else {
response = new ResponseData(ResponseData.statusError, "Unexpected output on command");
}
this.logout();
} else {
this.logout();
response = new ResponseData(ResponseData.statusError, "Unexpected output on login");
}
} else {
response = new ResponseData(ResponseData.statusError, "Could not open connection to AS400");
}
return response;
}
// open connection to server
public boolean open() {
try {
if (this.SSL) {
final SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(this.host, 992);
this.ioWriter = new PrintWriter(sslSocket.getOutputStream(), true);
this.ioReader = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
} else {
ConnectorLogger.getInstance().debug(this.logPrefix + "Create socket...");
this.ioSocket = new Socket(this.host, 23);
this.ioSocket.setSoTimeout(6000);
ConnectorLogger.getInstance().debug(this.logPrefix + "Get outputstream");
this.ioWriter = new PrintWriter(this.ioSocket.getOutputStream(), true);
ConnectorLogger.getInstance().debug(this.logPrefix + "Read from socket");
this.ioReader = new BufferedReader(new InputStreamReader(this.ioSocket.getInputStream()));
ConnectorLogger.getInstance().debug(this.logPrefix + "Reading done");
}
this.send("\n\r");
return true;
} catch (final Exception e) {
ConnectorLogger.getInstance().debug(this.logPrefix + "CRITICAL: Network error", e);
return false;
}
}
// write str to stream
public void send(final String str) {
this.ioWriter.print(str);
this.ioWriter.flush();
}
public boolean login() throws Exception {
ConnectorLogger.getInstance().debug(this.logPrefix + " waiting for screen...");
/* Wait for the login screen */
if (this.waitReceive("IBM CORP", WorkWithProblemHandler.NONE) != null) {
ConnectorLogger.getInstance().debug(this.logPrefix + " sending login information for " + this.login + "...");
int unameLength;
unameLength = this.login.length();
/* send login user/pass */
this.send(this.login);
if (unameLength != 10) {
this.send("\t");
}
this.send(this.password + "\r");
ConnectorLogger.getInstance().debug(this.logPrefix + " waiting for login to process...");
/* Wait and receive command screen */
if (this.waitReceive("===>", WorkWithProblemHandler.LOGIN) != null)
return true;
}
return false;
}
// close connection to server
public boolean close() {
try {
if (this.SSL) {
this.sslSocket.close();
} else {
if (this.ioSocket != null) {
this.ioSocket.close();
}
}
if (this.ioReader != null) {
this.ioReader.close();
}
if (this.ioWriter != null) {
this.ioWriter.close();
}
return true;
} catch (final IOException e) {
ConnectorLogger.getInstance().debug(this.logPrefix + "CRITICAL: Network error", e);
return false;
}
}
// Receives all info in stream until it sees the string 'str'.
public String waitReceive(final String str, final int procedure) throws Exception {
final StringBuilder buffer = new StringBuilder();
boolean flag = true;
ConnectorLogger.getInstance().debug(this.logPrefix + " waiting for token " + str + "...");
try {
while (flag) {
int ch;
while ((ch = this.ioReader.read()) != -1) {
buffer.append((char) ch);
if (!this.ioReader.ready())
break;
}
ConnectorLogger.getInstance().trace("\n**BUFFER IS:**\n");
final String convertedBuffer = ColorCodes.ParseColors(buffer.toString());
ConnectorLogger.getInstance().trace(convertedBuffer);
ConnectorLogger.getInstance().trace("\n**END OF BUFFER**\n");
if (procedure == WorkWithProblemHandler.LOGIN) {
if (buffer.indexOf("CPF1107") != -1) {
this.close();
throw new Exception("CRITICAL - Login ERROR, Invalid password");
} else if (buffer.indexOf("CPF1120") != -1) {
this.close();
throw new Exception("CRITICAL - Login ERROR, Invalid username");
} else if (buffer.indexOf("/" + this.login.toUpperCase() + "/") != -1) {
ConnectorLogger.getInstance()
.debug(this.logPrefix + " responding to allocated to another job message...");
this.send("\r");
buffer.setLength(0);
} else if (buffer.indexOf(this.AS400Lang.PASSWORD_HAS_EXPIRED) != -1) {
this.send((char) 27 + "3");
this.waitReceive("Exit sign-on request", WorkWithProblemHandler.NONE);
this.send("Y\r");
this.close();
throw new Exception("WARNING - Expired password, Please change it.");
} else if (buffer.indexOf("CPF1394") != -1) {
this.close();
throw new Exception("CRITICAL - Login ERROR, User profile " + this.login + " cannot sign on.");
} else if (buffer.indexOf(this.AS400Lang.PASSWORD_EXPIRES) != -1) {
ConnectorLogger.getInstance().debug(this.logPrefix + " responding to password expires message...");
this.send("\r");
buffer.setLength(0);
} else if (buffer.indexOf(this.AS400Lang.DISPLAY_MESSAGES) != -1) {
ConnectorLogger.getInstance().debug(this.logPrefix + " continuing through message display...");
this.send((char) 27 + "3");
buffer.setLength(0);
}
} else if (procedure == WorkWithProblemHandler.GETOUTQ) {
if (buffer.indexOf(this.AS400Lang.NO_OUTPUT_QUEUES) != -1) {
this.logout();
throw new Exception("CRITICAL - outq does NOT exist");
}
}
// check for command not allowed errors
if (procedure != WorkWithProblemHandler.LOGIN) {
if (buffer.indexOf(this.AS400Lang.LIBRARY_NOT_ALLOWED) != -1) {
this.send((char) 27 + "3");
this.logout();
throw new Exception("CRITICAL - Command NOT allowed");
}
}
if (buffer.indexOf(str) != -1)
flag = false;
}
} catch (final IOException e) {
throw new Exception("CRITICAL: Network error:" + e);
}
ConnectorLogger.getInstance().debug(this.logPrefix + " token received.");
return buffer.toString();
}
public void logout() {
// send F3
ConnectorLogger.getInstance().debug(this.logPrefix + "Logging out...\n sending F3...");
this.send((char) 27 + "3");
try {
ConnectorLogger.getInstance().debug(this.logPrefix + "Wait for response...");
this.waitReceive("===>", WorkWithProblemHandler.NONE);
ConnectorLogger.getInstance().debug(this.logPrefix + "Response received. requesting signoff...");
// send logout
this.send("signoff *nolist\r");
// waitReceive(";53H",NONE);
ConnectorLogger.getInstance().debug(this.logPrefix + "Signoff sent. Wait for lockscreen...");
waitReceive("IBM CORP", NONE);
} catch (final Exception e) {
ConnectorLogger.getInstance().error(e.getMessage(), e);
} finally {
this.close();
}
ConnectorLogger.getInstance().debug(this.logPrefix + "Job ending immediately");
this.send("\r");
// waitReceive(LANG.LOGIN_SCREEN, NONE);
ConnectorLogger.getInstance().debug(this.logPrefix + " terminating connection...");
this.close();
ConnectorLogger.getInstance().debug(this.logPrefix + "Logged out.");
ConnectorLogger.getInstance()
.debug(this.logPrefix + "LogoutCount = " + WorkWithProblemHandler.getAndIncrementLogoutCount());
}
}

View File

@ -0,0 +1,44 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.client;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
public interface IClient {
String getRawRequest();
void writeAnswer(ResponseData answer);
void parseRequest() throws Exception;
String getAs400Host();
String getAs400Login();
String getAs400Password();
String getAs400CheckType();
Object getAs400Arg(String key);
}

View File

@ -0,0 +1,116 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.client.impl;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.centreon.connector.as400.dispatcher.check.InputData;
import com.centreon.connector.as400.client.IClient;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
/**
* @author Lamotte Jean-Baptiste
*/
abstract class AbstractClient implements IClient {
private InputData input = null;
private String as400Host = null;
private String as400Login = null;
private String as400Password = null;
private String as400CheckType = null;
private String as400Args = null;
private List<Map<String, String>> argList = new ArrayList<Map<String, String>>();
@Override
public abstract String getRawRequest();
protected abstract void writeAnswer(String answer);
public AbstractClient() {
}
@Override
public String getAs400Host() {
return this.input.getHost();
}
@Override
public String getAs400Login() {
return this.input.getLogin();
}
@Override
public String getAs400Password() {
return this.input.getPassword();
}
@Override
public String getAs400CheckType() {
return this.input.getCommand();
}
@Override
public Object getAs400Arg(String key) {
return this.input.getArg(key);
}
public List<Map<String , String>> getAs400ArgList(String key) {
Object arg = this.input.getArg(key);
if (arg == null) {
return null;
}
Gson gson = new Gson();
return gson.fromJson(arg.toString(), argList.getClass());
}
@Override
public void parseRequest() throws Exception {
Gson gson = new Gson();
this.input = gson.fromJson(this.getRawRequest(), InputData.class);
if (this.input.getHost() == null) {
throw new Exception("Invalid option: As/400 host required");
}
if (this.input.getLogin() == null) {
throw new Exception("Invalid option: As/400 login required");
}
if (this.input.getPassword() == null) {
throw new Exception("Invalid option: As/400 password required");
}
if (this.input.getCommand() == null) {
throw new Exception("Invalid option: As/400 command required");
}
}
@Override
public void writeAnswer(final ResponseData data) {
Gson gson = new GsonBuilder().create();
String json = gson.toJson(data);
this.writeAnswer(json);
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.client.impl;
import io.undertow.util.HttpString;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import io.undertow.io.Receiver.FullBytesCallback;
import com.centreon.connector.as400.Conf;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.client.IClient;
/**
* @author Lamotte Jean-Baptiste
*/
public class NetworkClient extends AbstractClient implements IClient {
private HttpServerExchange exchange = null;
private String rawRequest = null;
public NetworkClient(final HttpServerExchange exchange) {
super();
this.exchange = exchange;
}
public void readRequest() throws Exception {
HttpString method = exchange.getRequestMethod();
if (method.toString().equals("POST") == false) {
throw new Exception("Unsupported method");
}
this.exchange.getRequestReceiver().receiveFullBytes(new FullBytesCallback() {
@Override
public void handle(HttpServerExchange exchange, byte[] message) {
rawRequest = new String(message);
}
});
}
@Override
protected void writeAnswer(final String answer) {
ConnectorLogger.getInstance().debug("--------------------");
ConnectorLogger.getInstance().debug("request : " + this.getRawRequest());
ConnectorLogger.getInstance().debug("answer : \n" + answer);
ConnectorLogger.getInstance().debug("--------------------");
this.exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
this.exchange.getResponseSender().send(answer);
this.exchange.endExchange();
}
private void clean() {
}
@Override
public String getRawRequest() {
return this.rawRequest;
}
public HttpServerExchange getExchange() {
return this.exchange;
}
}

View File

@ -0,0 +1,140 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.daemon;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Collections;
import java.util.List;
import io.undertow.Undertow;
import io.undertow.UndertowOptions;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import io.undertow.security.api.AuthenticationMechanism;
import io.undertow.security.api.AuthenticationMode;
import io.undertow.security.api.SecurityContext;
import io.undertow.security.handlers.AuthenticationCallHandler;
import io.undertow.security.handlers.AuthenticationConstraintHandler;
import io.undertow.security.handlers.AuthenticationMechanismsHandler;
import io.undertow.security.handlers.SecurityInitialHandler;
import io.undertow.security.idm.IdentityManager;
import io.undertow.security.impl.BasicAuthenticationMechanism;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import com.centreon.connector.as400.daemon.MapIdentityManager;
import com.centreon.connector.as400.Conf;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.client.impl.NetworkClient;
/**
* The Class DaemonCore.
*
* @author Lamotte Jean-Baptiste
*/
public class Daemon {
/**
* execute.
*
*/
public void start(int port) throws Exception, IOException, InterruptedException {
Undertow server;
Undertow.Builder builder = Undertow.builder();
builder.setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, Conf.daemonNoRequestTimeout)
.setServerOption(UndertowOptions.REQUEST_PARSE_TIMEOUT, Conf.daemonRequestParseTimeout);
if (Conf.keyStoreFile != null) {
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
KeyStore keyStore = KeyStore.getInstance(Conf.keyStoreType);
FileInputStream stream = new FileInputStream(Conf.keyStoreFile);
if (stream == null) {
throw new Exception("keystore file not found: " + Conf.keyStoreFile);
}
keyStore.load(
stream,
Conf.keyStorePassword.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, Conf.keyStorePassword.toCharArray());
SSLContext sslContext;
sslContext = SSLContext.getInstance(Conf.sslProtocol);
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
builder.addHttpsListener(port, Conf.daemonListenerHost, sslContext);
} catch (final Exception e) {
throw new Exception(e);
}
} else {
builder.addHttpListener(port, Conf.daemonListenerHost);
}
if (Conf.authUsername != null && Conf.authPassword != null) {
final Map<String, char[]> users = new HashMap<String, char[]>(1);
users.put(Conf.authUsername, Conf.authPassword.toCharArray());
final IdentityManager identityManager = new MapIdentityManager(users);
server = builder.setHandler(addSecurity(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
NewtworkRunnable network = new NewtworkRunnable(new NetworkClient(exchange));
network.run();
}
}, identityManager))
.build();
} else {
server = builder.setHandler(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
NewtworkRunnable network = new NewtworkRunnable(new NetworkClient(exchange));
network.run();
}
}).build();
}
server.start();
while (true) {
Thread.sleep(10000);
}
}
private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) {
HttpHandler handler = toWrap;
handler = new AuthenticationCallHandler(handler);
handler = new AuthenticationConstraintHandler(handler);
final List<AuthenticationMechanism> mechanisms = Collections.<AuthenticationMechanism>singletonList(new BasicAuthenticationMechanism("My Realm"));
handler = new AuthenticationMechanismsHandler(handler, mechanisms);
handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler);
return handler;
}
}

View File

@ -0,0 +1,37 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.daemon;
/**
* @author Lamotte Jean-Baptiste
*/
public class DelayedConnectionException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
DelayedConnectionException(final String reason) {
super(reason);
}
}

View File

@ -0,0 +1,110 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.daemon;
import io.undertow.security.idm.Account;
import io.undertow.security.idm.Credential;
import io.undertow.security.idm.IdentityManager;
import io.undertow.security.idm.PasswordCredential;
import java.security.Principal;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* A simple {@link IdentityManager} implementation, that just takes a map of users to their
* password.
*
* This is in now way suitable for real world production use.
*
*
* @author Stuart Douglas
*/
class MapIdentityManager implements IdentityManager {
private final Map<String, char[]> users;
MapIdentityManager(final Map<String, char[]> users) {
this.users = users;
}
@Override
public Account verify(Account account) {
// An existing account so for testing assume still valid.
return account;
}
@Override
public Account verify(String id, Credential credential) {
Account account = getAccount(id);
if (account != null && verifyCredential(account, credential)) {
return account;
}
return null;
}
@Override
public Account verify(Credential credential) {
// TODO Auto-generated method stub
return null;
}
private boolean verifyCredential(Account account, Credential credential) {
if (credential instanceof PasswordCredential) {
char[] password = ((PasswordCredential) credential).getPassword();
char[] expectedPassword = users.get(account.getPrincipal().getName());
return Arrays.equals(password, expectedPassword);
}
return false;
}
private Account getAccount(final String id) {
if (users.containsKey(id)) {
return new Account() {
private final Principal principal = new Principal() {
@Override
public String getName() {
return id;
}
};
@Override
public Principal getPrincipal() {
return principal;
}
@Override
public Set<String> getRoles() {
return Collections.emptySet();
}
};
}
return null;
}
}

View File

@ -0,0 +1,68 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.daemon;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.client.impl.NetworkClient;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
import com.centreon.connector.as400.dispatcher.client.impl.ClientDispatcherImpl;
/**
* The Class NewtworkRunnable.
*
* @author Lamotte Jean-Baptiste
*/
class NewtworkRunnable implements Runnable {
private NetworkClient client = null;
/**
* Instantiates a new newtwork runnable.
*
* @param client the client
*/
NewtworkRunnable(final NetworkClient client) {
this.client = client;
}
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
try {
try {
this.client.readRequest();
this.client.parseRequest();
ClientDispatcherImpl.getInstance().dispatch(this.client);
} catch (final java.net.SocketException e) {
ConnectorLogger.getInstance().debug("", e);
this.client.writeAnswer(new ResponseData(ResponseData.statusError, "" + e.getMessage()));
} catch (final Exception e) {
ConnectorLogger.getInstance().error("", e);
this.client.writeAnswer(new ResponseData(ResponseData.statusError, "" + e.getMessage()));
}
} catch (final Exception e) {
ConnectorLogger.getInstance().error("", e);
}
}
}

View File

@ -0,0 +1,241 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.dispatcher.check;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import com.ibm.as400.access.AS400SecurityException;
import com.centreon.connector.as400.Conf;
import com.centreon.connector.as400.check.handler.ICachedMessageQueueHandler;
import com.centreon.connector.as400.check.handler.ICommandHandler;
import com.centreon.connector.as400.check.handler.IDiskHandler;
import com.centreon.connector.as400.check.handler.IJobHandler;
import com.centreon.connector.as400.check.handler.IJobQueueHandler;
import com.centreon.connector.as400.check.handler.IMessageQueueHandler;
import com.centreon.connector.as400.check.handler.ISubSystemHandler;
import com.centreon.connector.as400.check.handler.ISystemHandler;
import com.centreon.connector.as400.check.handler.impl.CommandHandler;
import com.centreon.connector.as400.check.handler.impl.DiskHandler;
import com.centreon.connector.as400.check.handler.impl.JobHandler;
import com.centreon.connector.as400.check.handler.impl.JobQueueHandler;
import com.centreon.connector.as400.check.handler.impl.SubSystemHandler;
import com.centreon.connector.as400.check.handler.impl.SystemHandler;
import com.centreon.connector.as400.check.handler.msgqueue.CachedMessageQueueHandler;
import com.centreon.connector.as400.check.handler.msgqueue.MessageQueueHandler;
import com.centreon.connector.as400.check.handler.wrkprb.WorkWithProblemHandler;
import com.centreon.connector.as400.client.impl.NetworkClient;
import io.undertow.server.HttpServerExchange;
/**
* @author Lamotte Jean-Baptiste
*/
public class CheckDispatcher {
private static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
private DefaultThreadFactory(final String host, final String type) {
final SecurityManager s = System.getSecurityManager();
this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.namePrefix = "" + host + "-pool-" + type + "-" + DefaultThreadFactory.poolNumber.getAndIncrement()
+ "-thread-";
}
@Override
public Thread newThread(final Runnable r) {
final Thread t = new Thread(this.group, r, this.namePrefix + this.threadNumber.getAndIncrement(), 0);
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
private String host = null;
private String login = null;
private String password = null;
private volatile ConcurrentHashMap<String, Long> filter = new ConcurrentHashMap<String, Long>();
private ISubSystemHandler subSystemHandler = null;
private ISystemHandler systemHandler = null;
private IJobHandler jobHandler = null;
private IDiskHandler diskHandler = null;
private ICommandHandler commandHandler = null;
private ThreadPoolExecutor executorGlobal = null;
private ThreadPoolExecutor executorJobs = null;
private ThreadPoolExecutor executorDisk = null;
class ThreadPoolExecutorPostFilter extends ThreadPoolExecutor {
public ThreadPoolExecutorPostFilter(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime,
final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
public ThreadPoolExecutorPostFilter(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime,
final TimeUnit unit, final BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public ThreadPoolExecutorPostFilter(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime,
final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}
public ThreadPoolExecutorPostFilter(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime,
final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory,
final RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
@Override
protected void afterExecute(final Runnable r, final Throwable t) {
if (r instanceof CheckHandlerRunnable) {
final CheckHandlerRunnable runnable = (CheckHandlerRunnable) r;
final NetworkClient client = runnable.getClient();
final String rawRequest = client.getRawRequest();
CheckDispatcher.this.filter.remove(rawRequest);
}
super.afterExecute(r, t);
}
}
public CheckDispatcher(final String host, final String login, final String password) {
this.host = host;
this.login = login;
this.password = password;
this.executorGlobal = new ThreadPoolExecutorPostFilter(5, 10, Conf.workerQueueTimeout, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
this.executorGlobal.setThreadFactory(new DefaultThreadFactory(host, "global"));
this.executorJobs = new ThreadPoolExecutorPostFilter(1, 1, Conf.workerQueueTimeout, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
this.executorJobs.setThreadFactory(new DefaultThreadFactory(host, "job"));
this.executorDisk = new ThreadPoolExecutorPostFilter(1, 1, Conf.workerQueueTimeout, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
this.executorDisk.setThreadFactory(new DefaultThreadFactory(host, "disk"));
}
public String getHost() {
return this.host;
}
public String getLogin() {
return this.login;
}
public String getPassword() {
return this.password;
}
public synchronized void dispatch(final NetworkClient client) {
if (this.filter.containsKey(client.getRawRequest())) {
final long time = this.filter.get(client.getRawRequest());
client.writeAnswer(new ResponseData(ResponseData.statusError, "Previous request pending (started "
+ (System.currentTimeMillis() - time)
+ " ms ago). Increase your check interval, and nagios check timeout. Also check your bandwidth availability"));
return;
}
this.filter.put(client.getRawRequest(), System.currentTimeMillis());
final String command = client.getAs400CheckType();
if (command.equalsIgnoreCase("listJobs")) {
client.getExchange().dispatch(this.executorJobs, new CheckHandlerRunnable(client, this));
} else if (command.equalsIgnoreCase("listDisks")) {
client.getExchange().dispatch(this.executorDisk, new CheckHandlerRunnable(client, this));
} else {
client.getExchange().dispatch(this.executorGlobal, new CheckHandlerRunnable(client, this));
}
}
public ICommandHandler getCommandHandler() throws AS400SecurityException, IOException {
if (this.commandHandler == null) {
this.commandHandler = new CommandHandler(this.host, this.login, this.password);
}
return this.commandHandler;
}
public IDiskHandler getDiskHandler() throws AS400SecurityException, IOException {
if (this.diskHandler == null) {
this.diskHandler = new DiskHandler(this.host, this.login, this.password);
}
return this.diskHandler;
}
public IJobHandler getJobHandler() throws AS400SecurityException, IOException {
if (this.jobHandler == null) {
this.jobHandler = new JobHandler(this.host, this.login, this.password);
}
return this.jobHandler;
}
public ISubSystemHandler getSubSystemHandler() throws AS400SecurityException, IOException {
if (this.subSystemHandler == null) {
this.subSystemHandler = new SubSystemHandler(this.host, this.login, this.password);
}
return this.subSystemHandler;
}
public ISystemHandler getSystemHandler() throws AS400SecurityException, IOException {
if (this.systemHandler == null) {
this.systemHandler = new SystemHandler(this.host, this.login, this.password);
}
return this.systemHandler;
}
public ICachedMessageQueueHandler getCachedMessageQueueHandler() throws AS400SecurityException, IOException {
return new CachedMessageQueueHandler(this.host, this.login, this.password);
}
public IMessageQueueHandler getMessageQueueHandler() throws AS400SecurityException, IOException {
return new MessageQueueHandler(this.host, this.login, this.password);
}
public IJobQueueHandler getJobQueueHandler() throws AS400SecurityException, IOException {
return new JobQueueHandler(this.host, this.login, this.password);
}
public WorkWithProblemHandler getWrkPrbHandler() throws AS400SecurityException, IOException {
return new WorkWithProblemHandler(this.host, this.login, this.password);
}
}

View File

@ -0,0 +1,249 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.dispatcher.check;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.ibm.as400.access.AS400SecurityException;
import com.centreon.connector.as400.Conf;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.client.impl.NetworkClient;
/**
* @author Lamotte Jean-Baptiste
*/
public class CheckHandlerRunnable implements Runnable {
protected NetworkClient client = null;
protected CheckDispatcher checkDispatcher = null;
public CheckHandlerRunnable(final NetworkClient client, final CheckDispatcher checkDispatcher) {
this.client = client;
this.checkDispatcher = checkDispatcher;
}
public NetworkClient getClient() {
return this.client;
}
private ResponseData getErrorResponse(final String message) {
return new ResponseData(ResponseData.statusError, message);
}
@Override
public void run() {
this.client.writeAnswer(this.handleAs400Args(this.client.getAs400CheckType()));
}
protected ResponseData handleAs400Args(final String check) {
ResponseData data = null;
final String[] args = null;
final long now = System.currentTimeMillis();
try {
if (check.equalsIgnoreCase("listDisks")) {
data = this.listDisks();
} else if (check.equalsIgnoreCase("listSubsystems")) {
data = this.listSubsystems();
} else if (check.equalsIgnoreCase("listJobs")) {
data = this.listJobs();
} else if (check.equalsIgnoreCase("getErrorMessageQueue")) {
data = this.getErrorMessageQueue();
} else if (check.equalsIgnoreCase("pageFault")) {
data = this.checkPageFault();
} else if (check.equalsIgnoreCase("getSystem")) {
data = this.getSystem();
} else if (check.equalsIgnoreCase("getJobQueues")) {
data = this.getJobQueues();
} else if (check.equalsIgnoreCase("executeCommand")) {
data = this.executeCommand();
} else if (check.equalsIgnoreCase("getNewMessageInMessageQueue")) {
data = this.getNewMessageInMessageQueue();
} else if (check.equalsIgnoreCase("workWithProblem")) {
data = this.workWithProblem();
} else if (check.equalsIgnoreCase("dumpAll")) {
this.dumpAll();
data = new ResponseData(ResponseData.statusOk, "dump done");
} else {
data = new ResponseData(ResponseData.statusError, "unknown request : " + check);
ConnectorLogger.getInstance().debug("unknown request : " + check);
}
} catch (final NumberFormatException e) {
data = new ResponseData(ResponseData.statusError, e.getMessage());
ConnectorLogger.getInstance().debug("Error during request", e);
} catch (final AS400SecurityException e) {
String error = "";
if (e.getCause() != null) {
error = e.getCause().getMessage();
} else {
error = e.getMessage();
}
data = new ResponseData(ResponseData.statusError, error);
ConnectorLogger.getInstance().debug("Error during request", e);
} catch (final IOException e) {
data = new ResponseData(ResponseData.statusError, e.getMessage());
ConnectorLogger.getInstance().debug("Error during request", e);
} catch (final Exception e) {
data = new ResponseData(ResponseData.statusError, e.getMessage());
ConnectorLogger.getInstance().debug("Error during request", e);
}
data.setRequestDuration(System.currentTimeMillis() - now);
return data;
}
private void dumpAll() {
try {
checkDispatcher.getSystemHandler().dumpSystem();
} catch (Exception e) {
ConnectorLogger.getInstance().error("Failed to dump system measures", e);
throw new IllegalStateException("Failed to dump system measures", e);
}
}
private ResponseData workWithProblem() throws Exception {
Object lang = this.client.getAs400Arg("lang");
final ResponseData data = this.checkDispatcher.getWrkPrbHandler().getProblems(
lang != null ? lang.toString() : null);
return data;
}
private ResponseData listDisks() throws Exception {
Object diskName = this.client.getAs400Arg("diskName");
final ResponseData data = this.checkDispatcher.getDiskHandler().listDisks(
diskName != null ? diskName.toString() : null);
return data;
}
private ResponseData listJobs() throws Exception {
ResponseData data = this.checkDispatcher.getJobHandler().listJobs();
return data;
}
private ResponseData executeCommand() throws Exception {
Object cmdName = this.client.getAs400Arg("cmdName");
final ResponseData data = this.checkDispatcher.getCommandHandler().executeCommand(
cmdName != null ? cmdName.toString() : null);
return data;
}
private ResponseData getJobQueues() throws Exception {
List<Map<String , String>> queues = this.client.getAs400ArgList("queues");
if (queues == null || queues.size() == 0) {
return this.getErrorResponse("Invalid arguments. please set jobQueueNames");
}
final ResponseData data = this.checkDispatcher.getJobQueueHandler().getJobQueues(queues);
return data;
}
private ResponseData getSystem() throws Exception {
final ResponseData data = this.checkDispatcher.getSystemHandler().getSystem();
return data;
}
private ResponseData checkPageFault() throws Exception {
final ResponseData data = this.checkDispatcher.getSystemHandler().getPageFault();
return data;
}
private ResponseData getErrorMessageQueue() throws NumberFormatException, Exception {
Object arg = this.client.getAs400Arg("messageQueuePath");
String messageQueuePath = (arg != null ? arg.toString() : null);
arg = this.client.getAs400Arg("messageIdfilterPattern");
String messageIdfilterPattern = (arg != null ? arg.toString() : null);
if (messageQueuePath == null) {
return this.getErrorResponse("Invalid arguments. please set messageQueuePath");
}
int minSeverityLevel;
try {
minSeverityLevel = Integer.parseInt(this.client.getAs400Arg("minSeverityLevel").toString());
} catch (final Exception e) {
minSeverityLevel = Integer.MIN_VALUE;
}
int maxSeverityLevel;
try {
maxSeverityLevel = Integer.parseInt(this.client.getAs400Arg("maxSeverityLevel").toString());
} catch (final Exception e) {
maxSeverityLevel = Integer.MAX_VALUE;
}
final ResponseData data = this.checkDispatcher.getMessageQueueHandler().getErrorMessageQueue(
messageQueuePath, messageIdfilterPattern, minSeverityLevel, maxSeverityLevel);
return data;
}
private ResponseData getNewMessageInMessageQueue() throws NumberFormatException, Exception {
Object arg = this.client.getAs400Arg("messageQueuePath");
String messageQueuePath = (arg != null ? arg.toString() : null);
arg = this.client.getAs400Arg("messageIdfilterPattern");
String messageIdfilterPattern = (arg != null ? arg.toString() : null);
if (messageQueuePath == null) {
return this.getErrorResponse("Invalid arguments. please set messageQueuePath");
}
int minSeverityLevel;
try {
minSeverityLevel = Integer.parseInt(this.client.getAs400Arg("minSeverityLevel").toString());
} catch (final Exception e) {
minSeverityLevel = Integer.MIN_VALUE;
}
int maxSeverityLevel;
try {
maxSeverityLevel = Integer.parseInt(this.client.getAs400Arg("maxSeverityLevel").toString());
} catch (final Exception e) {
maxSeverityLevel = Integer.MAX_VALUE;
}
final ResponseData data = this.checkDispatcher.getCachedMessageQueueHandler().getNewMessageInMessageQueue(
messageQueuePath, messageIdfilterPattern, minSeverityLevel, maxSeverityLevel);
return data;
}
private ResponseData listSubsystems() throws Exception {
final ResponseData data = this.checkDispatcher.getSubSystemHandler().listSubsystems();
return data;
}
}

View File

@ -0,0 +1,61 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.dispatcher.check;
import java.util.HashMap;
import java.util.Map;
/**
* @author Garnier Quentin
*/
public class InputData {
private String login = null;
private String password = null;
private String host = null;
private String command = null;
Map<String, Object> args = null;
public InputData() {
}
public String getLogin() {
return this.login;
}
public String getPassword() {
return this.password;
}
public String getHost() {
return this.host;
}
public String getCommand() {
return this.command;
}
public Object getArg(String name) {
if (args == null) {
return null;
}
return this.args.get(name);
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.dispatcher.check;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Lamotte Jean-Baptiste
*/
public class ResponseData {
public static final int statusOk = 0;
public static final int statusError = 1;
private long requestDuration = 0;
private int code = 0;
private String message = null;
private ArrayList result = new ArrayList();
public ResponseData() {
}
public ResponseData(final int code, final String message) {
this.message = message;
this.code = code;
}
public int getCode() {
return this.code;
}
public void setCode(final int code) {
this.code = code;
}
public ArrayList getResult() {
return this.result;
}
public Object getAttrResult(int index, String attr) {
HashMap<String, Object> attrs = (HashMap<String, Object>)this.result.get(index);
return attrs.get(attr);
}
public void setResult(final ArrayList result) {
this.result = result;
}
public String getMessage() {
return this.message;
}
public void setMessage(final String message) {
this.message = message;
}
public long getRequestDuration() {
return this.requestDuration;
}
public void setRequestDuration(final long requestDuration) {
this.requestDuration = requestDuration;
}
}

View File

@ -0,0 +1,31 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.dispatcher.client;
import java.io.IOException;
import com.ibm.as400.access.AS400SecurityException;
import com.centreon.connector.as400.client.impl.NetworkClient;
import com.centreon.connector.as400.daemon.DelayedConnectionException;
public interface ClientDispatcher {
void dispatch(final NetworkClient client) throws AS400SecurityException, IOException, DelayedConnectionException, Exception;
}

View File

@ -0,0 +1,88 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.dispatcher.client.impl;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.ibm.as400.access.AS400SecurityException;
import com.centreon.connector.as400.ConnectorLogger;
import com.centreon.connector.as400.client.impl.NetworkClient;
import com.centreon.connector.as400.daemon.DelayedConnectionException;
import com.centreon.connector.as400.dispatcher.check.CheckDispatcher;
import com.centreon.connector.as400.dispatcher.client.ClientDispatcher;
/**
* @author Lamotte Jean-Baptiste
*/
public class ClientDispatcherImpl implements ClientDispatcher {
private volatile Map<CheckDispatcher, Long> pool = null;
private static ClientDispatcherImpl instance = null;
public static synchronized ClientDispatcherImpl getInstance() {
if (ClientDispatcherImpl.instance == null) {
ClientDispatcherImpl.instance = new ClientDispatcherImpl();
}
return ClientDispatcherImpl.instance;
}
private ClientDispatcherImpl() {
this.pool = new ConcurrentHashMap<CheckDispatcher, Long>();
}
private synchronized CheckDispatcher createNewCheckDispatcher(final String host, final String login,
final String password) throws AS400SecurityException, IOException, DelayedConnectionException, Exception {
ConnectorLogger.getInstance().info("create new As400 : " + host);
CheckDispatcher resource = null;
resource = new CheckDispatcher(host, login, password);
this.pool.put(resource, System.currentTimeMillis());
return resource;
}
private CheckDispatcher getAs400(final String host, final String login, final String password)
throws AS400SecurityException, IOException, DelayedConnectionException, Exception {
for (final CheckDispatcher resource : this.pool.keySet()) {
if (resource.getHost().equalsIgnoreCase(host) && resource.getLogin().equalsIgnoreCase(login)
&& resource.getPassword().equalsIgnoreCase(password)) {
this.pool.put(resource, System.currentTimeMillis());
return resource;
}
}
return this.createNewCheckDispatcher(host, login, password);
}
@Override
public synchronized void dispatch(final NetworkClient client)
throws AS400SecurityException, IOException, DelayedConnectionException, Exception {
final CheckDispatcher checkDispatcher = this.getAs400(client.getAs400Host(), client.getAs400Login(),
client.getAs400Password());
checkDispatcher.dispatch(client);
}
}

View File

@ -0,0 +1,39 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.parser;
import org.apache.commons.cli.ParseException;
/**
* @author Lamotte Jean-Baptiste
*/
public class InvalidOptionException extends ParseException {
/**
*
*/
private static final long serialVersionUID = 3542190890196517483L;
public InvalidOptionException(final String reason) {
super(reason);
}
}

View File

@ -0,0 +1,112 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.parser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
/**
* @author Lamotte Jean-Baptiste
*/
public class OptionFactory {
private OptionFactory() {
}
private static synchronized Options addAs400Options(final Options options) {
OptionBuilder.withArgName("host");
OptionBuilder.hasArg();
OptionBuilder.withDescription("dns name or ip address");
OptionBuilder.withLongOpt("host");
final Option host = OptionBuilder.create('H');
OptionBuilder.withArgName("login");
OptionBuilder.hasArg();
OptionBuilder.withDescription("login");
OptionBuilder.withLongOpt("login");
final Option login = OptionBuilder.create('l');
OptionBuilder.withArgName("password");
OptionBuilder.hasArg();
OptionBuilder.withDescription("password");
OptionBuilder.withLongOpt("password");
final Option password = OptionBuilder.create('p');
OptionBuilder.withArgName("check");
OptionBuilder.hasArgs();
OptionBuilder.withDescription("check command type");
OptionBuilder.withLongOpt("check");
final Option check = OptionBuilder.create('C');
OptionBuilder.withArgName("args");
OptionBuilder.hasArgs();
OptionBuilder.withDescription("arguments for as400 request");
OptionBuilder.withLongOpt("args");
final Option args = OptionBuilder.create('A');
options.addOption(host);
options.addOption(login);
options.addOption(password);
options.addOption(check);
options.addOption(args);
return options;
}
/**
* Gets the options.
*
* @return the options
*/
public static synchronized Options getOptions() {
Options options = new Options();
final Option daemon = Option.builder("D")
.argName("port")
.hasArg()
.desc("Start the daemon on the specified port")
.longOpt("port")
.build();
// Création des option générique
final Option help = new Option("h", "help", false, "print this message");
final Option version = new Option("v", "version", false, "print the version information and exit");
final Option jmx = new Option("I", "as400", false, "Request type : as400");
// Ajout des options de groupe unique
final OptionGroup startType = new OptionGroup();
startType.addOption(daemon);
startType.addOption(jmx);
startType.addOption(help);
startType.addOption(version);
startType.setRequired(true);
options.addOptionGroup(startType);
options = OptionFactory.addAs400Options(options);
return options;
}
}

View File

@ -0,0 +1,83 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.utils;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.centreon.connector.as400.ConnectorLogger;
public final class BlowFishUtils {
private static final String BLOWFISH = "Blowfish"; //$NON-NLS-1$
private static final String TRANSFORMATION = "Blowfish/CBC/PKCS5Padding"; //$NON-NLS-1$
private static final byte[] KEY = "3fe7b4d9e0b50a".getBytes(StringUtils.CHARSET); //$NON-NLS-1$
private static final byte[] IV_BYTES = "00000000".getBytes(StringUtils.CHARSET); //$NON-NLS-1$
public static final String decrypt(final String cryptedMessage) {
if (cryptedMessage == null) {
return StringUtils.EMPTY_STRING;
}
try {
final byte[] buffer = HexUtils.hexToBuffer(cryptedMessage);
return new String(BlowFishUtils.decrypt(buffer, BlowFishUtils.KEY), StringUtils.CHARSET);
} catch (final Exception e) {
ConnectorLogger.getInstance().error("", e);
return StringUtils.EMPTY_STRING;
}
}
public static final String encrypt(final String message) {
if (message == null) {
return StringUtils.EMPTY_STRING;
}
try {
final byte[] crypted = BlowFishUtils.encrypt(message.getBytes(StringUtils.CHARSET), BlowFishUtils.KEY);
return HexUtils.bufferToHex(crypted);
} catch (final Exception e) {
ConnectorLogger.getInstance().error("", e);
return StringUtils.EMPTY_STRING;
}
}
private static final byte[] decrypt(final byte[] encrypted, final byte[] key) throws GeneralSecurityException {
final SecretKeySpec skeySpec = new SecretKeySpec(key, BlowFishUtils.BLOWFISH);
final Cipher cipher = Cipher.getInstance(BlowFishUtils.TRANSFORMATION);
final IvParameterSpec ivs = new IvParameterSpec(BlowFishUtils.IV_BYTES);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivs);
return cipher.doFinal(encrypted);
}
private static final byte[] encrypt(final byte[] messageBytes, final byte[] key) throws GeneralSecurityException {
final SecretKeySpec skeySpec = new SecretKeySpec(key, BlowFishUtils.BLOWFISH);
final Cipher cipher = Cipher.getInstance(BlowFishUtils.TRANSFORMATION);
final IvParameterSpec ivs = new IvParameterSpec(BlowFishUtils.IV_BYTES);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivs);
return cipher.doFinal(messageBytes);
}
private BlowFishUtils() {
// hide
}
}

View File

@ -0,0 +1,60 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.utils;
public final class HexUtils {
private static final char[] K_HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F' };
public static String bufferToHex(final byte[] buffer) {
return HexUtils.bufferToHex(buffer, 0, buffer.length);
}
public static byte[] hexToBuffer(final String hex) {
final byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < (hex.length() - 1); i += 2) {
final String output = hex.substring(i, i + 2);
bytes[i / 2] = (byte) Integer.parseInt(output, 16);
}
return bytes;
}
private static void appendHexPair(final byte b, final StringBuilder hexString) {
final char highNibble = HexUtils.K_HEX_CHARS[(b & 0xF0) >> 4];
final char lowNibble = HexUtils.K_HEX_CHARS[b & 0x0F];
hexString.append(highNibble);
hexString.append(lowNibble);
}
private static String bufferToHex(final byte[] buffer, final int startOffset, final int length) {
final StringBuilder hexString = new StringBuilder(2 * length);
final int endOffset = startOffset + length;
for (int i = startOffset; i < endOffset; i++) {
HexUtils.appendHexPair(buffer[i], hexString);
}
return hexString.toString();
}
private HexUtils() {
}
}

View File

@ -0,0 +1,125 @@
/*
* Copyright 2021 Centreon (http://www.centreon.com/)
*
* Centreon is a full-fledged industry-strength solution that meets
* the needs in IT infrastructure and application monitoring for
* service performance.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centreon.connector.as400.utils;
import java.nio.charset.Charset;
import com.centreon.connector.as400.ConnectorLogger;
public final class StringUtils {
public static final Charset CHARSET = Charset.forName("UTF-8"); //$NON-NLS-1$
public static final String NEW_LINE = System.getProperty("line.separator"); //$NON-NLS-1$
public static final String EMPTY_STRING = ""; //$NON-NLS-1$
public static final String SLASH = "/"; //$NON-NLS-1$
public static final String VIRGULE = ","; //$NON-NLS-1$
public static boolean isNullEmptyOrBlank(final String string) {
if (string == null) {
return true;
}
if (string.length() == 0) {
return true;
}
if (string.trim().length() == 0) {
return true;
}
return "null".equalsIgnoreCase(string.trim()); //$NON-NLS-1$
}
public static boolean isOneNullEmptyOrBlank(final String... args) {
for (final String arg : args) {
if (StringUtils.isNullEmptyOrBlank(arg)) {
return true;
}
}
return false;
}
public static String nonNullString(final String string) {
if (string == null) {
return StringUtils.EMPTY_STRING;
}
return string;
}
public static double parseDouble(final String input) {
return StringUtils.parseDouble(input, -1d);
}
public static double parseDouble(final String input, final double errorValue) {
if ((input == null) || (input.length() == 0)) {
return errorValue;
}
try {
return Double.parseDouble(input);
} catch (final Exception e) {
ConnectorLogger.getInstance().error("", e);
return errorValue;
}
}
public static int parseInt(final String input) {
return StringUtils.parseInt(input, -1);
}
public static int parseInt(final String input, final int errorValue) {
if ((input == null) || (input.length() == 0)) {
return errorValue;
}
try {
return Integer.parseInt(input);
} catch (final Exception e) {
ConnectorLogger.getInstance().error("", e);
return errorValue;
}
}
public static long parseLong(final String input) {
return StringUtils.parseLong(input, Long.MIN_VALUE);
}
public static long parseLong(final String input, final long errorValue) {
if ((input == null) || (input.length() == 0)) {
return errorValue;
}
try {
return Long.parseLong(input);
} catch (final Exception e) {
ConnectorLogger.getInstance().error("", e);
return errorValue;
}
}
public static String toHex(final int value, final int length) {
String hex = Integer.toHexString(value);
while (hex.length() < length) {
hex = '0' + hex;
}
return hex;
}
private StringUtils() {
// hide constructor
}
}

View File

@ -0,0 +1,4 @@
Open List of Jobs (QGYOLJOB) API
Retrieve Job Queue Information (QSPRJOBQ) API
List Subsystem Job Queues (QWDLSJBQ) API
Open List of ASPs (QYASPOL) API

View File

@ -0,0 +1,55 @@
<pcml version="1.0">
Offset Type Field
Dec Hex
0 0 BINARY(4) Bytes returned
4 4 BINARY(4) Bytes availablea
8 8 CHAR(10) Job queue name
18 12 CHAR(10) Job queue library name
28 1C CHAR(10) Operator controlled
38 26 CHAR(10) Authority to check
48 30 BINARY(4) Number of jobs
52 34 CHAR(10) Job queue status
62 3E CHAR(10) Subsystem name
72 48 CHAR(50) Text description
122 7A CHAR(10) Subsystem library name
132 84 BINARY(4) Sequence number
136 88 BINARY(4) Maximum active
140 8C BINARY(4) Current active
<!-- Format JOBQ0100 - Other formats are available -->
<struct name="jobq0100">
<data name="bytesReturned" type="int" length="4" usage="output"/>
<data name="bytesAvailable" type="int" length="4" usage="output"/>
<data name="jobqName" type="char" length="10" usage="output"/>
<data name="jobqLibName" type="char" length="10" usage="output"/>
<data name="operatorControlled" type="char" length="10" usage="output"/>
<data name="authorityCheck" type="char" length="10" usage="output"/>
<data name="numberOfJob" type="int" length="4" usage="output"/>
<data name="jobQueueStatus" type="char" length="10" usage="output"/>
<data name="subSystemName" type="char" length="10" usage="output"/>
<data name="textDescription" type="char" length="50" usage="output"/>
<data name="subSystemLibName" type="char" length="10" usage="output"/>
<data name="sequenceNumber" type="int" length="4" usage="output"/>
<data name="maximumActive" type="int" length="4" usage="output"/>
<data name="currentActive" type="int" length="4" usage="output"/>
</struct>
1 Receiver variable Output Char(*)
2 Length of receiver variable Input Binary(4)
3 Format name Input Char(8)
4 Qualified job queue name Input Char(20)
5 Error Code I/O Char(*)
<!-- Program QSPRJOBQ and its parameter list for retrieving JOBQ0100 format -->
<program name="qsprjobq" path="/QSYS.lib/QSPRJOBQ.pgm">
<data name="receiver" type="struct" struct="jobq0100" usage="output"/>
<data name="receiverLength" type="int" length="4" usage="input" />
<data name="format" type="char" length="8" usage="input" init="JOBQ0100"/>
<data name="qualifiedJobQueueName" type="char" length="20" usage="input"/>
<data name="errorCode" type="int" length="4" usage="input" init="0"/>
</program>
</pcml>

View File

@ -0,0 +1,153 @@
<pcml version="1.0">
Offset Type Field
Dec Hex
0 0 BINARY(4) Bytes returned
4 4 BINARY(4) Bytes available
8 8 CHAR(10) Job queue name
18 12 CHAR(10) Job queue library name
28 1C CHAR(10) Operator controlled
38 26 CHAR(10) Authority to check
48 30 BINARY(4) Number of jobs
52 34 CHAR(10) Job queue status
62 3E CHAR(10) Subsystem name
72 48 CHAR(10) Subsystem library name
82 52 CHAR(50) Text description
132 84 BINARY(4) Sequence Number
136 88 BINARY(4) Maximum active
140 8C BINARY(4) Current active
144 90 BINARY(4) Maximum active jobs with priority 1
148 94 BINARY(4) Maximum active jobs with priority 2
152 98 BINARY(4) Maximum active jobs with priority 3
156 9C BINARY(4) Maximum active jobs with priority 4
160 A0 BINARY(4) Maximum active jobs with priority 5
164 A4 BINARY(4) Maximum active jobs with priority 6
168 A8 BINARY(4) Maximum active jobs with priority 7
172 AC BINARY(4) Maximum active jobs with priority 8
176 B0 BINARY(4) Maximum active jobs with priority 9
180 B4 BINARY(4) Active jobs with priority 0
184 B8 BINARY(4) Active jobs with priority 1
188 BC BINARY(4) Active jobs with priority 2
192 C0 BINARY(4) Active jobs with priority 3
196 C4 BINARY(4) Active jobs with priority 4
200 C8 BINARY(4) Active jobs with priority 5
204 CC BINARY(4) Active jobs with priority 6
208 D0 BINARY(4) Active jobs with priority 7
212 D4 BINARY(4) Active jobs with priority 8
216 D8 BINARY(4) Active jobs with priority 9
220 DC BINARY(4) Released jobs on queue with priority 0
224 E0 BINARY(4) Released jobs on queue with priority 1
228 E4 BINARY(4) Released jobs on queue with priority 2
232 E8 BINARY(4) Released jobs on queue with priority 3
236 EC BINARY(4) Released jobs on queue with priority 4
240 F0 BINARY(4) Released jobs on queue with priority 5
244 F4 BINARY(4) Released jobs on queue with priority 6
248 F8 BINARY(4) Released jobs on queue with priority 7
252 FC BINARY(4) Released jobs on queue with priority 8
256 100 BINARY(4) Released jobs on queue with priority 9
260 104 BINARY(4) Scheduled jobs on queue with priority 0
264 108 BINARY(4) Scheduled jobs on queue with priority 1
268 10C BINARY(4) Scheduled jobs on queue with priority 2
272 110 BINARY(4) Scheduled jobs on queue with priority 3
276 114 BINARY(4) Scheduled jobs on queue with priority 4
280 118 BINARY(4) Scheduled jobs on queue with priority 5
284 11C BINARY(4) Scheduled jobs on queue with priority 6
288 120 BINARY(4) Scheduled jobs on queue with priority 7
292 124 BINARY(4) Scheduled jobs on queue with priority 8
296 128 BINARY(4) Scheduled jobs on queue with priority 9
300 12C BINARY(4) Held jobs on queue with priority 0
304 130 BINARY(4) Held jobs on queue with priority 1
308 134 BINARY(4) Held jobs on queue with priority 2
312 138 BINARY(4) Held jobs on queue with priority 3
316 13C BINARY(4) Held jobs on queue with priority 4
320 140 BINARY(4) Held jobs on queue with priority 5
324 144 BINARY(4) Held jobs on queue with priority 6
328 148 BINARY(4) Held jobs on queue with priority 7
332 14C BINARY(4) Held jobs on queue with priority 8
336 150 BINARY(4) Held jobs on queue with priority 9
<!-- Format JOBQ0200 - Other formats are available -->
<struct name="jobq0200">
<data name="bytesReturned" type="int" length="4" usage="output"/>
<data name="bytesAvailable" type="int" length="4" usage="output"/>
<data name="jobqName" type="char" length="10" usage="output"/>
<data name="jobqLibName" type="char" length="10" usage="output"/>
<data name="operatorControlled" type="char" length="10" usage="output"/>
<data name="authorityCheck" type="char" length="10" usage="output"/>
<data name="numberOfJob" type="int" length="4" usage="output"/>
<data name="jobQueueStatus" type="char" length="10" usage="output"/>
<data name="subSystemName" type="char" length="10" usage="output"/>
<data name="subSystemLibName" type="char" length="10" usage="output"/>
<data name="textDescription" type="char" length="50" usage="output"/>
<data name="sequenceNumber" type="int" length="4" usage="output"/>
<data name="maximumActive" type="int" length="4" usage="output"/>
<data name="currentActive" type="int" length="4" usage="output"/>
<data name="maxActiveJobPriority1" type="int" length="4" usage="output"/>
<data name="maxActiveJobPriority2" type="int" length="4" usage="output"/>
<data name="maxActiveJobPriority3" type="int" length="4" usage="output"/>
<data name="maxActiveJobPriority4" type="int" length="4" usage="output"/>
<data name="maxActiveJobPriority5" type="int" length="4" usage="output"/>
<data name="maxActiveJobPriority6" type="int" length="4" usage="output"/>
<data name="maxActiveJobPriority7" type="int" length="4" usage="output"/>
<data name="maxActiveJobPriority8" type="int" length="4" usage="output"/>
<data name="maxActiveJobPriority9" type="int" length="4" usage="output"/>
<data name="activeJobPriority0" type="int" length="4" usage="output"/>
<data name="activeJobPriority1" type="int" length="4" usage="output"/>
<data name="activeJobPriority2" type="int" length="4" usage="output"/>
<data name="activeJobPriority3" type="int" length="4" usage="output"/>
<data name="activeJobPriority4" type="int" length="4" usage="output"/>
<data name="activeJobPriority5" type="int" length="4" usage="output"/>
<data name="activeJobPriority6" type="int" length="4" usage="output"/>
<data name="activeJobPriority7" type="int" length="4" usage="output"/>
<data name="activeJobPriority8" type="int" length="4" usage="output"/>
<data name="activeJobPriority9" type="int" length="4" usage="output"/>
<data name="scheduledJobOnQueuePriority0" type="int" length="4" usage="output"/>
<data name="scheduledJobOnQueuePriority1" type="int" length="4" usage="output"/>
<data name="scheduledJobOnQueuePriority2" type="int" length="4" usage="output"/>
<data name="scheduledJobOnQueuePriority3" type="int" length="4" usage="output"/>
<data name="scheduledJobOnQueuePriority4" type="int" length="4" usage="output"/>
<data name="scheduledJobOnQueuePriority5" type="int" length="4" usage="output"/>
<data name="scheduledJobOnQueuePriority6" type="int" length="4" usage="output"/>
<data name="scheduledJobOnQueuePriority7" type="int" length="4" usage="output"/>
<data name="scheduledJobOnQueuePriority8" type="int" length="4" usage="output"/>
<data name="scheduledJobOnQueuePriority9" type="int" length="4" usage="output"/>
<data name="heldJobOnQueuePriority0" type="int" length="4" usage="output"/>
<data name="heldJobOnQueuePriority1" type="int" length="4" usage="output"/>
<data name="heldJobOnQueuePriority2" type="int" length="4" usage="output"/>
<data name="heldJobOnQueuePriority3" type="int" length="4" usage="output"/>
<data name="heldJobOnQueuePriority4" type="int" length="4" usage="output"/>
<data name="heldJobOnQueuePriority5" type="int" length="4" usage="output"/>
<data name="heldJobOnQueuePriority6" type="int" length="4" usage="output"/>
<data name="heldJobOnQueuePriority7" type="int" length="4" usage="output"/>
<data name="heldJobOnQueuePriority8" type="int" length="4" usage="output"/>
<data name="heldJobOnQueuePriority9" type="int" length="4" usage="output"/>
</struct>
1 Receiver variable Output Char(*)
2 Length of receiver variable Input Binary(4)
3 Format name Input Char(8)
4 Qualified job queue name Input Char(20)
5 Error Code I/O Char(*)
<!-- Program QSPRJOBQ and its parameter list for retrieving JOBQ0200 format -->
<program name="qsprjobq" path="/QSYS.lib/QSPRJOBQ.pgm">
<data name="receiver" type="struct" struct="jobq0200" usage="output"/>
<data name="receiverLength" type="int" length="4" usage="input" />
<data name="format" type="char" length="8" usage="input" init="JOBQ0200"/>
<data name="qualifiedJobQueueName" type="char" length="20" usage="input"/>
<data name="errorCode" type="int" length="4" usage="input" init="0"/>
</program>
</pcml>

View File

@ -0,0 +1,78 @@
<pcml version="1.0">
<!-- PCML source for calling "Open List of ASPs (QYASPOL) API" (QYASPOL) API -->
<!-- http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2Fapis%2Fqyaspol.htm -->
<!-- YASP0100 -->
<struct name="yasp0100">
<data name="aspNumber" type="int" length="4" />
<data name="resourceName" type="char" length="10" />
<data name="deviceDescriptionName" type="char" length="10" />
<data name="version" type="int" length="4" />
<data name="aspUsage" type="int" length="4" />
<data name="aspStatus" type="int" length="4" />
<data name="databaseName" type="char" length="18" />
<data name="primaryAspName" type="char" length="10" />
</struct>
<!-- List information structure (common for "Open List" type APIs) -->
<struct name="listInfo">
<data name="totalRcds" type="int" length="4" />
<data name="rcdsReturned" type="int" length="4" />
<data name="rqsHandle" type="byte" length="4" />
<data name="rcdLength" type="int" length="4" />
<data name="infoComplete" type="char" length="1" />
<data name="dateCreated" type="char" length="7" />
<data name="timeCreated" type="char" length="6" />
<data name="listStatus" type="char" length="1" />
<data type="byte" length="1" />
<data name="lengthOfInfo" type="int" length="4" />
<data name="firstRecord" type="int" length="4" />
<data type="byte" length="40" />
</struct>
<struct name="filterInformation" usage="input">
<data name="sizeOfFileEntry" type="int" length="4" init="16"/>
<data name="filterKey" type="int" length="4" init="1"/>
<data name="sizeOfFilterData" type="int" length="4" init="4"/>
<data name="filterData" type="int" length="4" init="1"/>
</struct>
<!-- Program QYASPOL and its parameter list-->
<program name="qyaspol" path="/QSYS.lib/QGY.lib/QYASPOL.pgm" parseorder="listInfo receiver">
<!-- 1 Receiver variable Output Char(*) -->
<data name="receiver" type="struct" struct="yasp0100" usage="output" count="listInfo.rcdsReturned" outputsize="receiverLength" />
<!-- 2 Length of receiver variable Input Binary(4) -->
<data name="receiverLength" type="int" length="4" usage="input" init="16384" />
<!-- 3 List information Output Char(80) -->
<data name="listInfo" type="struct" struct="listInfo" usage="output" />
<!-- 4 Number of records to return Input Binary(4) -->
<data name="rcdsToReturn" type="int" length="4" usage="input" init="264" />
<!-- 5 Number of filters Input Binary(4) -->
<data name="numberOfFilters" type="int" length="4" usage="input" init="1" />
<!-- 6 Filter information Input Char(*) -->
<data name="filterInfo" type="struct" struct="filterInformation" usage="input" />
<!-- 7 Format name Input Char(8) -->
<data name="format" type="char" length="8" usage="input" init="YASP0100" />
<!-- 8 Error Code I/O Char(*) -->
<data name="errorCode" type="int" length="4" usage="input" init="0" />
</program>
<!-- Program QGYGTLE returned additional "records" from the list created by QYASPOL. -->
<program name="qgygtle" path="/QSYS.lib/QGY.lib/QGYGTLE.pgm" parseorder="listInfo receiver">
<data name="receiver" type="struct" struct="yasp0100" usage="output" count="listInfo.rcdsReturned" outputsize="receiverLength" />
<data name="receiverLength" type="int" length="4" usage="input" init="16384" />
<data name="requestHandle" type="byte" length="4" usage="input" />
<data name="listInfo" type="struct" struct="listInfo" usage="output" />
<data name="rcdsToReturn" type="int" length="4" usage="input" init="264" />
<data name="startingRcd" type="int" length="4" usage="input" />
<data name="errorCode" type="int" length="4" usage="input" init="0" />
</program>
<!-- Program QGYCLST closes the list, freeing resources on the server -->
<program name="qgyclst" path="/QSYS.lib/QGY.lib/QGYCLST.pgm" >
<data name="requestHandle" type="byte" length="4" usage="input" />
<data name="errorCode" type="int" length="4" usage="input" init="0" />
</program>
</pcml>

View File

@ -0,0 +1,151 @@
<pcml version="1.0">
<!-- PCML source for calling "Open List of ASPs (QYASPOL) API" (QYASPOL) API -->
<!-- http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2Fapis%2Fqyaspol.htm -->
0 0 BINARY(4) ASP number
4 4 CHAR(4) Disk type
8 8 CHAR(4) Disk model
12 C CHAR(10) Disk serial number
22 16 CHAR(10) Resource name
32 20 BINARY(4) Disk unit number
36 24 BINARY(4) Disk capacity
40 28 BINARY(4) Disk storage available
44 2C BINARY(4) Disk storage reserved for system
48 30 CHAR(1) Mirrored unit protected
49 31 CHAR(1) Mirrored unit reported
50 32 CHAR(1) Mirrored unit status
51 33 CHAR(1) Reserved
52 34 BINARY(4) Unit control
56 38 BINARY(4) Blocks transferred to main storage
60 3C BINARY(4) Blocks transferred from main storage
64 40 BINARY(4) Requests for data transfer to main storage
68 44 BINARY(4) Requests for data transfer from main storage
72 48 BINARY(4) Permanent blocks transferred from main storage
76 4C BINARY(4) Requests for permanent data transfer from main storage
80 50 BINARY(4) Sample count
84 64 BINARY(4) Not busy count
88 68 CHAR(1) Compression status
89 69 CHAR(1) Disk protection type
90 6A CHAR(1) Compressed unit
91 6B CHAR(1) Storage allocation restricted unit
92 6C CHAR(1) Availability parity set unit
93 6D CHAR(1) Multiple connection unit
<!-- YASP0300 -->
<struct name="yasp0300">
<data name="aspNumber" type="int" length="4" />
<data name="diskType" type="char" length="4" />
<data name="diskModel" type="char" length="4" />
<data name="diskSerialNumber" type="char" length="10" />
<data name="resourceName" type="char" length="10" />
<data name="diskUnitNumber" type="int" length="4" />
<data name="diskCapacity" type="int" length="4" />
<data name="diskStorageAvailable" type="int" length="4" />
<data name="diskStorageReservedForSystem" type="int" length="4" />
<data name="mirroredUnitProtected" type="char" length="1" />
<data name="mirroredUnitReported" type="char" length="1" />
<data name="mirroredUnitStatus" type="char" length="1" />
<data name="reserved" type="char" length="1" />
<data name="unitControl" type="int" length="4" />
<data name="blockTransferredToMainStorage" type="int" length="4" />
<data name="blockTransferredFromMainStorage" type="int" length="4" />
<data name="requestForDataToMainStorage" type="int" length="4" />
<data name="requestForDataForMainStorage" type="int" length="4" />
<data name="requestForPermanentFromMainStorage" type="int" length="4" />
<data name="sampleCount" type="int" length="4" />
<data name="notBusyCount" type="int" length="4" />
<data name="compressionStatus" type="char" length="1" />
<data name="diskProtectionType" type="char" length="1" />
<data name="compressedUnit" type="char" length="1" />
<data name="storageAllocationRestrictedUnit" type="char" length="1" />
<data name="availabilityParitySetUnit" type="char" length="1" />
<data name="multipleConnectionUnit" type="char" length="1" />
</struct>
0 0 BINARY(4) Total records
4 4 BINARY(4) Records returned
8 8 CHAR(4) Request handle
12 C BINARY(4) Record length
16 10 CHAR(1) Information complete indicator
17 11 CHAR(13) Date and time created
30 1E CHAR(1) List status indicator
31 1F CHAR(1) Reserved
32 20 BINARY(4) Length of information returned
36 24 BINARY(4) First record in receiver variable
40 28 CHAR(40) Reserved
<!-- List information structure (common for "Open List" type APIs) -->
<struct name="listInfo">
<data name="totalRcds" type="int" length="4" />
<data name="rcdsReturned" type="int" length="4" />
<data name="rqsHandle" type="byte" length="4" />
<data name="rcdLength" type="int" length="4" />
<data name="infoComplete" type="char" length="1" />
<data name="dateCreated" type="char" length="7" />
<data name="timeCreated" type="char" length="6" />
<data name="listStatus" type="char" length="1" />
<data type="byte" length="1" />
<data name="lengthOfInfo" type="int" length="4" />
<data name="firstRecord" type="int" length="4" />
<data type="byte" length="40" />
</struct>
<struct name="filterInformation" usage="input">
<data name="sizeOfFileEntry" type="int" length="4" init="16"/>
<data name="filterKey" type="int" length="4" init="1"/>
<data name="sizeOfFilterData" type="int" length="4" init="4"/>
<data name="filterData" type="int" length="4" init="1"/>
</struct>
<!-- Program QYASPOL and its parameter list-->
<program name="qyaspol" path="/QSYS.lib/QGY.lib/QYASPOL.pgm" parseorder="listInfo receiver">
<!-- 1 Receiver variable Output Char(*) -->
<data name="receiver" type="struct" struct="yasp0300" usage="output" count="listInfo.rcdsReturned" outputsize="receiverLength" />
<!-- 2 Length of receiver variable Input Binary(4) -->
<data name="receiverLength" type="int" length="4" usage="input" init="94" />
<!-- 3 List information Output Char(80) -->
<data name="listInfo" type="struct" struct="listInfo" usage="output" />
<!-- 4 Number of records to return Input Binary(4) -->
<data name="rcdsToReturn" type="int" length="4" usage="input" init="264" />
<!-- 5 Number of filters Input Binary(4) -->
<data name="numberOfFilters" type="int" length="4" usage="input" init="1" />
<!-- 6 Filter information Input Char(*) -->
<data name="filterInfo" type="struct" struct="filterInformation" usage="input" />
<!-- 7 Format name Input Char(8) -->
<data name="format" type="char" length="8" usage="input" init="YASP0300" />
<!-- 8 Error Code I/O Char(*) -->
<data name="errorCode" type="int" length="4" usage="input" init="0" />
</program>
1 Receiver variable Output Char(*)
2 Length of receiver variable Input Binary(4)
3 Request handle Input Char(4)
4 List information Output Char(80)
5 Number of records to return Input Binary(4)
6 Starting record Input Binary(4)
7 Error code I/O Char(*)
<!-- Program QGYGTLE returned additional "records" from the list created by QYASPOL. -->
<program name="qgygtle" path="/QSYS.lib/QGY.lib/QGYGTLE.pgm" parseorder="listInfo receiver">
<data name="receiver" type="struct" struct="yasp0300" usage="output" count="listInfo.rcdsReturned" outputsize="receiverLength" />
<data name="receiverLength" type="int" length="4" usage="input" init="94" />
<data name="requestHandle" type="byte" length="4" usage="input" />
<data name="listInfo" type="struct" struct="listInfo" usage="output" />
<data name="rcdsToReturn" type="int" length="4" usage="input" init="264" />
<data name="startingRcd" type="int" length="4" usage="input" />
<data name="errorCode" type="int" length="4" usage="input" init="0" />
</program>
<!-- Program QGYCLST closes the list, freeing resources on the server -->
<program name="qgyclst" path="/QSYS.lib/QGY.lib/QGYCLST.pgm" >
<data name="requestHandle" type="byte" length="4" usage="input" />
<data name="errorCode" type="int" length="4" usage="input" init="0" />
</program>
</pcml>

View File

@ -0,0 +1,195 @@
/////////////////////////////////////////////////////////////////////////
//
// Program call example. This program calls the QWCRSSTS server program
// to retrieve the status of the system.
//
// Command syntax:
// PCSystemStatusExample system
//
// This source is an example of IBM Toolbox for Java "ProgramCall".
//
/////////////////////////////////////////////////////////////////////////
package com.centreon.connector.as400;
import com.ibm.as400.access.*;
public class IbmTest extends Object {
public static void main(String[] parameters) {
System.out.println(" ");
// if a system was not specified, display help text and exit.
if (parameters.length >= 3) {
try {
// Create an AS400 object for the server that contains the
// program. Assume the parameters are the system name, the login
// and the password.
AS400 as400 = new AS400(parameters[0], parameters[1], parameters[2]);
// Create the path to the program.
QSYSObjectPathName programName = new QSYSObjectPathName("QSYS", "QWCRSSTS", "PGM");
// Create the program call object. Assocate the object with the
// AS400 object that represents the server we get status from.
ProgramCall getSystemStatus = new ProgramCall(as400);
// Create the program parameter list. This program has five
// parameters that will be added to this list.
ProgramParameter[] parmlist = new ProgramParameter[5];
// The server program returns data in parameter 1. It is an output
// parameter. Allocate 64 bytes for this parameter.
parmlist[0] = new ProgramParameter(64);
// Parameter 2 is the buffer size of parm 1. It is a numeric input
// parameter. Sets its value to 64, convert it to the server format,
// then add the parm to the parm list.
AS400Bin4 bin4 = new AS400Bin4();
Integer iStatusLength = 64;
byte[] statusLength = bin4.toBytes(iStatusLength);
parmlist[1] = new ProgramParameter(statusLength);
// Parameter 3 is the status-format parameter. It is a string input
// parameter. Set the string value, convert it to the server format,
// then add the parameter to the parm list.
AS400Text text1 = new AS400Text(8, as400);
byte[] statusFormat = text1.toBytes("SSTS0200");
parmlist[2] = new ProgramParameter(statusFormat);
// Parameter 4 is the reset-statistics parameter. It is a string input
// parameter. Set the string value, convert it to the server format,
// then add the parameter to the parm list.
AS400Text text3 = new AS400Text(10, as400);
byte[] resetStats = text3.toBytes("*NO ");
parmlist[3] = new ProgramParameter(resetStats);
// Parameter 5 is the error info parameter. It is an input/output
// parameter. Add it to the parm list.
byte[] errorInfo = new byte[32];
parmlist[4] = new ProgramParameter(errorInfo, 0);
// Set the program to call and the parameter list to the program
// call object.
getSystemStatus.setProgram(programName.getPath(), parmlist);
// Run the program then sleep. We run the program twice because
// the first set of results are inflated. If we discard the first
// set of results and run the command again five seconds later the
// number will be more accurate.
getSystemStatus.run();
Thread.sleep(5000);
// Run the program
if (getSystemStatus.run() != true) {
// If the program did not run get the list of error messages
// from the program object and display the messages. The error
// would be something like program-not-found or not-authorized
// to the program.
AS400Message[] msgList = getSystemStatus.getMessageList();
System.out.println("The program did not run. Server messages:");
for (int i = 0; i < msgList.length; i++) {
System.out.println(msgList[i].getText());
}
}
// Else the program did run.
else {
// Create a server to Java numeric converter. This converter
// will be used in the following section to convert the numeric
// output from the server format to Java format.
AS400Bin4 as400Int = new AS400Bin4();
// Get the results of the program. Output data is in
// a byte array in the first parameter.
byte[] as400Data = parmlist[0].getOutputData();
// CPU utilization is a numeric field starting at byte
// 32 of the output buffer. Convert this number from the
// server format to Java format and output the number.
Integer cpuUtil = (Integer) as400Int.toObject(as400Data, 32);
cpuUtil = cpuUtil.intValue() / 10;
System.out.print("CPU Utilization: ");
System.out.print(cpuUtil);
System.out.println("%");
// DASD utilization is a numeric field starting at byte
// 52 of the output buffer. Convert this number from the
// server format to Java format and output the number.
Integer dasdUtil = (Integer) as400Int.toObject(as400Data, 52);
dasdUtil = dasdUtil.intValue() / 10000;
System.out.print("Dasd Utilization: ");
System.out.print(dasdUtil);
System.out.println("%");
// Number of jobs is a numeric field starting at byte
// 36 of the output buffer. Convert this number from the
// server format to Java format and output the number.
Integer nj = (Integer) as400Int.toObject(as400Data, 36);
System.out.print("Active jobs: ");
System.out.println(nj);
}
// This program is done running program so disconnect from
// the command server on the server. Program call and command
// call use the same server on the server.
as400.disconnectService(AS400.COMMAND);
} catch (Exception e) {
// If any of the above operations failed say the program failed
// and output the exception.
System.out.println("Program call failed");
System.out.println(e);
}
}
// Display help text when parameters are incorrect.
else {
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Parameters are not correct. Command syntax is:");
System.out.println("");
System.out.println(" PCSystemStatusExample myServer myLogin myPassword");
System.out.println("");
System.out.println("Where");
System.out.println("");
System.out.println(" myServer = get status of this server ");
System.out.println("");
System.out.println("For example:");
System.out.println("");
System.out.println(" PCSystemStatusExample mySystem myUser myUserPwd");
System.out.println("");
System.out.println("");
}
System.exit(0);
}
}

View File

@ -0,0 +1,34 @@
// package com.centreon.connector.as400.check.handler.impl;
//
// import static org.junit.Assert.*;
//
// import org.junit.After;
// import org.junit.AfterClass;
// import org.junit.Before;
// import org.junit.BeforeClass;
// import org.junit.Test;
//
// public class JobHandlerTest {
//
// @BeforeClass
// public static void setUpBeforeClass() throws Exception {
// }
//
// @AfterClass
// public static void tearDownAfterClass() throws Exception {
// }
//
// @Before
// public void setUp() throws Exception {
// }
//
// @After
// public void tearDown() throws Exception {
// }
//
// @Test
// public void test() {
// fail("Not yet implemented");
// }
//
// }

View File

@ -0,0 +1,60 @@
package com.centreon.connector.as400.check.handler.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.ArrayList;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
import com.ibm.as400.access.SystemStatus;
import com.centreon.connector.as400.Conf;
import com.centreon.connector.as400.dispatcher.check.ResponseData;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class SystemHandlerTest {
private AtomicInteger runs = new AtomicInteger(0);
@Test
public void dumpAll_should_print_measures() throws Exception {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
PrintStream originalOut = System.out;
System.setOut(new PrintStream(outContent));
try {
SystemStatus as400 = mock(SystemStatus.class);
when(as400.getSystemPools()).thenReturn(new Vector<Object>().elements());
SystemHandler sh = new SystemHandler(null, null, null, as400);
sh.dumpSystem();
} finally {
System.setOut(originalOut);
}
assertEquals(DUMP_OUTPUT_EXPECTED, outContent.toString());
}
private final String DUMP_OUTPUT_EXPECTED = "ActiveJobsInSystem : 0\nActiveThreadsInSystem : 0\n"
+ "BatchJobsEndedWithPrinterOutputWaitingToPrint : 0\nBatchJobsEnding : 0\nBatchJobsHeldOnJobQueue : 0\n"
+ "BatchJobsHeldWhileRunning : 0\nBatchJobsOnAHeldJobQueue : 0\nBatchJobsOnUnassignedJobQueue : 0\nBatchJobsRunning : 0\n"
+ "BatchJobsWaitingForMessage : 0\nBatchJobsWaitingToRunOrAlreadyScheduled : 0\nCurrentProcessingCapacity : 0.0\n"
+ "CurrentUnprotectedStorageUsed : 0\nDateAndTimeStatusGathered : null\nElapsedTime : 0\nJobsInSystem : 0\nMainStorageSize : 0\n"
+ "MaximumJobsInSystem : 0\nMaximumUnprotectedStorageUsed : 0\nNumberOfPartitions : 0\nNumberOfProcessors : 0\nPartitionIdentifier : 0\n"
+ "PercentCurrentInteractivePerformance : 0.0\nPercentDBCapability : 0.0\nPercentPermanent256MBSegmentsUsed : 0.0\n"
+ "PercentPermanent4GBSegmentsUsed : 0.0\nPercentPermanentAddresses : 0.0\nPercentProcessingUnitUsed : 0.0\n"
+ "PercentSharedProcessorPoolUsed : 0.0\nPercentSystemASPUsed : 0.0\nPercentTemporary256MBSegmentsUsed : 0.0\n"
+ "PercentTemporary4GBSegmentsUsed : 0.0\nPercentTemporaryAddresses : 0.0\nPercentUncappedCPUCapacityUsed : 0.0\n"
+ "PoolsNumber : 0\nProcessorSharingAttribute : 0\nRestrictedStateFlag : false\nSystem : null\nSystemASP : 0 Mbytes\n"
+ "SystemName : null\nTotalAuxiliaryStorage : 0\nUsersCurrentSignedOn : 0\nUsersSignedOffWithPrinterOutputWaitingToPrint : 0\n"
+ "UsersSuspendedByGroupJobs : 0\nUsersSuspendedBySystemRequest : 0\nUsersTemporarilySignedOff : 0\n";
}

View File

@ -0,0 +1,37 @@
// package com.centreon.connector.as400.check.handler.msgqueue;
//
// import org.junit.After;
// import org.junit.AfterClass;
// import org.junit.Before;
// import org.junit.BeforeClass;
// import org.junit.Test;
// import org.mockito.Mockito;
//
// import com.ibm.as400.access.QueuedMessage;
//
// public class CachedMessageQueueHandlerTest {
//
// @BeforeClass
// public static void setUpBeforeClass() throws Exception {
// }
//
// @AfterClass
// public static void tearDownAfterClass() throws Exception {
// }
//
// @Before
// public void setUp() throws Exception {
// }
//
// @After
// public void tearDown() throws Exception {
// }
//
// @Test
// public void test() {
// new CachedMessageQueueHandler("localhost", "toto", "tutu");
//
// Mockito.mock(QueuedMessage.class);
// }
//
// }

View File

@ -0,0 +1,61 @@
//package com.centreon.connector.as400.check.handler.msgqueue;
//
//import java.sql.Date;
//import java.sql.SQLException;
//import java.util.Calendar;
//
//import org.junit.After;
//import org.junit.AfterClass;
//import org.junit.Before;
//import org.junit.BeforeClass;
//import org.junit.Test;
//import org.mockito.Mockito;
//
//import com.ibm.as400.access.QueuedMessage;
//
//public class LocalDbTest {
//
// @BeforeClass
// public static void setUpBeforeClass() throws Exception {
// }
//
// @AfterClass
// public static void tearDownAfterClass() throws Exception {
// }
//
// @Before
// public void setUp() throws Exception {
// }
//
// @After
// public void tearDown() throws Exception {
// }
//
// private QueuedMessage createMockedObject(final String msgId, final int severity, final String text, final int type, final String user, final Date date,
// final Date createDate) {
//
// final QueuedMessage msg = Mockito.mock(QueuedMessage.class);
// Mockito.when(msg.getID()).thenReturn(msgId);
// Mockito.when(msg.getSeverity()).thenReturn(severity);
// Mockito.when(msg.getText()).thenReturn(text);
// Mockito.when(msg.getType()).thenReturn(type);
// Mockito.when(msg.getUser()).thenReturn(user);
// Mockito.when(msg.getDate()).thenReturn(new Calendar.Builder().setDate(1, 1, 1).build());
// Mockito.when(msg.getCreateDate()).thenReturn(createDate);
//
// return msg;
// }
//
// @Test
// public void testAddEntry() throws SQLException {
// final LocalDb db = new LocalDb("/tmp/test123");
// final QueuedMessage msg = this.createMockedObject("123", 5, "This is an output", 2, "user", new Date(0), new Date(0));
// db.addEntry(msg);
// }
//
// @Test
// public void testGetQueuedMessage() {
// // Assert.fail("Not yet implemented");
// }
//
//}

View File

@ -0,0 +1,53 @@
// package com.centreon.connector.as400.client;
//
// import java.io.IOException;
//
// import org.junit.After;
// import org.junit.AfterClass;
// import org.junit.Before;
// import org.junit.BeforeClass;
// import org.junit.Test;
// import org.mockito.Mockito;
//
// import com.ibm.as400.access.AS400SecurityException;
// import com.centreon.connector.as400.client.impl.CommandLineClient;
// import com.centreon.connector.as400.daemon.DelayedConnectionException;
// import com.centreon.connector.as400.dispatcher.check.CheckDispatcher;
// import com.centreon.connector.as400.dispatcher.check.CheckHandlerRunnable;
//
// public class TestClient {
// @BeforeClass
// public static void setUpBeforeClass() throws Exception {
// }
//
// @AfterClass
// public static void tearDownAfterClass() throws Exception {
// }
//
// @Before
// public void setUp() throws Exception {
//
// }
//
// @After
// public void tearDown() throws Exception {
// }
//
// @Test
// public void testCommandLine() throws AS400SecurityException, IOException,
// DelayedConnectionException, Exception {
// final String args[] = { "-I", "-H", "localhost", "--login", "test",
// "--password", "test", "-C", "cpu", "-A", "80,90" };
// final IClient client = new CommandLineClient(args);
// // ClientDispatcherImpl.getInstance().dispatch(client);
//
// final CheckDispatcher dispatcher = Mockito.mock(CheckDispatcher.class);
//
// final CheckHandlerRunnable runnable = new CheckHandlerRunnable(client,
// dispatcher);
// runnable.run();
// // final CheckDispatcher checkDispatcher = new
// // CheckDispatcher("localhost", "test", "test");
// // checkDispatcher.dispatch(client);
// }
// }

View File

@ -0,0 +1,144 @@
package com.centreon.connector.as400.dispatcher.check;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.centreon.connector.as400.check.handler.ICommandHandler;
import com.centreon.connector.as400.check.handler.IDiskHandler;
import com.centreon.connector.as400.check.handler.IJobHandler;
import com.centreon.connector.as400.check.handler.IJobQueueHandler;
import com.centreon.connector.as400.check.handler.IMessageQueueHandler;
import com.centreon.connector.as400.check.handler.ISubSystemHandler;
import com.centreon.connector.as400.check.handler.ISystemHandler;
public class TestCheckHandlerRunnable extends CheckHandlerRunnable {
public TestCheckHandlerRunnable() {
super(null, null);
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
new ResponseData(ResponseData.statusOk, "OK");
final ISubSystemHandler subSystemHandler = Mockito.mock(ISubSystemHandler.class, new Answer<ResponseData>() {
@Override
public ResponseData answer(final InvocationOnMock invocation) throws Throwable {
return new ResponseData(ResponseData.statusOk, "OK");
}
});
final ISystemHandler systemHandler = Mockito.mock(ISystemHandler.class, new Answer<ResponseData>() {
@Override
public ResponseData answer(final InvocationOnMock invocation) throws Throwable {
return new ResponseData(ResponseData.statusOk, "OK");
}
});
final IJobHandler jobHandler = Mockito.mock(IJobHandler.class, new Answer<ResponseData>() {
@Override
public ResponseData answer(final InvocationOnMock invocation) throws Throwable {
return new ResponseData(ResponseData.statusOk, "OK");
}
});
final IDiskHandler diskHandler = Mockito.mock(IDiskHandler.class, new Answer<ResponseData>() {
@Override
public ResponseData answer(final InvocationOnMock invocation) throws Throwable {
return new ResponseData(ResponseData.statusOk, "OK");
}
});
final ICommandHandler commandHandler = Mockito.mock(ICommandHandler.class, new Answer<ResponseData>() {
@Override
public ResponseData answer(final InvocationOnMock invocation) throws Throwable {
return new ResponseData(ResponseData.statusOk, "OK");
}
});
final IMessageQueueHandler messageQueueHandler = Mockito.mock(IMessageQueueHandler.class,
new Answer<ResponseData>() {
@Override
public ResponseData answer(final InvocationOnMock invocation) throws Throwable {
return new ResponseData(ResponseData.statusOk, "OK");
}
});
final IJobQueueHandler jobQueueHandler = Mockito.mock(IJobQueueHandler.class, new Answer<ResponseData>() {
@Override
public ResponseData answer(final InvocationOnMock invocation) throws Throwable {
return new ResponseData(ResponseData.statusOk, "OK");
}
});
this.checkDispatcher = Mockito.mock(CheckDispatcher.class);
Mockito.when(this.checkDispatcher.getJobHandler()).thenReturn(jobHandler);
Mockito.when(this.checkDispatcher.getCommandHandler()).thenReturn(commandHandler);
Mockito.when(this.checkDispatcher.getSubSystemHandler()).thenReturn(subSystemHandler);
Mockito.when(this.checkDispatcher.getDiskHandler()).thenReturn(diskHandler);
Mockito.when(this.checkDispatcher.getSystemHandler()).thenReturn(systemHandler);
Mockito.when(this.checkDispatcher.getMessageQueueHandler()).thenReturn(messageQueueHandler);
Mockito.when(this.checkDispatcher.getJobQueueHandler()).thenReturn(jobQueueHandler);
}
@After
public void tearDown() throws Exception {
}
private void testCommand(final String command, final int exceptedStatus) {
final ResponseData data = this.handleAs400Args(command);
Assert.assertEquals(data.getMessage(), exceptedStatus, data.getCode());
}
@Test
public void testListDisks() throws NumberFormatException, Exception {
this.testCommand("listDisks", ResponseData.statusError);
}
@Test
public void testListSubsystems() throws NumberFormatException, Exception {
this.testCommand("listSubsystems", ResponseData.statusOk);
}
@Test
public void testListJobs() throws NumberFormatException, Exception {
this.testCommand("listJobs", ResponseData.statusOk);
}
@Test
public void testGetErrorMessageQueue() throws NumberFormatException, Exception {
this.testCommand("getErrorMessageQueue", ResponseData.statusError);
}
@Test
public void testPageFault() throws NumberFormatException, Exception {
this.testCommand("pageFault", ResponseData.statusOk);
}
@Test
public void testGetJobQueues() throws NumberFormatException, Exception {
this.testCommand("getJobQueues", ResponseData.statusError);
}
@Test
public void testExecuteCommand() throws NumberFormatException, Exception {
this.testCommand("executeCommand", ResponseData.statusError);
}
@Test
public void testUnknown() throws NumberFormatException, Exception {
this.testCommand("blabla", ResponseData.statusError);
}
}

View File

@ -0,0 +1,39 @@
daemonListenerHost=localhost
#as400 login timeout for nagios check (ms)
as400LoginTimeout=10000
#as400 read timeout for nagios check (ms)
as400ReadTimeout=300000
#Time before cleaning an unused as400 resource (ms)
as400ResourceDuration=7200000
#time before killing a dead as400 connection (s)
as400SoLinger=1
#Duration of the job & (ms)
cacheTimeout=60000
daemonNoRequestTimeout=5000
daemonRequestParseTimeout=5000
#time before killing a dead as400 connection (s)
daemonSoLinger=1
#Time before discaring a check in queue (ms)
workerQueueTimeout=360000
# active debug
debug=false
# active exception
exception=false
# active trace (in /tmp/trace.log)
trace=false
# MessageQueueDB Base path
pathMsgQDB=/tmp/

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="console" target="System.err">
<PatternLayout pattern="[%-20d{dd/MM/yyyy HH:mm:ss}] [%-6p] %m %n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="org.apache.log4j.xml" level="info"/>
<Root level="error">
<AppenderRef ref="console"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,68 @@
name: "centreon-plugin-Operatingsystems-AS400-daemon"
arch: "${ARCH}"
platform: "linux"
version_schema: "none"
version: "2.0.2"
release: "${RELEASE}${DIST}"
section: "default"
priority: "optional"
maintainer: "Centreon <contact@centreon.com>"
description: |
Centreon Connector Server for AS400.
vendor: "Centreon"
homepage: "https://www.centreon.com"
license: "Apache-2.0"
contents:
- src: "../connector.as400/target/centreon-as400-2.0.2-jar-with-dependencies.jar" # VARIABLE VERSION REQUIRED HERE
dst: "/usr/share/centreon-as400/bin/centreon-as400-2.0.2-jar-with-dependencies.jar" # VARIABLE VERSION REQUIRED HERE
file_info:
mode: 0755
owner: "centreon-as400"
group: "centreon-as400"
- src: "../connector.as400.install/init-script/centreon-as400.service"
dst: "/lib/systemd/system/centreon-as400.service"
file_info:
mode: 0644
- src: "../connector.as400.install/init-script/centreon-as400-sysconfig"
dst: "/etc/sysconfig/centreon-as400-sysconfig"
file_info:
mode: 0644
- src: "../connector.as400.install/etc/config.properties"
dst: "/etc/centreon-as400/config.properties"
file_info:
mode: 0644
- src: "../connector.as400.install/etc/log4j2.xml"
dst: "/etc/centreon-as400/log4j2.xml"
file_info:
mode: 0644
- dst: "/var/log/centreon-as400"
type: dir
file_info:
mode: 0755
owner: centreon-as400
group: centreon-as400
scripts:
preinstall: ./scripts/centreon-as400-daemon-preinstall.sh
postinstall: ./scripts/centreon-as400-daemon-postinstall.sh
preremove: ./scripts/centreon-as400-daemon-preremove.sh
overrides:
rpm:
depends:
- java-1.8.0-openjdk
deb:
depends:
- default-jre
rpm:
summary: Centreon AS 400 Plugin daemon
signature:
key_file: ${RPM_SIGNING_KEY_FILE}
key_id: ${RPM_SIGNING_KEY_ID}

View File

@ -0,0 +1,5 @@
#!/bin/sh
# Start as400-daemon function
# Handle actions

View File

@ -0,0 +1,4 @@
#!/bin/sh
echo "Creating centreon-as400 user ..."
useradd -m -r centreon-as400 2> /dev/null ||:

View File

@ -0,0 +1,4 @@
#!/bin/sh
# Stop as400-daemon
systemctl stop centreon-as400