├── debian
├── compat
├── docs
├── source
│ ├── format
│ ├── options
│ └── lintian-overrides
├── install
├── control
├── default
├── rules
├── copyright
├── jmxproxy.yml.example
└── init
├── scripts
├── server
│ ├── access.txt
│ ├── passwd.txt
│ ├── jmxproxy.yml
│ └── start.sh
├── json_pretty.py
├── cacti
│ ├── ss_jmxproxy.php
│ └── ss_hadoop.php
├── graphite
│ ├── jmxproxy.py
│ └── hadoop.py
└── nagios
│ └── check_jmxproxy.py
├── src
├── test
│ ├── resources
│ │ ├── fixtures
│ │ │ ├── list_integer.json
│ │ │ ├── boxed_integer_array.json
│ │ │ ├── list_string.json
│ │ │ ├── boxed_boolean_array.json
│ │ │ ├── boxed_double_array.json
│ │ │ ├── list_list_integer.json
│ │ │ ├── list_list_string.json
│ │ │ ├── health_check_pass.json
│ │ │ ├── health_check_fail.json
│ │ │ ├── app_config.json
│ │ │ ├── web_config.json
│ │ │ └── multi_json_string.json
│ │ ├── logback.xml
│ │ └── main_config.yaml
│ └── java
│ │ └── com
│ │ └── github
│ │ └── mk23
│ │ └── jmxproxy
│ │ ├── tests
│ │ ├── AuthenticatedTests.java
│ │ └── JMXProxyApplicationTest.java
│ │ ├── conf
│ │ └── tests
│ │ │ └── AppConfigTest.java
│ │ ├── jmx
│ │ └── tests
│ │ │ ├── TimeoutRMISocketFactoryTest.java
│ │ │ ├── ConnectionCredentialsTest.java
│ │ │ └── ConnectionManagerTest.java
│ │ ├── core
│ │ └── tests
│ │ │ ├── HostTest.java
│ │ │ ├── MBeanTest.java
│ │ │ └── AttributeTest.java
│ │ └── util
│ │ └── tests
│ │ └── HistoryTest.java
├── main
│ ├── resources
│ │ ├── assets
│ │ │ ├── fonts
│ │ │ │ ├── fuelux.eot
│ │ │ │ ├── fuelux.ttf
│ │ │ │ ├── fuelux.woff
│ │ │ │ ├── glyphicons-halflings-regular.eot
│ │ │ │ ├── glyphicons-halflings-regular.ttf
│ │ │ │ ├── glyphicons-halflings-regular.woff
│ │ │ │ ├── glyphicons-halflings-regular.woff2
│ │ │ │ └── fuelux.svg
│ │ │ ├── img
│ │ │ │ └── favicon.ico
│ │ │ ├── webfonts
│ │ │ │ ├── fa-brands-400.eot
│ │ │ │ ├── fa-brands-400.ttf
│ │ │ │ ├── fa-solid-900.eot
│ │ │ │ ├── fa-solid-900.ttf
│ │ │ │ ├── fa-solid-900.woff
│ │ │ │ ├── fa-brands-400.woff
│ │ │ │ ├── fa-brands-400.woff2
│ │ │ │ ├── fa-regular-400.eot
│ │ │ │ ├── fa-regular-400.ttf
│ │ │ │ ├── fa-regular-400.woff
│ │ │ │ ├── fa-solid-900.woff2
│ │ │ │ └── fa-regular-400.woff2
│ │ │ ├── css
│ │ │ │ └── jmxproxy.css
│ │ │ └── js
│ │ │ │ ├── jquery.flot.resize.js
│ │ │ │ └── jquery.flot.time.js
│ │ ├── banner.txt
│ │ ├── versions.xml
│ │ └── checkstyle.xml
│ └── java
│ │ └── com
│ │ └── github
│ │ └── mk23
│ │ └── jmxproxy
│ │ ├── jmx
│ │ ├── package-info.java
│ │ ├── TimeoutRMISocketFactory.java
│ │ ├── ConnectionCredentials.java
│ │ ├── ConnectionWorker.java
│ │ └── ConnectionManager.java
│ │ ├── util
│ │ ├── package-info.java
│ │ └── History.java
│ │ ├── conf
│ │ ├── package-info.java
│ │ ├── MainConfig.java
│ │ ├── DurationSerializer.java
│ │ ├── DurationDeserializer.java
│ │ └── AppConfig.java
│ │ ├── package-info.java
│ │ ├── core
│ │ ├── package-info.java
│ │ ├── Host.java
│ │ ├── MBean.java
│ │ └── Attribute.java
│ │ ├── JMXProxyHealthCheck.java
│ │ └── JMXProxyApplication.java
└── site
│ └── site.xml
├── misc
├── mbeans.png
└── overview.png
├── .gitignore
├── LICENSE.txt
├── release.sh
└── .travis.yml
/debian/compat:
--------------------------------------------------------------------------------
1 | 7
2 |
--------------------------------------------------------------------------------
/debian/docs:
--------------------------------------------------------------------------------
1 | README.md
2 |
--------------------------------------------------------------------------------
/debian/source/format:
--------------------------------------------------------------------------------
1 | 3.0 (native)
2 |
--------------------------------------------------------------------------------
/scripts/server/access.txt:
--------------------------------------------------------------------------------
1 | ro readonly
2 |
--------------------------------------------------------------------------------
/scripts/server/passwd.txt:
--------------------------------------------------------------------------------
1 | ro public
2 |
--------------------------------------------------------------------------------
/src/test/resources/fixtures/list_integer.json:
--------------------------------------------------------------------------------
1 | [1, 2]
2 |
--------------------------------------------------------------------------------
/src/test/resources/fixtures/boxed_integer_array.json:
--------------------------------------------------------------------------------
1 | [1, 2]
2 |
--------------------------------------------------------------------------------
/debian/source/options:
--------------------------------------------------------------------------------
1 | tar-ignore = '.git'
2 | tar-ignore = '.m2'
3 |
--------------------------------------------------------------------------------
/src/test/resources/fixtures/list_string.json:
--------------------------------------------------------------------------------
1 | ["val1", "val2"]
2 |
--------------------------------------------------------------------------------
/src/test/resources/fixtures/boxed_boolean_array.json:
--------------------------------------------------------------------------------
1 | [true, false]
2 |
--------------------------------------------------------------------------------
/misc/mbeans.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/misc/mbeans.png
--------------------------------------------------------------------------------
/misc/overview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/misc/overview.png
--------------------------------------------------------------------------------
/src/test/resources/fixtures/boxed_double_array.json:
--------------------------------------------------------------------------------
1 | [1.23, "NaN", "Infinity", "Infinity"]
2 |
--------------------------------------------------------------------------------
/src/test/resources/fixtures/list_list_integer.json:
--------------------------------------------------------------------------------
1 | [
2 | [1, 2],
3 | [3, 4]
4 | ]
5 |
--------------------------------------------------------------------------------
/debian/install:
--------------------------------------------------------------------------------
1 | debian/jmxproxy.yml.example /etc
2 | target/jmxproxy-*.jar /usr/share/jmxproxy
3 |
--------------------------------------------------------------------------------
/src/test/resources/fixtures/list_list_string.json:
--------------------------------------------------------------------------------
1 | [
2 | ["val1", "val2"],
3 | ["val3", "val4"]
4 | ]
5 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target
2 | .DS_Store
3 | *.sw*
4 | *.pyc
5 | .m2
6 | debian/files
7 | debian/debhelper*
8 | debian/jmxproxy*
9 |
--------------------------------------------------------------------------------
/src/main/resources/assets/fonts/fuelux.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/fonts/fuelux.eot
--------------------------------------------------------------------------------
/src/main/resources/assets/fonts/fuelux.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/fonts/fuelux.ttf
--------------------------------------------------------------------------------
/src/main/resources/assets/img/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/img/favicon.ico
--------------------------------------------------------------------------------
/src/main/resources/assets/fonts/fuelux.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/fonts/fuelux.woff
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-brands-400.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-brands-400.eot
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-brands-400.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-brands-400.ttf
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-solid-900.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-solid-900.eot
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-solid-900.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-solid-900.ttf
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-solid-900.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-solid-900.woff
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-brands-400.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-brands-400.woff
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-brands-400.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-brands-400.woff2
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-regular-400.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-regular-400.eot
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-regular-400.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-regular-400.ttf
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-regular-400.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-regular-400.woff
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-solid-900.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-solid-900.woff2
--------------------------------------------------------------------------------
/src/main/resources/assets/webfonts/fa-regular-400.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/webfonts/fa-regular-400.woff2
--------------------------------------------------------------------------------
/src/test/java/com/github/mk23/jmxproxy/tests/AuthenticatedTests.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.tests;
2 |
3 | public interface AuthenticatedTests {}
4 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/jmx/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
Classes for handling JMX agent connections.
3 | */
4 | package com.github.mk23.jmxproxy.jmx;
5 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/util/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Utility classes for the entire application.
3 | */
4 | package com.github.mk23.jmxproxy.util;
5 |
--------------------------------------------------------------------------------
/src/main/resources/assets/fonts/glyphicons-halflings-regular.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/fonts/glyphicons-halflings-regular.eot
--------------------------------------------------------------------------------
/src/main/resources/assets/fonts/glyphicons-halflings-regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/fonts/glyphicons-halflings-regular.ttf
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/conf/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Classes for handling application configuration.
3 | */
4 | package com.github.mk23.jmxproxy.conf;
5 |
--------------------------------------------------------------------------------
/src/main/resources/assets/fonts/glyphicons-halflings-regular.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/fonts/glyphicons-halflings-regular.woff
--------------------------------------------------------------------------------
/src/main/resources/assets/fonts/glyphicons-halflings-regular.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mk23/jmxproxy/HEAD/src/main/resources/assets/fonts/glyphicons-halflings-regular.woff2
--------------------------------------------------------------------------------
/src/test/resources/fixtures/health_check_pass.json:
--------------------------------------------------------------------------------
1 | {
2 | "deadlocks": {
3 | "healthy": true
4 | },
5 | "manager": {
6 | "healthy": true
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Classes for handling main application lifecycle, resources, and health checks.
3 | */
4 | package com.github.mk23.jmxproxy;
5 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/core/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Classes for organizing and tracking core application objects for client retrieval.
3 | */
4 | package com.github.mk23.jmxproxy.core;
5 |
--------------------------------------------------------------------------------
/scripts/server/jmxproxy.yml:
--------------------------------------------------------------------------------
1 | jmxproxy:
2 | allowed_endpoints:
3 | - 'localhost:1123'
4 | history_size: 20
5 |
6 | logging:
7 | level: INFO
8 |
9 | loggers:
10 | "com.github.mk23.jmxproxy": DEBUG
11 |
--------------------------------------------------------------------------------
/src/test/resources/fixtures/health_check_fail.json:
--------------------------------------------------------------------------------
1 | {
2 | "deadlocks": {
3 | "healthy": true
4 | },
5 | "manager": {
6 | "healthy": false,
7 | "message": "connection manager is not started"
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/test/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | %-5level %-36logger{36} - %msg%n
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/src/test/resources/fixtures/app_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "cleanInterval": 12,
3 | "cacheDuration": 23000,
4 | "accessDuration": 404276000,
5 | "connectTimeout": 3000,
6 | "historySize": 11,
7 | "allowedEndpoints": [
8 | "localhost:1100",
9 | "remotehost:2211"
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/src/test/resources/fixtures/web_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "clean_interval": 12,
3 | "cache_duration": 23000,
4 | "access_duration": 404276000,
5 | "connect_timeout": 3000,
6 | "history_size": 11,
7 | "allowed_endpoints": [
8 | "localhost:1100",
9 | "remotehost:2211"
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/src/test/resources/fixtures/multi_json_string.json:
--------------------------------------------------------------------------------
1 | [
2 | null,
3 | true,
4 | 1,
5 | 1.23,
6 | "val",
7 | {
8 | "key1": [
9 | "val1",
10 | [
11 | 1,
12 | 2
13 | ]
14 | ],
15 | "key2": "val2"
16 | },
17 | [
18 | 1,
19 | 1.23
20 | ]
21 | ]
22 |
--------------------------------------------------------------------------------
/scripts/server/start.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -e
2 |
3 | cd $( (cd $(dirname $0) && echo $(pwd -P)) )
4 | exec java \
5 | -Xmx100m \
6 | -D'com.sun.management.jmxremote.port=1123' \
7 | -D'com.sun.management.jmxremote.ssl=false' \
8 | -D'com.sun.management.jmxremote.access.file=access.txt' \
9 | -D'com.sun.management.jmxremote.password.file=passwd.txt' \
10 | -jar ../../target/jmxproxy-3.4.0.jar server jmxproxy.yml
11 |
--------------------------------------------------------------------------------
/debian/source/lintian-overrides:
--------------------------------------------------------------------------------
1 | # erroneously detects missing source on javascript file
2 | source-is-missing src/main/resources/assets/js/jquery.flot.js line length *
3 | # erroneously detects missing source on javascript file
4 | source-is-missing src/main/resources/assets/js/jquery.flot.navigate.js line length *
5 | # erroneously detects missing source on javascript file
6 | source-is-missing src/main/resources/assets/js/jquery.flot.resize.js line length *
7 |
--------------------------------------------------------------------------------
/debian/control:
--------------------------------------------------------------------------------
1 | Source: jmxproxy
2 | Section: java
3 | Priority: extra
4 | Maintainer: Max Kalika
5 | Build-Depends: debhelper (>= 7), java8-sdk, maven, libxml-xpath-perl
6 | Standards-Version: 3.9.5
7 |
8 | Package: jmxproxy
9 | Architecture: all
10 | Depends: ${misc:Depends}, java8-runtime
11 | Description: JMX to HTTP proxy.
12 | JMXProxy exposes all available MBean attributes on a given JVM via
13 | simple HTTP request.
14 |
--------------------------------------------------------------------------------
/src/test/resources/main_config.yaml:
--------------------------------------------------------------------------------
1 | jmxproxy:
2 | access_duration: 300000
3 | allowed_endpoints:
4 | - 'localhost:1100'
5 | - 'remotehost:2211'
6 | cache_duration: '150s'
7 | clean_interval: '3m'
8 | history_size: 11
9 |
10 | logging:
11 | level: OFF
12 |
13 | server:
14 | requestLog:
15 | appenders: []
16 | applicationConnectors:
17 | - type: http
18 | port: 0
19 | adminConnectors:
20 | - type: http
21 | port: 0
22 |
--------------------------------------------------------------------------------
/debian/default:
--------------------------------------------------------------------------------
1 | # Set ENABLED to 1 if you want the init script to start jmxproxy.
2 | ENABLED=0
3 |
4 | # Run service as this user.
5 | #RUN_AS=nobody
6 |
7 | # Configuration file path. Must end with ".yml" or ".yaml" to be parsed as yaml otherwise it will be parsed as json.
8 | #CONF_FILE=/etc/jmxproxy.yml
9 |
10 | # Add extra java flags here.
11 | #JAVA_OPTS="-Xmx100m -Dcom.sun.management.jmxremote.port=1123 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"
12 |
--------------------------------------------------------------------------------
/src/main/resources/banner.txt:
--------------------------------------------------------------------------------
1 | __ __ __ __ __ ______ ______ ______ __ __ __ __
2 | /\ \ /\ "-./ \ /\_\_\_\ /\ == \ /\ == \ /\ __ \ /\_\_\_\ /\ \_\ \
3 | _\_\ \ \ \ \-./\ \ \/_/\_\/_ \ \ _-/ \ \ __< \ \ \/\ \ \/_/\_\/_ \ \____ \
4 | /\_____\ \ \_\ \ \_\ /\_\/\_\ \ \_\ \ \_\ \_\ \ \_____\ /\_\/\_\ \/\_____\
5 | \/_____/ \/_/ \/_/ \/_/\/_/ \/_/ \/_/ /_/ \/_____/ \/_/\/_/ \/_____/
6 |
7 |
--------------------------------------------------------------------------------
/debian/rules:
--------------------------------------------------------------------------------
1 | #!/usr/bin/make -f
2 | # -*- makefile -*-
3 | # Sample debian/rules that uses debhelper.
4 | # This file was originally written by Joey Hess and Craig Small.
5 | # As a special exception, when this file is copied by dh-make into a
6 | # dh-make output file, you may use that output file without restriction.
7 | # This special exception was added by Craig Small in version 0.37 of dh-make.
8 |
9 | VERSION=$(shell xpath -q -e '/project/version/text()' pom.xml)
10 | M2_REPO=$(CURDIR)/.m2
11 |
12 | export MAVEN_OPTS=-Duser.home=$(HOME) -Dmaven.repo.local=$(M2_REPO)
13 |
14 | %:
15 | dh $@
16 |
17 | override_dh_auto_configure:
18 | [ -d $(M2_REPO) ] || mkdir $(M2_REPO)
19 |
20 | override_dh_auto_build:
21 | mvn -B package
22 |
23 | override_dh_link:
24 | dh_link usr/share/jmxproxy/jmxproxy-$(VERSION).jar usr/share/jmxproxy/jmxproxy.jar
25 |
26 | override_dh_auto_clean:
27 | mvn -B clean
28 |
--------------------------------------------------------------------------------
/scripts/json_pretty.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 |
3 | import argparse
4 | import json
5 | import sys
6 |
7 | def parse(obj, path):
8 | for part in path.strip('/').split('/'):
9 | if part in obj:
10 | obj = obj[part]
11 |
12 | return obj
13 |
14 | if __name__ == '__main__':
15 | parser = argparse.ArgumentParser('json output prettyfier')
16 | parser.add_argument('-p', '--path', default='',
17 | help='path to the interesting object')
18 | parser.add_argument('-s', '--size', default=False, action='store_true',
19 | help='print size of the object instead')
20 | parser.add_argument('-f', '--file', default=sys.stdin, type=argparse.FileType(),
21 | help='file to use instead of stdin')
22 | args = parser.parse_args()
23 |
24 | item = parse(json.loads(args.file.read()), args.path)
25 |
26 | if args.size:
27 | print len(item)
28 | else:
29 | print json.dumps(item, indent=4)
30 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 | Copyright © 2011-2018 Max Kalika
3 |
4 | Permission is hereby granted, free of charge, to any person obtaining a copy
5 | of this software and associated documentation files (the "Software"), to deal
6 | in the Software without restriction, including without limitation the rights
7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | copies of the Software, and to permit persons to whom the Software is
9 | furnished to do so, subject to the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be included in
12 | all copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | THE SOFTWARE.
21 |
--------------------------------------------------------------------------------
/release.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -e
2 |
3 | BRANCH=$(git rev-parse --abbrev-ref HEAD)
4 | if [ "${BRANCH}" = "HEAD" ] ; then
5 | echo "Cannot release on detached HEAD. Please switch to a branch."
6 | exit 1
7 | fi
8 |
9 | read -p "Would you like to commit ${BRANCH} branch? [y/N] " -r
10 | if [[ $REPLY =~ ^[Yy]$ ]] ; then
11 | COMMIT=--commit
12 | fi
13 |
14 | echo
15 | (
16 | /usr/bin/curl -L -s https://raw.github.com/mk23/sandbox/master/misc/release.py ||
17 | echo 'raise Exception("unable to load release.py")'
18 | ) |
19 | exec /usr/bin/env python2.7 - ${COMMIT} --release xenial \
20 | -e pom.xml 'jmxproxy \s+{version} ' \
21 | -e README.md 'jmxproxy-{version}.jar' \
22 | -e README.md 'jmxproxy.{version}.tar.gz' \
23 | -e README.md '/download/jmxproxy.{version}/' \
24 | -e scripts/server/start.sh 'jmxproxy-{version}.jar' \
25 | "$@"
26 |
27 | if [ -n "${COMMIT}" ] ; then
28 | echo
29 | TAG=$(git describe --abbrev=0 --tags)
30 | echo "Created tag ${TAG}"
31 |
32 | for REMOTE in $(git remote -v | cut -f1 | uniq) ; do
33 | read -p "Would you like to push to ${REMOTE}? [y/N] " -r
34 | if [[ $REPLY =~ ^[Yy]$ ]] ; then
35 | git push "${REMOTE}" "${BRANCH}" "${TAG}"
36 | fi
37 | done
38 | fi
39 |
--------------------------------------------------------------------------------
/src/main/resources/assets/css/jmxproxy.css:
--------------------------------------------------------------------------------
1 | .banner-container {
2 | text-align: center;
3 | }
4 |
5 | .banner-container h1 {
6 | margin: 0;
7 | font-size: 8em;
8 | text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.6);
9 | }
10 |
11 | .banner-container h3 {
12 | text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.6);
13 | }
14 |
15 | .banner-container hr {
16 | width: 50%;
17 | border-top: 1px solid #f8f8f8;
18 | border-bottom: 1px solid rgba(0, 0, 0, 0.2);
19 | }
20 |
21 | .loader-wrapper {
22 | position: absolute;
23 | top: 50%;
24 | left: 50%;
25 | }
26 |
27 | .graph-tooltip {
28 | position: absolute;
29 | }
30 |
31 | div.overview-graph {
32 | width: 100%;
33 | height: 225px;
34 | }
35 |
36 | div.focused-graph {
37 | width: 100%;
38 | height: 450px;
39 | }
40 |
41 | div.progress {
42 | width: 100%;
43 | cursor: pointer;
44 | text-align: right;
45 | color: black;
46 | }
47 |
48 | div.tooltip-inner {
49 | max-width: 600px;
50 | }
51 |
52 | div.popover-content {
53 | word-wrap: break-word;
54 | }
55 |
56 | #endpoint-combo,
57 | #mbean-title,
58 | #attrib-name {
59 | font-weight: bold;
60 | font-family: monospace;
61 | }
62 |
63 | #mbean-reset {
64 | cursor: pointer;
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/JMXProxyHealthCheck.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy;
2 |
3 | import com.github.mk23.jmxproxy.jmx.ConnectionManager;
4 |
5 | import com.codahale.metrics.health.HealthCheck;
6 |
7 | /**
8 | * Service health check.
9 | *
10 | * Checks the state of the {@link ConnectionManager}.
11 | *
12 | * @since 2015-05-11
13 | * @author mk23
14 | * @version 3.2.0
15 | */
16 | public class JMXProxyHealthCheck extends HealthCheck {
17 | /**
18 | * Lifecycle {@link ConnectionManager} object that determines
19 | * the overall service status.
20 | */
21 | private final ConnectionManager manager;
22 |
23 | /**
24 | * Default constructor.
25 | *
26 | * Uses the {@link ConnectionManager} object to determine
27 | * service status when a health check is requested.
28 | *
29 | * @param manager of the endpoint cache.
30 | */
31 | public JMXProxyHealthCheck(final ConnectionManager manager) {
32 | this.manager = manager;
33 | }
34 |
35 | /** {@inheritDoc} */
36 | @Override
37 | protected final Result check() throws Exception {
38 | if (!manager.isStarted()) {
39 | return Result.unhealthy("connection manager is not started");
40 | }
41 | return Result.healthy();
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/conf/MainConfig.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.conf;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import io.dropwizard.Configuration;
6 |
7 | import javax.validation.Valid;
8 |
9 | /**
10 | * Main top-level configuration.
11 | *
12 | * Maintains the top-level application configuration object. The
13 | * application initializer creates and marshals the object from
14 | * JSON or Yaml config file.
15 | *
16 | * @since 2016-01-28
17 | * @author mk23
18 | * @version 3.2.1
19 | */
20 | public class MainConfig extends Configuration {
21 | /**
22 | * Application service config.
23 | */
24 | @Valid
25 | @JsonProperty("jmxproxy")
26 | private AppConfig appConfig = new AppConfig();
27 |
28 | /**
29 | * Getter for appConfig.
30 | *
31 | * Application service config.
32 | *
33 | * @return Application subsection from the full configuration file.
34 | */
35 | public final AppConfig getAppConfig() {
36 | return appConfig;
37 | }
38 | /**
39 | * Setter for appConfig.
40 | *
41 | * @param appConfig Application subsection from the full configuration file.
42 | */
43 | public final void setAppConfig(final AppConfig appConfig) {
44 | this.appConfig = appConfig;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/conf/DurationSerializer.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.conf;
2 |
3 | import com.fasterxml.jackson.core.JsonGenerator;
4 | import com.fasterxml.jackson.core.JsonProcessingException;
5 | import com.fasterxml.jackson.databind.JsonSerializer;
6 | import com.fasterxml.jackson.databind.SerializerProvider;
7 |
8 | import io.dropwizard.util.Duration;
9 |
10 | import java.io.IOException;
11 |
12 | /**
13 | * Custom serializer for configuration Duration fields.
14 | *
15 | * Converts io.dropwizard.util.Duration types to milliseconds
16 | * for JSON requests.
17 | *
18 | * @see io.dropwizard.util.Duration
19 | * @see com.fasterxml.jackson.databind.JsonSerializer
20 | *
21 | * @since 2016-01-29
22 | * @author mk23
23 | * @version 3.2.1
24 | */
25 | public class DurationSerializer extends JsonSerializer {
26 | /** {@inheritDoc} */
27 | @Override
28 | public final void serialize(
29 | final Duration duration,
30 | final JsonGenerator jgen,
31 | final SerializerProvider provider
32 | ) throws IOException, JsonProcessingException {
33 | jgen.writeNumber(duration.toMilliseconds());
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/debian/copyright:
--------------------------------------------------------------------------------
1 | Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2 | Upstream-Name: jmxproxy
3 | Source: https://github.com/mk23/jmxproxy
4 |
5 | Files: *
6 | Copyright: 2011-2018 Max Kalika
7 | License: MIT
8 |
9 | Files: debian/*
10 | Copyright: 2011-2018 Max Kalika
11 | License: MIT
12 |
13 | License: MIT
14 | Permission is hereby granted, free of charge, to any person obtaining a
15 | copy of this software and associated documentation files (the "Software"),
16 | to deal in the Software without restriction, including without limitation
17 | the rights to use, copy, modify, merge, publish, distribute, sublicense,
18 | and/or sell copies of the Software, and to permit persons to whom the
19 | Software is furnished to do so, subject to the following conditions:
20 | .
21 | The above copyright notice and this permission notice shall be included
22 | in all copies or substantial portions of the Software.
23 | .
24 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
25 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
27 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
28 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
29 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
30 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/conf/DurationDeserializer.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.conf;
2 |
3 | import com.fasterxml.jackson.core.JsonParser;
4 | import com.fasterxml.jackson.core.JsonProcessingException;
5 | import com.fasterxml.jackson.core.JsonToken;
6 | import com.fasterxml.jackson.databind.DeserializationContext;
7 | import com.fasterxml.jackson.databind.JsonDeserializer;
8 |
9 | import io.dropwizard.util.Duration;
10 |
11 | import java.io.IOException;
12 |
13 | /**
14 | * Custom deserializer for configuration Duration fields.
15 | *
16 | * Converts a String or Long into io.dropwizard.util.Duration types to milliseconds.
17 | *
18 | * @see io.dropwizard.util.Duration
19 | * @see com.fasterxml.jackson.databind.JsonDeserializer
20 | *
21 | * @since 2016-07-02
22 | * @author mk23
23 | * @version 3.3.3
24 | */
25 | public class DurationDeserializer extends JsonDeserializer {
26 | /** {@inheritDoc} */
27 | @Override
28 | public final Duration deserialize(
29 | final JsonParser jp,
30 | final DeserializationContext ctxt
31 | ) throws IOException, JsonProcessingException {
32 | return jp.getCurrentToken() == JsonToken.VALUE_NUMBER_INT
33 | ? Duration.milliseconds(jp.getValueAsLong())
34 | : Duration.parse(jp.getValueAsString());
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/resources/assets/fonts/fuelux.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Generated by Fontastic.me
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/src/site/site.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ${this.name}
6 |
7 |
8 | 67784002
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | org.apache.maven.skins
26 | maven-fluido-skin
27 | 1.5
28 |
29 |
30 |
31 |
32 | span3
33 | span9
34 |
35 | false
36 |
37 | true
38 |
39 | true
40 |
41 | pull-right
42 |
43 | |
44 |
45 |
46 | ${this.github.repo.name}
47 | right
48 | red
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 |
3 | language: java
4 | jdk:
5 | - oraclejdk8
6 |
7 | install:
8 | - 'chmod 0600 scripts/server/passwd.txt'
9 | script:
10 | - 'mvn -B clean package'
11 | after_success:
12 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && mvn coveralls:report'
13 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && git -C target/site init'
14 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && git -C target/site config user.name "$(curl -s https://api.github.com/user?access_token=${GH_OAUTH2} | jq .name)"'
15 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && git -C target/site config user.email "$(curl -s https://api.github.com/user?access_token=${GH_OAUTH2} | jq .email)"'
16 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && git -C target/site add .'
17 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && git -C target/site commit -m "Deploy site from https://travis-ci.org/${TRAVIS_REPO_SLUG}/builds/${TRAVIS_BUILD_ID}"'
18 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && git -C target/site push --force --quiet "https://${GH_OAUTH2}@github.com/${TRAVIS_REPO_SLUG}.git" master:gh-pages'
19 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" -a -n "${TRAVIS_TAG}" ] && git log --no-merges --format=" * [%h] %s\\r\\n" "$(git tag | grep -B1 ^${TRAVIS_TAG}$ | head -n1)..${TRAVIS_TAG}^" | paste -s --delimiters="" > __txt'
20 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" -a -n "${TRAVIS_TAG}" ] && printf ''{"tag_name":"%s","name":"JMXProxy %s","body":"%s"}'' "${TRAVIS_TAG}" "${TRAVIS_TAG#*.}" "$(< __txt)" > __req'
21 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" -a -n "${TRAVIS_TAG}" ] && curl -s https://api.github.com/repos/${TRAVIS_REPO_SLUG}/releases?access_token=${GH_OAUTH2} -XPOST --data-binary @__req > __res'
22 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" -a -n "${TRAVIS_TAG}" ] && curl -s "$(jq -r .upload_url __res | sed "s/{.*}//")?name=${TRAVIS_TAG/./-}.jar&access_token=${GH_OAUTH2}" -XPOST --data-binary @target/${TRAVIS_TAG/./-}.jar -H "Content-Type: application/zip" > __obj'
23 |
24 | branches:
25 | only:
26 | - master
27 | - /jmxproxy\..+/
28 |
29 | cache:
30 | directories:
31 | - $HOME/.m2
32 |
--------------------------------------------------------------------------------
/src/main/resources/versions.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | .*-(?:rc\d+|android)(?:-.*)?
7 |
8 |
9 |
10 |
11 | .*-rc\d+
12 |
13 |
14 |
15 |
16 | .*
17 |
18 |
19 |
20 |
21 | .*
22 |
23 |
24 |
25 |
26 | .*
27 |
28 |
29 |
30 |
31 | .*
32 |
33 |
34 |
35 |
36 | 6\..*
37 |
38 |
39 |
40 |
41 | .*-(?:alpha|beta)\d*
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/src/test/java/com/github/mk23/jmxproxy/conf/tests/AppConfigTest.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.conf.tests;
2 |
3 | import com.github.mk23.jmxproxy.conf.AppConfig;
4 |
5 | import com.fasterxml.jackson.core.JsonProcessingException;
6 | import com.fasterxml.jackson.databind.JsonNode;
7 | import com.fasterxml.jackson.databind.ObjectMapper;
8 |
9 | import io.dropwizard.util.Duration;
10 |
11 | import java.io.IOException;
12 |
13 | import java.util.Arrays;
14 |
15 | import org.junit.Before;
16 | import org.junit.Rule;
17 | import org.junit.Test;
18 | import org.junit.rules.TestName;
19 |
20 | import static org.hamcrest.core.Is.is;
21 | import static org.junit.Assert.assertThat;
22 |
23 | import static io.dropwizard.testing.FixtureHelpers.fixture;
24 |
25 | public class AppConfigTest {
26 | private final ObjectMapper om = new ObjectMapper();
27 |
28 | @Rule public TestName name = new TestName();
29 |
30 | private String asJson(Object object) throws JsonProcessingException {
31 | return om.writeValueAsString(object);
32 | }
33 |
34 | private String jsonFixture(String filename) throws IOException {
35 | return om.writeValueAsString(om.readValue(fixture(filename), JsonNode.class));
36 | }
37 |
38 | @Before
39 | public void printTestName() {
40 | System.out.println(" -> " + name.getMethodName());
41 | }
42 |
43 | /* Configuration tests */
44 | @Test
45 | public void checkValidConfiguration() throws Exception {
46 | final AppConfig appConfig = new AppConfig()
47 | .setCleanInterval(Duration.milliseconds(12))
48 | .setCacheDuration(Duration.seconds(23))
49 | .setAccessDuration(Duration.seconds(404276))
50 | .setConnectTimeout(Duration.seconds(3))
51 | .setHistorySize(11)
52 | .setAllowedEndpoints(Arrays.asList("localhost:1100", "remotehost:2211"));
53 |
54 | final String expectedResult = jsonFixture("fixtures/app_config.json");
55 | final String acquiredResult = asJson(appConfig);
56 |
57 | assertThat("valid configuration", acquiredResult, is(expectedResult));
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/debian/jmxproxy.yml.example:
--------------------------------------------------------------------------------
1 | #jmxproxy:
2 | # # how often for the cleaner thread to
3 | # # wake up to purge unaccessed hosts
4 | # # Time units: ns, us, ms, s, m, h, d
5 | # clean_interval: 1m
6 | #
7 | # # how long to keep unaccessed hosts before purging
8 | # # by the cleaner thread
9 | # access_duration: 5m
10 | #
11 | # # how long to cache JMX attribute values before
12 | # # reconnecting to the agent and pulling new data
13 | # cache_duration: 5m
14 | #
15 | # # how long to wait on a new JMX connection before
16 | # # giving up with a not found error to the client
17 | # connect_timeout: 3s
18 | #
19 | # # white list of allowed endpoints in host or host:port
20 | # # format for this agent to connect to, defaulting
21 | # # to allowing all when empty or missing
22 | # allowed_endpoints:
23 | # - 'localhost'
24 | # - 'host1:1234'
25 | # - 'host1:4321'
26 | # - 'host2:5678'
27 | #
28 | # # maximum number of historical attribute values to
29 | # # retain and provide when the history query parameter
30 | # # is specified to the attribute request call
31 | # history_size: 1
32 | #
33 | #server:
34 | # # simple server example where application and admin
35 | # # servlets listen on the same port.
36 | # # NOTE: it is important to override the application
37 | # # context path here or all requests will have to be
38 | # # prefixed with "/application" in the URI.
39 | # type: simple
40 | # applicationContextPath: /
41 | # connector:
42 | # type: http
43 | # port: 8000
44 | #
45 | # # use default server if application and admin servlets
46 | # # need to be separated on to different ports
47 | # type: default
48 | # applicationConnectors:
49 | # type: http
50 | # port: 8000
51 | # adminConnectors:
52 | # type: http
53 | # port: 8001
54 | #
55 | #logging:
56 | # # default logging set to INFO level
57 | # level: INFO
58 | #
59 | # # set jmxproxy classes to log at DEBUG level
60 | # loggers:
61 | # "com.github.mk23.jmxproxy": DEBUG
62 | #
63 | # # configure syslog host and facility
64 | # # the local syslog server will need listen on an inet socket
65 | # appenders:
66 | # - type: syslog
67 | # host: localhost
68 | # facility: local0
69 |
--------------------------------------------------------------------------------
/src/test/java/com/github/mk23/jmxproxy/jmx/tests/TimeoutRMISocketFactoryTest.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.jmx.tests;
2 |
3 | import com.github.mk23.jmxproxy.jmx.TimeoutRMISocketFactory;
4 |
5 | import java.net.BindException;
6 | import java.net.ConnectException;
7 | import java.net.SocketTimeoutException;
8 |
9 | import org.junit.Before;
10 | import org.junit.Rule;
11 | import org.junit.Test;
12 |
13 | import org.junit.rules.ExpectedException;
14 | import org.junit.rules.TestName;
15 |
16 | import static org.junit.Assert.assertNotNull;
17 |
18 | public class TimeoutRMISocketFactoryTest {
19 | private final String validHost = "localhost";
20 | private final String invalidHost = "192.0.2.1";
21 |
22 | private final int serverPort = Integer.getInteger("com.sun.management.jmxremote.port");
23 |
24 | private final int connectTimeout = 500;
25 |
26 | @Rule public ExpectedException thrown = ExpectedException.none();
27 | @Rule public TestName name = new TestName();
28 |
29 | @Before
30 | public void printTestName() {
31 | System.out.println(" -> " + name.getMethodName());
32 | }
33 |
34 | @Test
35 | public void checkClientValidHostValidPort() throws Exception {
36 | final TimeoutRMISocketFactory sf = new TimeoutRMISocketFactory(connectTimeout);
37 |
38 | assertNotNull(sf.createSocket(validHost, serverPort));
39 | }
40 |
41 | @Test(timeout=2000)
42 | public void checkClientInvalidHostValidPort() throws Exception {
43 | final TimeoutRMISocketFactory sf = new TimeoutRMISocketFactory(connectTimeout);
44 |
45 | thrown.expect(SocketTimeoutException.class);
46 | sf.createSocket(invalidHost, serverPort);
47 | }
48 |
49 | @Test
50 | public void checkClientValidHostInvalidPort() throws Exception {
51 | final TimeoutRMISocketFactory sf = new TimeoutRMISocketFactory(connectTimeout);
52 |
53 | thrown.expect(ConnectException.class);
54 | sf.createSocket(validHost, 0);
55 | }
56 |
57 | @Test
58 | public void checkServerValidPort() throws Exception {
59 | final TimeoutRMISocketFactory sf = new TimeoutRMISocketFactory(connectTimeout);
60 |
61 | assertNotNull(sf.createServerSocket(0));
62 | }
63 |
64 | @Test
65 | public void checkServerInvalidPort() throws Exception {
66 | final TimeoutRMISocketFactory sf = new TimeoutRMISocketFactory(connectTimeout);
67 |
68 | thrown.expect(BindException.class);
69 | sf.createServerSocket(serverPort);
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/jmx/TimeoutRMISocketFactory.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.jmx;
2 |
3 | import java.io.IOException;
4 |
5 | import java.net.InetSocketAddress;
6 | import java.net.Socket;
7 | import java.net.ServerSocket;
8 |
9 | import java.rmi.server.RMISocketFactory;
10 |
11 | import org.slf4j.Logger;
12 | import org.slf4j.LoggerFactory;
13 |
14 | /**
15 | * Remote Method Invocation socket factory with connection timeout.
16 | *
17 | * Extends RMISocketFactory to return a socket that implements a connection timeout,
18 | * preventing black-holed backend agents from piling up connections in the server.
19 | *
20 | * @see java.net.Socket
21 | * @see java.rmi.server.RMISocketFactory
22 | *
23 | * @since 2017-01-20
24 | * @author mk23
25 | * @version 3.3.6
26 | */
27 | public class TimeoutRMISocketFactory extends RMISocketFactory {
28 | private static final Logger LOG = LoggerFactory.getLogger(TimeoutRMISocketFactory.class);
29 |
30 | private int timeout;
31 |
32 | /**
33 | * Default constructor.
34 | *
35 | * Initializes the timeout to the specified value in milliseconds.
36 | *
37 | * @param timeout milliseconds to pass to Socket's connect() method.
38 | */
39 | public TimeoutRMISocketFactory(final int timeout) {
40 | super();
41 |
42 | this.timeout = timeout;
43 | }
44 |
45 | /**
46 | * Setter for timeout.
47 | *
48 | * Resets the timeout to the specified milliseconds value.
49 | *
50 | * @param timeout milliseconds to pass to Socket's connect() method.
51 | *
52 | * @return Modified TimeoutRMISocketFactory for setter chaining.
53 | */
54 | public final TimeoutRMISocketFactory setTimeout(final int timeout) {
55 | this.timeout = timeout;
56 | return this;
57 | }
58 |
59 | /** {@inheritDoc} */
60 | @Override
61 | public final Socket createSocket(final String host, final int port) throws IOException {
62 | LOG.debug("creating new socket with " + timeout + "ms timeout");
63 |
64 | Socket socket = new Socket();
65 | socket.connect(new InetSocketAddress(host, port), timeout);
66 |
67 | return socket;
68 | }
69 |
70 | /** {@inheritDoc} */
71 | @Override
72 | public final ServerSocket createServerSocket(final int port) throws IOException {
73 | return new ServerSocket(port);
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/debian/init:
--------------------------------------------------------------------------------
1 | #! /bin/sh
2 | ### BEGIN INIT INFO
3 | # Provides: jmxproxy
4 | # Required-Start: $remote_fs $syslog
5 | # Required-Stop: $remote_fs $syslog
6 | # Default-Start: 2 3 4 5
7 | # Default-Stop: 0 1 6
8 | # Short-Description: JMXProxy service
9 | # Description: Starts and stops the JMX to HTTP proxy
10 | # service.
11 | ### END INIT INFO
12 |
13 | # Author: Max Kalika
14 |
15 | PATH=/sbin:/usr/sbin:/bin:/usr/bin
16 | DESC="JMXProxy service"
17 | NAME=jmxproxy
18 | RUN_AS=nobody
19 | JAVA_HOME=/usr
20 | JAVA_OPTS=-Xmx256m
21 | PIDFILE=/var/run/${NAME}.pid
22 |
23 | # Read configuration variable file if it is present
24 | [ -r /etc/default/$NAME ] && . /etc/default/$NAME
25 |
26 | # Load the VERBOSE setting and other rcS variables
27 | . /lib/init/vars.sh
28 |
29 | # Define LSB log_* functions.
30 | . /lib/lsb/init-functions
31 |
32 | # Exit if the package is not installed
33 | [ -x "${JAVA_HOME}/bin/java" -a -f "/usr/share/${NAME}/${NAME}.jar" ] || exit 0
34 |
35 | # Exit if service is administratively disabled
36 | [ -n "$ENABLED" -a "$ENABLED" != "0" ] || exit 0
37 |
38 | do_start() {
39 | start-stop-daemon --start --quiet --pidfile $PIDFILE --test \
40 | --exec ${JAVA_HOME}/bin/java \
41 | || return 1
42 |
43 | start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile \
44 | --background --chuid ${RUN_AS} \
45 | --exec ${JAVA_HOME}/bin/java -- \
46 | $JAVA_OPTS -jar /usr/share/${NAME}/${NAME}.jar server $CONF_FILE \
47 | || return 2
48 |
49 | return 0
50 | }
51 |
52 | do_stop() {
53 | start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE
54 | RETVAL="$?"
55 |
56 | rm -f $PIDFILE
57 | return "$RETVAL"
58 | }
59 |
60 | case "$1" in
61 | start)
62 | [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC"
63 | do_start
64 | case "$?" in
65 | 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
66 | 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
67 | esac
68 | ;;
69 | stop)
70 | [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC"
71 | do_stop
72 | case "$?" in
73 | 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
74 | 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
75 | esac
76 | ;;
77 | status)
78 | status_of_proc -p $PIDFILE ${JAVA_HOME}/bin/java $NAME && exit 0 || exit $?
79 | ;;
80 | restart|force-reload)
81 | log_daemon_msg "Restarting $DESC"
82 | do_stop
83 | sleep 2
84 | case "$?" in
85 | 0|1)
86 | do_start
87 | case "$?" in
88 | 0) log_end_msg 0 ;;
89 | *) log_end_msg 1 ;; # Failed to start
90 | esac
91 | ;;
92 | *)
93 | # Failed to stop
94 | log_end_msg 1
95 | ;;
96 | esac
97 | ;;
98 | *)
99 | echo "Usage: $0 {start|stop|status|restart|force-reload}" >&2
100 | exit 3
101 | ;;
102 | esac
103 |
104 | :
105 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/JMXProxyApplication.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy;
2 |
3 | import com.github.mk23.jmxproxy.conf.MainConfig;
4 | import com.github.mk23.jmxproxy.jmx.ConnectionManager;
5 |
6 | import io.dropwizard.Application;
7 | import io.dropwizard.assets.AssetsBundle;
8 | import io.dropwizard.server.AbstractServerFactory;
9 | import io.dropwizard.setup.Bootstrap;
10 | import io.dropwizard.setup.Environment;
11 |
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | /**
16 | * JMXProxy main application.
17 | *
18 | * Configures application from {@link MainConfig}, initializes, and starts the service.
19 | *
20 | * @see io.dropwizard.Application
21 | * @see io.dropwizard.setup.Bootstrap
22 | * @see io.dropwizard.setup.Environment
23 | *
24 | * @since 2015-05-11
25 | * @author mk23
26 | * @version 3.2.0
27 | */
28 | public class JMXProxyApplication extends Application {
29 | private static final Logger LOG = LoggerFactory.getLogger(JMXProxyApplication.class);
30 |
31 | /**
32 | * main application entrypoint.
33 | *
34 | * Starts main application.
35 | *
36 | * @param args an array of {@link String} command-line parameters.
37 | *
38 | * @throws Exception if initialization fails.
39 | */
40 | public static void main(final String[] args) throws Exception {
41 | LOG.info("starting jmxproxy service");
42 | new JMXProxyApplication().run(args);
43 | }
44 |
45 | /** {@inheritDoc} */
46 | @Override
47 | public final String getName() {
48 | return "jmxproxy";
49 | }
50 |
51 | /** {@inheritDoc} */
52 | @Override
53 | public final void initialize(final Bootstrap bootstrap) {
54 | bootstrap.addBundle(new AssetsBundle("/assets/", "/", "index.html"));
55 | }
56 |
57 | /** {@inheritDoc} */
58 | @Override
59 | public final void run(final MainConfig configuration, final Environment environment) {
60 | final ConnectionManager manager = new ConnectionManager(configuration.getAppConfig());
61 | final JMXProxyResource resource = new JMXProxyResource(manager);
62 | final JMXProxyHealthCheck healthCheck = new JMXProxyHealthCheck(manager);
63 |
64 | ((AbstractServerFactory) configuration.getServerFactory()).setJerseyRootPath("/jmxproxy/*");
65 |
66 | environment.lifecycle().manage(manager);
67 | environment.jersey().register(resource);
68 | environment.healthChecks().register("manager", healthCheck);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/scripts/cacti/ss_jmxproxy.php:
--------------------------------------------------------------------------------
1 | array('java.lang:type=Threading', 'ThreadCount'),
17 | 'thread_peak' => array('java.lang:type=Threading', 'PeakThreadCount'),
18 | 'memory_heap_used' => array('java.lang:type=Memory', 'HeapMemoryUsage', 'used'),
19 | 'memory_heap_max' => array('java.lang:type=Memory', 'HeapMemoryUsage', 'max'),
20 | 'gc_count' => array('java.lang:type=GarbageCollector,name=.*', 'CollectionCount'),
21 | 'classes_loaded' => array('java.lang:type=ClassLoading', 'LoadedClassCount'),
22 | 'classes_total' => array('java.lang:type=ClassLoading', 'TotalLoadedClassCount'),
23 | 'classes_unloaded' => array('java.lang:type=ClassLoading', 'UnloadedClassCount'),
24 | );
25 |
26 | $stats = array_merge($jvm_stats, $extra_stats);
27 | if (!empty($jmxcreds)) {
28 | $cntxt = stream_context_create(array(
29 | 'http' => array(
30 | 'method' => 'POST',
31 | 'header' => 'Content-type: application/x-www-form-urlencoded',
32 | 'content' => http_build_query(array(
33 | 'username' => urldecode(array_shift(explode(':', $jmxcreds))),
34 | 'password' => urldecode(array_pop(explode(':', $jmxcreds))),
35 | )),
36 | ),
37 | ));
38 | } else {
39 | $cntxt = stream_context_create();
40 | }
41 |
42 | stream_context_set_option($cntxt, 'http', 'timeout', 10.0);
43 | $beans = json_decode(file_get_contents("{$jmxproxy}/{$host}", FILE_USE_INCLUDE_PATH, $cntxt), true);
44 | $cache = array();
45 |
46 | $data = array();
47 | foreach ($stats as $key => $val) {
48 | if (is_null($val) || sizeof($val) < 2) {
49 | continue;
50 | }
51 | foreach (preg_grep("/^{$val[0]}\$/i", $beans) as $mbean) {
52 | if (!isset($cache[$mbean])) {
53 | $cache[$mbean] = json_decode(file_get_contents(sprintf("{$jmxproxy}/{$host}/%s?full=true", rawurlencode($mbean))), true);
54 | }
55 | $attribute = $cache[$mbean];
56 |
57 | foreach (array_slice($val, 1) as $part) {
58 | $attribute = $attribute[array_shift(preg_grep("/^{$part}\$/i", array_keys($attribute)))];
59 | }
60 | if (array_key_exists($key, $data)) {
61 | $data[$key] += $attribute;
62 | } else {
63 | $data[$key] = $attribute;
64 | }
65 | }
66 | }
67 |
68 | return implode(' ', array_map(function($k,$v) { return $k . ':' . (is_numeric($v) ? (int)$v : 'U'); }, array_keys($data), array_values($data)));
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/resources/assets/js/jquery.flot.resize.js:
--------------------------------------------------------------------------------
1 | /* Flot plugin for automatically redrawing plots as the placeholder resizes.
2 |
3 | Copyright (c) 2007-2014 IOLA and Ole Laursen.
4 | Licensed under the MIT license.
5 |
6 | It works by listening for changes on the placeholder div (through the jQuery
7 | resize event plugin) - if the size changes, it will redraw the plot.
8 |
9 | There are no options. If you need to disable the plugin for some plots, you
10 | can just fix the size of their placeholders.
11 |
12 | */
13 |
14 | /* Inline dependency:
15 | * jQuery resize event - v1.1 - 3/14/2010
16 | * http://benalman.com/projects/jquery-resize-plugin/
17 | *
18 | * Copyright (c) 2010 "Cowboy" Ben Alman
19 | * Dual licensed under the MIT and GPL licenses.
20 | * http://benalman.com/about/license/
21 | */
22 | (function($,e,t){"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function(){if(!n[f]&&this[s]){return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if(i.length===1){a=t;h()}},teardown:function(){if(!n[f]&&this[s]){return false}var e=$(this);for(var t=i.length-1;t>=0;t--){if(i[t]==this){i.splice(t,1);break}}e.removeData(m);if(!i.length){if(r){cancelAnimationFrame(a)}else{clearTimeout(a)}a=null}},add:function(e){if(!n[f]&&this[s]){return false}var i;function a(e,n,a){var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if($.isFunction(e)){i=e;return a}else{i=e.handler;e.handler=a}}};function h(t){if(r===true){r=t||1}for(var s=i.length-1;s>=0;s--){var l=$(i[s]);if(l[0]==e||l.is(":visible")){var f=l.width(),c=l.height(),d=l.data(m);if(d&&(f!==d.w||c!==d.h)){l.trigger(u,[d.w=f,d.h=c]);r=t||true}}else{d=l.data(m);d.w=0;d.h=0}}if(a!==null){if(r&&(t==null||t-r<1e3)){a=e.requestAnimationFrame(h)}else{a=setTimeout(h,n[o]);r=false}}}if(!e.requestAnimationFrame){e.requestAnimationFrame=function(){return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i){return e.setTimeout(function(){t((new Date).getTime())},n[l])}}()}if(!e.cancelAnimationFrame){e.cancelAnimationFrame=function(){return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this);
23 |
24 | (function ($) {
25 | var options = { }; // no options
26 |
27 | function init(plot) {
28 | function onResize() {
29 | var placeholder = plot.getPlaceholder();
30 |
31 | // somebody might have hidden us and we can't plot
32 | // when we don't have the dimensions
33 | if (placeholder.width() == 0 || placeholder.height() == 0)
34 | return;
35 |
36 | plot.resize();
37 | plot.setupGrid();
38 | plot.draw();
39 | }
40 |
41 | function bindEvents(plot, eventHolder) {
42 | plot.getPlaceholder().resize(onResize);
43 | }
44 |
45 | function shutdown(plot, eventHolder) {
46 | plot.getPlaceholder().unbind("resize", onResize);
47 | }
48 |
49 | plot.hooks.bindEvents.push(bindEvents);
50 | plot.hooks.shutdown.push(shutdown);
51 | }
52 |
53 | $.plot.plugins.push({
54 | init: init,
55 | options: options,
56 | name: 'resize',
57 | version: '1.0'
58 | });
59 | })(jQuery);
60 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/util/History.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.util;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.List;
6 |
7 | /**
8 | * Fixed size historical attribute value store.
9 | *
10 | * Saves an object into a fixed size round robin store. Allows clients to retreive latest
11 | * value, a subset of latest values, or the full stored history of values. When number
12 | * of stored values exceeds the fixed size of the store, the oldest values are overwritten.
13 | *
14 | * @param type of objects held in this History.
15 | *
16 | * @since 2015-05-11
17 | * @author mk23
18 | * @version 3.3.2
19 | */
20 | public class History {
21 | private List objects;
22 | private int length;
23 | private int pointer;
24 | private boolean wrapped;
25 |
26 | /**
27 | * Default constructor.
28 | *
29 | * Initializes the {@link Object} store {@link List} to the given history size.
30 | *
31 | * @param length number of {@link Object} values to keep in history.
32 | */
33 | public History(final int length) {
34 | this.length = length;
35 |
36 | pointer = -1;
37 | objects = new ArrayList(Collections.nCopies(length, (T) null));
38 | }
39 |
40 | /**
41 | * Adds a item to the store.
42 | *
43 | * Adds a new item to the history store. If the number of items exceeds the size
44 | * of the store, the oldest item is overwritten.
45 | *
46 | * @param item newest item to add to the store.
47 | */
48 | public final void add(final T item) {
49 | wrapped = ++pointer == length;
50 | pointer = pointer % length;
51 |
52 | objects.set(pointer, item);
53 | }
54 |
55 | /**
56 | * Gets the latest item from the history store.
57 | *
58 | * Gets the latest single item from the history store.
59 | *
60 | * @return Latest item from the history store or null if empty.
61 | */
62 | public final T getLast() {
63 | return pointer < 0 ? null : objects.get(pointer % length);
64 | }
65 |
66 | /**
67 | * Gets the full item history from the store.
68 | *
69 | * Gets the full item history from the store as a {@link List}.
70 | *
71 | * @return {@link List} of the full history. May be empty if history has no items.
72 | */
73 | public final List get() {
74 | return get(length);
75 | }
76 |
77 | /**
78 | * Gets a limited item history from the store.
79 | *
80 | * Gets a limited history from the store as a {@link List}, based
81 | * on requested item count. If the specified count is less than 0 or greater than
82 | * the number of entries, a full history is returned instead.
83 | *
84 | * @param limit number of items to retreive from the history store.
85 | *
86 | * @return {@link List} of the requested slice of history. May be empty if history has no items.
87 | */
88 | public final List get(final int limit) {
89 | if (pointer < 0) {
90 | return Collections.emptyList();
91 | }
92 |
93 | int head = pointer + length * Boolean.compare(wrapped, false);
94 | int size = Math.min(limit > 0 ? limit : Integer.MAX_VALUE, Math.min(head + 1, length));
95 | List rval = new ArrayList(size);
96 |
97 | for (int i = 0; i < size; i++) {
98 | rval.add(objects.get((head - i) % length));
99 | }
100 |
101 | return rval;
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/jmx/ConnectionCredentials.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.jmx;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import org.hibernate.validator.constraints.NotEmpty;
6 |
7 | /**
8 | * JMX Username and Password user input POJO.
9 | *
10 | * Used to marshal JMX agent credentials and provide methods for comparing.
11 | *
12 | * @since 2015-05-11
13 | * @author mk23
14 | * @version 3.2.0
15 | */
16 | public class ConnectionCredentials {
17 | @NotEmpty
18 | @JsonProperty
19 | private final String username;
20 |
21 | @NotEmpty
22 | @JsonProperty
23 | private final String password;
24 |
25 | private final String combined;
26 |
27 | private final boolean enabled;
28 |
29 | /**
30 | * Default disabled constructor.
31 | *
32 | * Creates a disabled credential object used for anonymous agent access.
33 | */
34 | public ConnectionCredentials() {
35 | username = null;
36 | password = null;
37 | combined = null;
38 |
39 | enabled = false;
40 | }
41 |
42 | /**
43 | * Default constructor.
44 | *
45 | * Sets the instance username and password {@link String}s from provided parameters.
46 | * Builds a single combined credential string for the hashCode computation.
47 | *
48 | * @param username username {@link String} for the new credential instance.
49 | * @param password password {@link String} for the new credential instance.
50 | */
51 | public ConnectionCredentials(
52 | @JsonProperty("username") final String username,
53 | @JsonProperty("password") final String password
54 | ) {
55 | if (username == null || password == null) {
56 | this.username = null;
57 | this.password = null;
58 | this.combined = null;
59 |
60 | this.enabled = false;
61 | } else {
62 | this.username = username;
63 | this.password = password;
64 | this.combined = username + "\0" + password;
65 |
66 | this.enabled = true;
67 | }
68 | }
69 |
70 | /**
71 | * Getter for username.
72 | *
73 | * Fetches the stored username {@link String}.
74 | *
75 | * @return username string.
76 | */
77 | public final String getUsername() {
78 | return username;
79 | }
80 |
81 | /**
82 | * Getter for password.
83 | *
84 | * Fetches the stored password {@link String}.
85 | *
86 | * @return password string.
87 | */
88 | public final String getPassword() {
89 | return password;
90 | }
91 |
92 | /**
93 | * Getter for enabled.
94 | *
95 | * Fetches enabled status for this credential object.
96 | *
97 | * @return enabled boolean.
98 | */
99 | public final boolean isEnabled() {
100 | return enabled;
101 | }
102 |
103 | /** {@inheritDoc} */
104 | @Override
105 | public final boolean equals(final Object obj) {
106 | if (obj != null && !(obj instanceof ConnectionCredentials)) {
107 | return false;
108 | }
109 |
110 | ConnectionCredentials peer = (obj != null) ? (ConnectionCredentials) obj : new ConnectionCredentials();
111 |
112 | if (!enabled) {
113 | return !peer.isEnabled();
114 | }
115 |
116 | return username.equals(peer.getUsername()) && password.equals(peer.getPassword());
117 | }
118 |
119 | /** {@inheritDoc} */
120 | @Override
121 | public final int hashCode() {
122 | return combined != null ? combined.hashCode() : 0;
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/scripts/graphite/jmxproxy.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 |
3 | import argparse
4 | import json
5 | import re
6 | import socket
7 | import time
8 | import urllib
9 | import urllib2
10 |
11 | mbeans = {
12 | 'jvm.thread_count': ('java.lang:type=Threading', 'ThreadCount'),
13 | 'jvm.thread_peak': ('java.lang:type=Threading', 'PeakThreadCount'),
14 | 'jvm.memory_heap_used': ('java.lang:type=Memory', 'HeapMemoryUsage', 'used'),
15 | 'jvm.memory_heap_max': ('java.lang:type=Memory', 'HeapMemoryUsage', 'max'),
16 | 'jvm.gc_count': ('java.lang:type=GarbageCollector,name=.*', 'CollectionCount'),
17 | 'jvm.classes_loaded': ('java.lang:type=ClassLoading', 'LoadedClassCount'),
18 | 'jvm.classes_total': ('java.lang:type=ClassLoading', 'TotalLoadedClassCount'),
19 | 'jvm.classes_unloaded': ('java.lang:type=ClassLoading', 'UnloadedClassCount'),
20 | }
21 |
22 | parser = argparse.ArgumentParser(description='jmxproxy poller for graphite')
23 | parser.add_argument('--service-host', default=socket.gethostname(),
24 | help='jvm jmx agent service host')
25 | parser.add_argument('--service-port', type=int, required=True,
26 | help='jvm jmx agent service port')
27 | parser.add_argument('--service-auth',
28 | help='jvm jmx agent service auth as username:password')
29 | parser.add_argument('--graphite-key',
30 | help='graphite key prefix')
31 | parser.add_argument('--graphite-host', default='localhost',
32 | help='graphite host')
33 | parser.add_argument('--graphite-port', type=int, default=2003,
34 | help='graphite port')
35 | parser.add_argument('--jmxproxy-host', default='localhost',
36 | help='jmxproxy host')
37 | parser.add_argument('--jmxproxy-port', type=int, default=8080,
38 | help='jmxproxy port')
39 | parser.add_argument('--jmxproxy-path', default='jmxproxy',
40 | help='jmxproxy path')
41 | parser.add_argument('-n', '--dry-run', default=False, action='store_true',
42 | help='print results instead of sending to graphite')
43 |
44 | def fetch_jmx(data, service_host, service_port, service_auth, jmxproxy_host, jmxproxy_port, jmxproxy_path):
45 | attrs = {}
46 | creds = None if not service_auth else urllib.urlencode(zip(('username', 'password'), service_auth.split(':')))
47 | beans = json.loads(urllib2.urlopen('http://%s:%d/%s/%s:%d?full=true' % (jmxproxy_host, jmxproxy_port, jmxproxy_path, service_host, service_port), creds).read())
48 |
49 | for key, val in data.items():
50 | for mbean in beans:
51 | if re.match('%s$' % val[0], mbean):
52 | attr = beans[mbean]
53 | for i in xrange(1, len(val)):
54 | attr = attr[val[i]]
55 |
56 | if key not in attrs:
57 | attrs[key] = 0
58 |
59 | attrs[key] += attr
60 |
61 | return attrs
62 |
63 | def send_data(data, path, graphite_host, graphite_port, send=True):
64 | t = int(time.time())
65 | m = '\n'.join("%s.%s %s %d" % (path, k, v, t) for k, v in sorted(data.items()))
66 |
67 | if send:
68 | s = socket.socket()
69 | s.connect((graphite_host, graphite_port))
70 | s.send(m)
71 | else:
72 | print m
73 |
74 |
75 | def main(args=None, service='', extra_stats={}):
76 | if args is None:
77 | args = parser.parse_args()
78 |
79 | mbeans.update(extra_stats)
80 | data = fetch_jmx(mbeans, args.service_host, args.service_port, args.service_auth, args.jmxproxy_host, args.jmxproxy_port, args.jmxproxy_path)
81 | path = '.'.join(i for i in (args.graphite_key, args.service_host, service) if i)
82 |
83 | send_data(data, path, args.graphite_host, args.graphite_port, send=not args.dry_run)
84 |
85 | if __name__ == '__main__':
86 | main()
87 |
--------------------------------------------------------------------------------
/src/test/java/com/github/mk23/jmxproxy/core/tests/HostTest.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.core.tests;
2 |
3 | import com.github.mk23.jmxproxy.core.Host;
4 |
5 | import com.fasterxml.jackson.core.JsonProcessingException;
6 | import com.fasterxml.jackson.databind.JsonNode;
7 | import com.fasterxml.jackson.databind.ObjectMapper;
8 |
9 | import org.junit.Before;
10 | import org.junit.Rule;
11 | import org.junit.Test;
12 | import org.junit.rules.TestName;
13 |
14 | import static org.hamcrest.core.Is.is;
15 | import static org.junit.Assert.assertThat;
16 | import static org.junit.Assert.assertTrue;
17 |
18 | public class HostTest {
19 | private final ObjectMapper om = new ObjectMapper();
20 |
21 | @Rule public TestName name = new TestName();
22 |
23 | private String asJson(Object object) throws JsonProcessingException {
24 | return om.writeValueAsString(object);
25 | }
26 |
27 | @Before
28 | public void printTestName() {
29 | System.out.println(" -> " + name.getMethodName());
30 | }
31 |
32 | @Test
33 | public void checkEmptyHost() throws Exception {
34 | final Host host = new Host();
35 | final String expected = new String("{}");
36 |
37 | assertThat("check empty host", asJson(host), is(expected));
38 | }
39 |
40 | @Test
41 | public void checkEmptyHostMBeanList() throws Exception {
42 | final Host host = new Host();
43 | final String expected = new String("[]");
44 |
45 | assertThat("check empty host mbean list", asJson(host.getMBeans()), is(expected));
46 | }
47 |
48 | @Test
49 | public void checkMissingMBean() throws Exception {
50 | final Host host = new Host();
51 | final String expected = new String("null");
52 |
53 | assertThat("check missing mbean", asJson(host.getMBean("bean")), is(expected));
54 | }
55 |
56 | @Test
57 | public void checkDuplicateMBean() throws Exception {
58 | final Host host = new Host();
59 | assertTrue(host.addMBean("bean") == host.addMBean("bean"));
60 | }
61 |
62 | @Test
63 | public void checkAddDefaultMBeanFull() throws Exception {
64 | final Host host = new Host();
65 | host.addMBean("bean");
66 |
67 | final String expected = new String("{\"bean\":{}}");
68 |
69 | assertThat("check add default mbean full", asJson(host), is(expected));
70 | }
71 |
72 | @Test
73 | public void checkAddDefaultMBeanList() throws Exception {
74 | final Host host = new Host();
75 | host.addMBean("bean");
76 |
77 | final String expected = new String("[\"bean\"]");
78 |
79 | assertThat("check add default mbean list", asJson(host.getMBeans()), is(expected));
80 | }
81 |
82 | @Test
83 | public void checkAddDefaultMBeanBare() throws Exception {
84 | final Host host = new Host();
85 | host.addMBean("bean");
86 |
87 | final String expected = new String("{}");
88 |
89 | assertThat("check add default mbean bare", asJson(host.getMBean("bean")), is(expected));
90 | }
91 |
92 | @Test
93 | public void checkAddExplicitMBeanFull() throws Exception {
94 | final Host host = new Host();
95 | host.addMBean("bean", 1);
96 |
97 | final String expected = new String("{\"bean\":{}}");
98 |
99 | assertThat("check add explicit mbean full", asJson(host), is(expected));
100 | }
101 |
102 | @Test
103 | public void checkAddExplicitMBeanList() throws Exception {
104 | final Host host = new Host();
105 | host.addMBean("bean", 1);
106 |
107 | final String expected = new String("[\"bean\"]");
108 |
109 | assertThat("check add explicit mbean list", asJson(host.getMBeans()), is(expected));
110 | }
111 |
112 | @Test
113 | public void checkAddExplicitMBeanBare() throws Exception {
114 | final Host host = new Host();
115 | host.addMBean("bean", 1);
116 |
117 | final String expected = new String("{}");
118 |
119 | assertThat("check add explicit mbean bare", asJson(host.getMBean("bean")), is(expected));
120 | }
121 |
122 | @Test
123 | public void checkRemoveMBean() throws Exception {
124 | final Host host = new Host();
125 | host.addMBean("bean");
126 | host.removeMBean("bean");
127 |
128 | final String expected = new String("{}");
129 |
130 | assertThat("check remove mbean", asJson(host), is(expected));
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/src/test/java/com/github/mk23/jmxproxy/jmx/tests/ConnectionCredentialsTest.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.jmx.tests;
2 |
3 | import com.github.mk23.jmxproxy.jmx.ConnectionCredentials;
4 |
5 | import org.junit.Before;
6 | import org.junit.Rule;
7 | import org.junit.Test;
8 | import org.junit.rules.TestName;
9 |
10 | import static org.junit.Assert.assertTrue;
11 | import static org.junit.Assert.assertFalse;
12 |
13 | public class ConnectionCredentialsTest {
14 | @Rule public TestName name = new TestName();
15 |
16 | @Before
17 | public void printTestName() {
18 | System.out.println(" -> " + name.getMethodName());
19 | }
20 |
21 | @Test
22 | public void checkAuthenticatedEquals() throws Exception {
23 | final ConnectionCredentials auth1 = new ConnectionCredentials(new String("user"), new String("pass"));
24 | final ConnectionCredentials auth2 = new ConnectionCredentials(new String("user"), new String("pass"));
25 |
26 | assertTrue(auth1.equals(auth2));
27 | }
28 |
29 | @Test
30 | public void checkAuthenticatedNotEqualsUser() throws Exception {
31 | final ConnectionCredentials auth1 = new ConnectionCredentials(new String("user"), new String("pass"));
32 | final ConnectionCredentials auth2 = new ConnectionCredentials(new String("pass"), new String("pass"));
33 |
34 | assertFalse(auth1.equals(auth2));
35 | }
36 |
37 | @Test
38 | public void checkAuthenticatedNotEqualsPass() throws Exception {
39 | final ConnectionCredentials auth1 = new ConnectionCredentials(new String("user"), new String("pass"));
40 | final ConnectionCredentials auth2 = new ConnectionCredentials(new String("user"), new String("user"));
41 |
42 | assertFalse(auth1.equals(auth2));
43 | }
44 |
45 | @Test
46 | public void checkAuthenticatedNotEqualsBoth() throws Exception {
47 | final ConnectionCredentials auth1 = new ConnectionCredentials(new String("user"), new String("pass"));
48 | final ConnectionCredentials auth2 = new ConnectionCredentials(new String("pass"), new String("user"));
49 |
50 | assertFalse(auth1.equals(auth2));
51 | }
52 |
53 | @Test
54 | public void checkAuthenticatedNotEqualsNull() throws Exception {
55 | final ConnectionCredentials auth = new ConnectionCredentials(new String("user"), new String("pass"));
56 |
57 | assertFalse(auth.equals(null));
58 | }
59 |
60 | @Test
61 | public void checkAuthenticatedNotEqualsInvalid() throws Exception {
62 | final ConnectionCredentials auth = new ConnectionCredentials(new String("user"), new String("pass"));
63 |
64 | assertFalse(auth.equals(new String("")));
65 | }
66 |
67 | @Test
68 | public void checkAuthenticatedEnabled() throws Exception {
69 | final ConnectionCredentials auth = new ConnectionCredentials(new String("user"), new String("pass"));
70 |
71 | assertTrue(auth.isEnabled());
72 | }
73 |
74 | @Test
75 | public void checkAuthenticatedHashCode() throws Exception {
76 | final ConnectionCredentials auth = new ConnectionCredentials(new String("user"), new String("pass"));
77 |
78 | assertTrue(auth.hashCode() == new String("user\0pass").hashCode());
79 | }
80 |
81 | @Test
82 | public void checkAnonymousEquals() throws Exception {
83 | final ConnectionCredentials auth1 = new ConnectionCredentials();
84 | final ConnectionCredentials auth2 = new ConnectionCredentials();
85 |
86 | assertTrue(auth1.equals(auth2));
87 | }
88 |
89 | @Test
90 | public void checkAnonymousNotEquals() throws Exception {
91 | final ConnectionCredentials auth1 = new ConnectionCredentials();
92 | final ConnectionCredentials auth2 = new ConnectionCredentials(new String("user"), new String("pass"));
93 |
94 | assertFalse(auth1.equals(auth2));
95 | }
96 |
97 | @Test
98 | public void checkAnonymousNotEqualsNull() throws Exception {
99 | final ConnectionCredentials auth = new ConnectionCredentials();
100 |
101 | assertTrue(auth.equals(null));
102 | }
103 |
104 | @Test
105 | public void checkAnonymousEnabledUser() throws Exception {
106 | final ConnectionCredentials auth = new ConnectionCredentials(new String("user"), null);
107 |
108 | assertFalse(auth.isEnabled());
109 | }
110 |
111 | @Test
112 | public void checkAnonymousEnabledPass() throws Exception {
113 | final ConnectionCredentials auth = new ConnectionCredentials(null, new String("pass"));
114 |
115 | assertFalse(auth.isEnabled());
116 | }
117 |
118 | @Test
119 | public void checkAnonymousEnabledBoth() throws Exception {
120 | final ConnectionCredentials auth = new ConnectionCredentials();
121 |
122 | assertFalse(auth.isEnabled());
123 | }
124 |
125 | @Test
126 | public void checkAnonymousHashCode() throws Exception {
127 | final ConnectionCredentials auth = new ConnectionCredentials();
128 |
129 | assertTrue(auth.hashCode() == 0);
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/src/test/java/com/github/mk23/jmxproxy/tests/JMXProxyApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.tests;
2 |
3 | import com.github.mk23.jmxproxy.JMXProxyApplication;
4 | import com.github.mk23.jmxproxy.conf.MainConfig;
5 | import com.github.mk23.jmxproxy.jmx.ConnectionManager;
6 |
7 | import com.fasterxml.jackson.databind.JsonNode;
8 | import com.fasterxml.jackson.databind.ObjectMapper;
9 |
10 | import io.dropwizard.testing.DropwizardTestSupport;
11 | import io.dropwizard.testing.FixtureHelpers;
12 | import io.dropwizard.testing.ResourceHelpers;
13 |
14 | import java.io.FileNotFoundException;
15 |
16 | import javax.ws.rs.client.Client;
17 | import javax.ws.rs.client.ClientBuilder;
18 | import javax.ws.rs.core.Response;
19 |
20 | import org.eclipse.jetty.util.component.LifeCycle;
21 |
22 | import org.junit.After;
23 | import org.junit.Before;
24 | import org.junit.Rule;
25 | import org.junit.Test;
26 | import org.junit.rules.ExpectedException;
27 | import org.junit.rules.TestName;
28 |
29 | import static org.junit.Assert.assertFalse;
30 | import static org.junit.Assert.assertNotNull;
31 | import static org.junit.Assert.assertTrue;
32 |
33 | public class JMXProxyApplicationTest {
34 |
35 | private static final String CONFIG =
36 | ResourceHelpers.resourceFilePath("main_config.yaml");
37 | public static final DropwizardTestSupport SUPPORT =
38 | new DropwizardTestSupport(JMXProxyApplication.class, CONFIG);
39 |
40 | private Client client;
41 |
42 | @Rule public ExpectedException thrown = ExpectedException.none();
43 | @Rule public TestName name = new TestName();
44 |
45 | @Before
46 | public void printTestName() {
47 | System.out.println(" -> " + name.getMethodName());
48 | }
49 |
50 | @Before
51 | public void startApplication() throws Exception {
52 | SUPPORT.before();
53 | }
54 |
55 | @Before
56 | public void createClient() throws Exception {
57 | client = ClientBuilder.newClient();
58 | }
59 |
60 | @After
61 | public void stopApplication() throws Exception {
62 | SUPPORT.after();
63 | }
64 |
65 | @After
66 | public void shutdownClient() throws Exception {
67 | client.close();
68 | }
69 |
70 | @Test
71 | public void checkApplication() throws Exception {
72 | Response response = client.target("http://localhost:" + SUPPORT.getLocalPort()).request().get();
73 |
74 | assertTrue(response.getStatus() == Response.Status.OK.getStatusCode());
75 | assertTrue(response.readEntity(String.class).contains("JMXProxy "));
76 | }
77 |
78 | @Test
79 | public void checkMinificationJS() throws Exception {
80 | Response response = client.target("http://localhost:" + SUPPORT.getLocalPort() + "/js/jmxproxy.js").request().get();
81 |
82 | assertTrue(response.getStatus() == Response.Status.OK.getStatusCode());
83 | assertFalse(response.readEntity(String.class).contains("var endpointHost;"));
84 | }
85 |
86 | @Test
87 | public void checkMinificationCSS() throws Exception {
88 | Response response = client.target("http://localhost:" + SUPPORT.getLocalPort() + "/css/jmxproxy.css").request().get();
89 |
90 | assertTrue(response.getStatus() == Response.Status.OK.getStatusCode());
91 | assertFalse(response.readEntity(String.class).contains("\n"));
92 | }
93 |
94 | @Test
95 | public void checkHealthStatusPass() throws Exception {
96 | ObjectMapper om = new ObjectMapper();
97 | String expected = om.writeValueAsString(om.readValue(FixtureHelpers.fixture("fixtures/health_check_pass.json"), JsonNode.class));
98 |
99 | Response response = client.target("http://localhost:" + SUPPORT.getAdminPort() + "/healthcheck").request().get();
100 |
101 | assertTrue(response.getStatus() == Response.Status.OK.getStatusCode());
102 | assertTrue(response.readEntity(String.class).equals(expected));
103 | }
104 |
105 | @Test
106 | public void checkHealthStatusFail() throws Exception {
107 | ObjectMapper om = new ObjectMapper();
108 | String expected = om.writeValueAsString(om.readValue(FixtureHelpers.fixture("fixtures/health_check_fail.json"), JsonNode.class));
109 |
110 | LifeCycle lc = null;
111 | for (LifeCycle object : SUPPORT.getEnvironment().lifecycle().getManagedObjects()) {
112 | if (object.toString().startsWith(ConnectionManager.class.getName())) {
113 | lc = object;
114 | break;
115 | }
116 | }
117 | assertNotNull(lc);
118 | lc.stop();
119 |
120 | Response response = client.target("http://localhost:" + SUPPORT.getAdminPort() + "/healthcheck").request().get();
121 |
122 | assertTrue(response.getStatus() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
123 | assertTrue(response.readEntity(String.class).equals(expected));
124 | }
125 |
126 | @Test
127 | public void checkMainValidConfig() throws Exception {
128 | JMXProxyApplication.main(new String[] {"server", CONFIG});
129 | // success if no exceptions are thrown
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/core/Host.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.core;
2 |
3 | import com.fasterxml.jackson.core.JsonGenerator;
4 | import com.fasterxml.jackson.core.JsonProcessingException;
5 | import com.fasterxml.jackson.databind.JsonSerializable;
6 | import com.fasterxml.jackson.databind.SerializerProvider;
7 | import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
8 |
9 | import java.io.IOException;
10 |
11 | import java.util.HashMap;
12 | import java.util.Map;
13 | import java.util.Set;
14 |
15 | /**
16 | * JMX Host tracker and serializer.
17 | *
18 | * Maintains a map of JMX {@link MBean} names and their values. Implements
19 | * JsonSerializable interface to convert the stored map into JSON.
20 | *
21 | * @see com.fasterxml.jackson.databind.JsonSerializable
22 | *
23 | * @since 2018-02-08
24 | * @author mk23
25 | * @version 3.4.0
26 | */
27 | public class Host implements JsonSerializable {
28 | private final Map mbeans;
29 | private final ThreadLocal limit = new ThreadLocal() {
30 | @Override protected Integer initialValue() {
31 | return -1;
32 | }
33 | };
34 |
35 | /**
36 | * Default constructor.
37 | *
38 | * Creates a map of {@link MBean} name to associated values.
39 | */
40 | public Host() {
41 | mbeans = new HashMap();
42 | }
43 |
44 | /**
45 | * Inserts a new MBean name to value association.
46 | *
47 | * Creates a new {@link MBean} object and inserts into the map store
48 | * associating it to the specified mbean name. Uses default attribute
49 | * {@link com.github.mk23.jmxproxy.util.History} size configuration.
50 | *
51 | * @param mbeanName name of the {@link MBean} used as the map key.
52 | *
53 | * @return the newly created {@link MBean} object.
54 | */
55 | public final MBean addMBean(final String mbeanName) {
56 | if (!mbeans.containsKey(mbeanName)) {
57 | MBean mbean = new MBean();
58 | mbeans.put(mbeanName, mbean);
59 | }
60 |
61 | return mbeans.get(mbeanName);
62 | }
63 |
64 | /**
65 | * Inserts a new MBean name to value association.
66 | *
67 | * Creates a new {@link MBean} object and inserts into the map store
68 | * associating it to the specified mbean name. Uses custom attribute
69 | * {@link com.github.mk23.jmxproxy.util.History} size configuration.
70 | *
71 | * @param mbeanName name of the {@link MBean} used as the map key.
72 | * @param historySize number of items to preserve in the associated
73 | * {@link com.github.mk23.jmxproxy.util.History}.
74 | *
75 | * @return the newly created {@link MBean} object.
76 | */
77 | public final MBean addMBean(final String mbeanName, final int historySize) {
78 | if (!mbeans.containsKey(mbeanName)) {
79 | MBean mbean = new MBean(historySize);
80 | mbeans.put(mbeanName, mbean);
81 | }
82 |
83 | return mbeans.get(mbeanName);
84 | }
85 |
86 | /**
87 | * Deletes an mbean association.
88 | *
89 | * Removes an associated {@link MBean} from the map store for this host.
90 | *
91 | * @param mbeanName name of the {@link MBean} to remove.
92 | */
93 | public final void removeMBean(final String mbeanName) {
94 | mbeans.remove(mbeanName);
95 | }
96 |
97 | /**
98 | * Sets the thread local history request limit.
99 | *
100 | * Set the thread local limit for all {@link com.github.mk23.jmxproxy.util.History} when
101 | * serializing to JSON. Because this method returns its object, requesting serialization
102 | * can be done * with a single statement.
103 | *
104 | * For example:
105 | *
106 | * return Response.ok(host.setLimit(5)).build();
107 | *
108 | * @see javax.ws.rs.core.Response
109 | *
110 | * @param bound the number of items to retreive from {@link com.github.mk23.jmxproxy.util.History}
111 | * for this thread.
112 | *
113 | * @return this host object for chaining calls.
114 | */
115 | public final Host setLimit(final Integer bound) {
116 | limit.set(bound);
117 | return this;
118 | }
119 |
120 | /**
121 | * Getter for mbean names.
122 | *
123 | * Extracts and returns the unique {@link Set} of all currently stored {@link MBean} names.
124 | *
125 | * @return {@link Set} of {@link MBean} name {@link String}s.
126 | */
127 | public final Set getMBeans() {
128 | return mbeans.keySet();
129 | }
130 |
131 | /**
132 | * Getter for specific mbean.
133 | *
134 | * Fetches the specified {@link MBean} from the map store.
135 | *
136 | * @param mbean name of the {@link MBean} to look up in the map store.
137 | *
138 | * @return {@link MBean} object if found, null otherwise.
139 | */
140 | public final MBean getMBean(final String mbean) {
141 | return mbeans.get(mbean);
142 | }
143 |
144 | /** {@inheritDoc} */
145 | public final void serialize(
146 | final JsonGenerator jgen,
147 | final SerializerProvider sp
148 | ) throws IOException, JsonProcessingException {
149 | serializeWithType(jgen, sp, null);
150 | }
151 |
152 | /** {@inheritDoc} */
153 | public final void serializeWithType(
154 | final JsonGenerator jgen,
155 | final SerializerProvider sp,
156 | final TypeSerializer ts
157 | ) throws IOException, JsonProcessingException {
158 | buildJson(jgen);
159 | }
160 |
161 | private void buildJson(final JsonGenerator jgen) throws IOException, JsonProcessingException {
162 | int bound = limit.get();
163 |
164 | jgen.writeStartObject();
165 | for (Map.Entry mbeanEntry : mbeans.entrySet()) {
166 | jgen.writeObjectField(mbeanEntry.getKey(), mbeanEntry.getValue().setLimit(bound));
167 | }
168 | jgen.writeEndObject();
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/scripts/nagios/check_jmxproxy.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 |
3 | import argparse
4 | import json
5 | import re
6 | import sys
7 | import traceback
8 | import urllib
9 | import urllib2
10 |
11 | SUCCESS, WARNING, CRITICAL, UNKNOWN = range(4)
12 | ERRORS = dict((v, k) for k, v in vars(sys.modules[__name__]).items() if type(v) == int)
13 |
14 | def lookup_val(host, port, expr, auth=None, proxy='http://localhost:8080/jmxproxy', cache={}):
15 | item = expr.split('//')
16 | name = item.pop(0)
17 | attr = item.pop(0)
18 |
19 | if auth:
20 | auth = urllib.urlencode(zip(('username', 'password'), auth.split(':')))
21 |
22 | if not cache:
23 | cache.update(dict((i, {}) for i in json.loads(urllib2.urlopen('%s/%s:%d' % (proxy, host, port), auth).read())))
24 |
25 | for bean in cache:
26 | if re.match(name + '$', bean, re.I):
27 | if not cache[bean]:
28 | cache[bean].update(dict((i, None) for i in json.loads(urllib2.urlopen('%s/%s:%d/%s' % (proxy, host, port, urllib.quote(bean)), auth).read())))
29 |
30 | if cache[bean][attr] is None:
31 | cache[bean][attr] = json.loads(urllib2.urlopen('%s/%s:%d/%s/%s' % (proxy, host, port, urllib.quote(bean), urllib.quote_plus(attr)), auth).read())
32 |
33 | val = cache[bean][attr]
34 | for key in item:
35 | val = val[key] if isinstance(val, dict) else json.loads(val)[key]
36 |
37 | if type(val) in (list, tuple):
38 | return len(val)
39 | elif unicode(val).isnumeric():
40 | return float(val)
41 | else:
42 | return val
43 |
44 | raise KeyError('%s[%s]: attribute not available' % (bean, attr))
45 |
46 | if __name__ == '__main__':
47 | master_parser = argparse.ArgumentParser(description='nagios jmxproxy plugin')
48 | master_parser.add_argument('-a', '--host', required=True,
49 | help='jmx agent host')
50 | master_parser.add_argument('-p', '--port', type=int, required=True,
51 | help='jmx agent port')
52 | master_parser.add_argument('-c', '--auth',
53 | help='jmx agent credentials as username:password')
54 | master_parser.add_argument('-e', '--expr', type=unicode, required=True,
55 | help='text attribute or rpn expression to calculate')
56 | master_parser.add_argument('-j', '--proxy', default='http://localhost:8080/jmxproxy',
57 | help='jmxproxy host:port')
58 | master_parser.add_argument('-i', '--invert', action='store_true',
59 | help='negates text match or forces negative crit/warn thresholds')
60 | master_parser.add_argument('-f', '--format', default=None,
61 | help='output format string for successul check')
62 |
63 | slave_parsers = master_parser.add_subparsers(dest='mode')
64 |
65 | parser = slave_parsers.add_parser('textual')
66 | parser.add_argument('text', help='expected attribute value')
67 |
68 | parser = slave_parsers.add_parser('metrics')
69 | parser.add_argument('-w', '--warn', type=float, required=True,
70 | help='warning threshold value')
71 | parser.add_argument('-c', '--crit', type=float, required=True,
72 | help='critical threshold value')
73 | args = master_parser.parse_args()
74 |
75 | results = [[] for i in range(4)]
76 | try:
77 | if args.mode == 'textual':
78 | item = lookup_val(args.host, args.port, args.expr, args.auth, args.proxy)
79 | if not args.invert and item == args.text or args.invert and item != args.text:
80 | results[SUCCESS].append((args.format or 'valid attribute value: {result}').format(result=item))
81 | else:
82 | results[CRITICAL].append((args.format or 'invalid attribute value: {result}').format(result=item))
83 |
84 | elif args.mode == 'metrics':
85 | stack = []
86 | for item in args.expr.split():
87 | if item == '+':
88 | stack.append(stack.pop() + stack.pop())
89 | elif item == '-':
90 | stack.append(stack.pop() - stack.pop())
91 | elif item == '/':
92 | stack.append(stack.pop() / stack.pop())
93 | elif item == '*':
94 | stack.append(stack.pop() * stack.pop())
95 | elif item == '%':
96 | stack.append(stack.pop() % stack.pop())
97 | elif '//' in item:
98 | stack.append(lookup_val(args.host, args.port, item, args.auth, args.proxy))
99 | elif item.isnumeric():
100 | stack.append(float(item))
101 | else:
102 | raise ValueError('invalid rpn expression')
103 |
104 | results[SUCCESS].append((args.format or 'calculated value: {result:.02f} threshold: {limit:.02f}').format(result=stack[0], limit=args.crit))
105 |
106 | if args.invert:
107 | if stack[0] < args.crit:
108 | results[CRITICAL].append((args.format or 'derived expression result {result:.02f} is below critical threshold of {limit:.02f}').format(result=stack[0], limit=args.crit))
109 | if stack[0] < args.warn:
110 | results[WARNING].append((args.format or 'derived expression result {result:.02f} is below warning threshold of {limit:.02f}').format(result=stack[0], limit=args.warn))
111 | else:
112 | if stack[0] > args.crit:
113 | results[CRITICAL].append((args.format or 'derived expression result {result:.02f} is above critical threshold of {limit:.02f}').format(result=stack[0], limit=args.crit))
114 | if stack[0] > args.warn:
115 | results[WARNING].append((args.format or 'derived expression result {result:.02f} is above warning threshold of {limit:.02f}').format(result=stack[0], limit=args.warn))
116 |
117 | except urllib2.HTTPError as e:
118 | results[CRITICAL].append('(%d) %s' % (e.code, e.msg))
119 | except urllib2.URLError as e:
120 | results[CRITICAL].append(e[0][1])
121 | except Exception:
122 | print 'unknown error'
123 | traceback.print_exc(file=sys.stdout)
124 | sys.exit(UNKNOWN)
125 |
126 |
127 | for code in (CRITICAL, UNKNOWN, WARNING, SUCCESS):
128 | size = len(results[code])
129 | if size > 1:
130 | print '%d %s results' % (size, ERRORS[code])
131 | print '\n'.join(results[code])
132 | sys.exit(code)
133 | if size == 1:
134 | print results[code][0]
135 | sys.exit(code)
136 |
137 | print 'no results found'
138 | sys.exit(UNKNOWN)
139 |
--------------------------------------------------------------------------------
/scripts/graphite/hadoop.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 |
3 | import argparse
4 | import jmxproxy
5 |
6 | HADOOP_STATS = {
7 | 'namenode': {
8 | 'cluster_capacity': ('hadoop:service=NameNode,name=NameNodeInfo', 'Total'),
9 | 'cluster_remaining': ('hadoop:service=NameNode,name=NameNodeInfo', 'Free'),
10 | 'cluster_used': ('hadoop:service=NameNode,name=NameNodeInfo', 'Used'),
11 | 'ops_create_file': ('hadoop:service=NameNode,name=NameNodeActivity', 'CreateFileOps'),
12 | 'ops_delete_file': ('hadoop:service=NameNode,name=NameNodeActivity', 'DeleteFileOps'),
13 | 'ops_file_info': ('hadoop:service=NameNode,name=NameNodeActivity', 'FileInfoOps'),
14 | 'ops_syncs': ('hadoop:service=NameNode,name=NameNodeActivity', 'SyncsNumOps'),
15 | 'ops_transactions': ('hadoop:service=NameNode,name=NameNodeActivity', 'TransactionsNumOps')
16 | },
17 | 'datanode': {
18 | 'ds_capacity': ('hadoop:service=DataNode,name=FSDatasetState-DS.*', 'Capacity'),
19 | 'ds_remaining': ('hadoop:service=DataNode,name=FSDatasetState-DS.*', 'Remaining'),
20 | 'ds_used': ('hadoop:service=DataNode,name=FSDatasetState-DS.*', 'DfsUsed'),
21 | 'ds_failed': ('hadoop:service=DataNode,name=FSDatasetState-DS.*', 'NumFailedVolumes'),
22 | 'blocks_read': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blocks_read'),
23 | 'blocks_removed': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blocks_removed'),
24 | 'blocks_replicated': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blocks_replicated'),
25 | 'blocks_verified': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blocks_verified'),
26 | 'blocks_written': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blocks_written'),
27 | 'bytes_read': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'bytes_read'),
28 | 'bytes_written': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'bytes_written'),
29 | 'reads_from_local_client': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'reads_from_local_client'),
30 | 'writes_from_local_client': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'writes_from_local_client'),
31 | 'reads_from_remote_client': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'reads_from_remote_client'),
32 | 'writes_from_remote_client': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'writes_from_remote_client'),
33 | 'ops_block_copy': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'copyBlockOpNumOps'),
34 | 'ops_block_read': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'readBlockOpNumOps'),
35 | 'ops_block_write': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'writeBlockOpNumOps'),
36 | 'ops_block_replace': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'replaceBlockOpNumOps'),
37 | 'ops_block_checksum': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blockChecksumOpNumOps'),
38 | 'ops_block_reports': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blockReportsNumOps'),
39 | 'ops_heartbeat': ('hadoop:service=DataNode,name=DataNodeActivity-.*', 'heartBeatsNumOps'),
40 | },
41 | 'jobtracker': {
42 | 'nodes_total': ('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'nodes'),
43 | 'nodes_alive': ('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'alive'),
44 | 'map_slots': ('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'slots', 'map_slots'),
45 | 'map_slots_used': ('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'slots', 'map_slots_used'),
46 | 'reduce_slots': ('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'slots', 'reduce_slots'),
47 | 'reduce_slots_used': ('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'slots', 'reduce_slots_used'),
48 | 'jobs': ('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'jobs'),
49 | },
50 | 'tasktracker': {
51 | 'tasks_running': ('hadoop:service=TaskTracker,name=TaskTrackerInfo', 'TasksInfoJson', 'running'),
52 | 'tasks_failed': ('hadoop:service=TaskTracker,name=TaskTrackerInfo', 'TasksInfoJson', 'failed'),
53 | 'commit_pending': ('hadoop:service=TaskTracker,name=TaskTrackerInfo', 'TasksInfoJson', 'commit_pending'),
54 | },
55 | 'masterserver': {
56 | 'cluster_requests': ('hadoop:service=Master,name=MasterStatistics', 'cluster_requests'),
57 | },
58 | 'regionserver': {
59 | 'cache_capacity': ('hadoop:service=RegionServer,name=RegionServerStatistics', 'blockCacheSize'),
60 | 'cache_remianing': ('hadoop:service=RegionServer,name=RegionServerStatistics', 'blockCacheFree'),
61 | 'cache_used': ('hadoop:service=RegionServer,name=RegionServerStatistics', 'blockCacheCount'),
62 | 'cache_hit_count': ('hadoop:service=RegionServer,name=RegionServerStatistics', 'blockCacheHitCount'),
63 | 'cache_miss_count': ('hadoop:service=RegionServer,name=RegionServerStatistics', 'blockCacheMissCount'),
64 | 'regions': ('hadoop:service=RegionServer,name=RegionServerStatistics', 'regions'),
65 | 'requests': ('hadoop:service=RegionServer,name=RegionServerStatistics', 'requests'),
66 | 'stores': ('hadoop:service=RegionServer,name=RegionServerStatistics', 'stores'),
67 | 'storefiles': ('hadoop:service=RegionServer,name=RegionServerStatistics', 'storefiles'),
68 | },
69 | 'zookeeper': {
70 | 'packets_received': ('org.apache.ZooKeeperService:name0=ReplicatedServer_id[0-9]+,name1=replica.[0-9]+,name2=Follower', 'PacketsReceived'),
71 | 'packets_sent': ('org.apache.ZooKeeperService:name0=ReplicatedServer_id[0-9]+,name1=replica.[0-9]+,name2=Follower', 'PacketsSent'),
72 | 'outstanding_requests': ('org.apache.ZooKeeperService:name0=ReplicatedServer_id[0-9]+,name1=replica.[0-9]+,name2=Follower', 'OutstandingRequests'),
73 | 'avg_request_latency': ('org.apache.ZooKeeperService:name0=ReplicatedServer_id[0-9]+,name1=replica.[0-9]+,name2=Follower', 'AvgRequestLatency'),
74 | },
75 | }
76 |
77 |
78 | def main():
79 | parser = argparse.ArgumentParser(parents=[jmxproxy.parser], add_help=False, description='jmxproxy hadoop poller for graphite')
80 | parser.add_argument('--service-name', required=True, choices=sorted(HADOOP_STATS.keys()),
81 | help='hadoop service name')
82 | args = parser.parse_args()
83 |
84 | jmxproxy.main(args, args.service_name, HADOOP_STATS[args.service_name])
85 |
86 |
87 | if __name__ == '__main__':
88 | main()
89 |
--------------------------------------------------------------------------------
/scripts/cacti/ss_hadoop.php:
--------------------------------------------------------------------------------
1 | array());
7 | $hadoop_stats['namenode'] = array(
8 | 'cluster_capacity' => array('hadoop:service=NameNode,name=NameNodeInfo', 'Total'),
9 | 'cluster_remaining' => array('hadoop:service=NameNode,name=NameNodeInfo', 'Free'),
10 | 'cluster_used' => array('hadoop:service=NameNode,name=NameNodeInfo', 'Used'),
11 | 'ops_create_file' => array('hadoop:service=NameNode,name=NameNodeActivity', 'CreateFileOps'),
12 | 'ops_delete_file' => array('hadoop:service=NameNode,name=NameNodeActivity', 'DeleteFileOps'),
13 | 'ops_file_info' => array('hadoop:service=NameNode,name=NameNodeActivity', 'FileInfoOps'),
14 | 'ops_syncs' => array('hadoop:service=NameNode,name=NameNodeActivity', 'SyncsNumOps'),
15 | 'ops_transactions' => array('hadoop:service=NameNode,name=NameNodeActivity', 'TransactionsNumOps'),
16 | );
17 | $hadoop_stats['datanode'] = array(
18 | 'ds_capacity' => array('hadoop:service=DataNode,name=FSDatasetState-.*', 'Capacity'),
19 | 'ds_remaining' => array('hadoop:service=DataNode,name=FSDatasetState-.*', 'Remaining'),
20 | 'ds_used' => array('hadoop:service=DataNode,name=FSDatasetState-.*', 'DfsUsed'),
21 | 'ds_failed' => array('hadoop:service=DataNode,name=FSDatasetState-.*', 'NumFailedVolumes'),
22 | 'blocks_read' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blocks_?read'),
23 | 'blocks_removed' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blocks_?removed'),
24 | 'blocks_replicated' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blocks_?replicated'),
25 | 'blocks_verified' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blocks_?verified'),
26 | 'blocks_written' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blocks_?written'),
27 | 'bytes_read' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'bytes_?read'),
28 | 'bytes_written' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'bytes_?written'),
29 | 'reads_from_local_client' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'reads_?from_?local_?client'),
30 | 'writes_from_local_client' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'writes_?from_?local_?client'),
31 | 'reads_from_remote_client' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'reads_?from_?remote_?client'),
32 | 'writes_from_remote_client' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'writes_?from_?remote_?client'),
33 | 'ops_block_copy' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'copyBlockOpNumOps'),
34 | 'ops_block_read' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'readBlockOpNumOps'),
35 | 'ops_block_write' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'writeBlockOpNumOps'),
36 | 'ops_block_replace' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'replaceBlockOpNumOps'),
37 | 'ops_block_checksum' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blockChecksumOpNumOps'),
38 | 'ops_block_reports' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'blockReportsNumOps'),
39 | 'ops_heartbeat' => array('hadoop:service=DataNode,name=DataNodeActivity-.*', 'heartBeatsNumOps'),
40 | );
41 | $hadoop_stats['jobtracker'] = array(
42 | 'nodes_total' => array('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'nodes'),
43 | 'nodes_alive' => array('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'alive'),
44 | 'map_slots' => array('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'slots', 'map_slots'),
45 | 'map_slots_used' => array('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'slots', 'map_slots_used'),
46 | 'reduce_slots' => array('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'slots', 'reduce_slots'),
47 | 'reduce_slots_used' => array('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'slots', 'reduce_slots_used'),
48 | 'jobs' => array('hadoop:service=JobTracker,name=JobTrackerInfo', 'SummaryJson', 'jobs'),
49 | );
50 | $hadoop_stats['tasktracker'] = array(
51 | 'tasks_running' => array('hadoop:service=TaskTracker,name=TaskTrackerInfo', 'TasksInfoJson', 'running'),
52 | 'tasks_failed' => array('hadoop:service=TaskTracker,name=TaskTrackerInfo', 'TasksInfoJson', 'failed'),
53 | 'commit_pending' => array('hadoop:service=TaskTracker,name=TaskTrackerInfo', 'TasksInfoJson', 'commit_pending'),
54 | );
55 | $hadoop_stats['master'] = array(
56 | 'cluster_requests' => array('hadoop:service=Master,name=MasterStatistics', 'cluster_requests'),
57 | );
58 | $hadoop_stats['regionserver'] = array(
59 | 'cache_capacity' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'blockCacheSize'),
60 | 'cache_remaining' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'blockCacheFree'),
61 | 'cache_used' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'blockCacheCount'),
62 | 'cache_hit_count' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'blockCacheHitCount'),
63 | 'cache_miss_count' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'blockCacheMissCount'),
64 | 'regions' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'regions'),
65 | 'requests' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'requests'),
66 | 'stores' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'stores'),
67 | 'storefiles' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'storefiles'),
68 | 'compaction_queue' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'compactionQueueSize'),
69 | 'flush_queue' => array('hadoop:service=RegionServer,name=RegionServerStatistics', 'flushQueueSize'),
70 | );
71 | $hadoop_stats['zookeeper'] = array(
72 | 'packets_received' => array('org.apache.ZooKeeperService:name0=ReplicatedServer_id[0-9]+,name1=replica.[0-9]+,name2=(Leader|Follower)', 'PacketsReceived'),
73 | 'packets_sent' => array('org.apache.ZooKeeperService:name0=ReplicatedServer_id[0-9]+,name1=replica.[0-9]+,name2=(Leader|Follower)', 'PacketsSent'),
74 | 'outstanding_requests' => array('org.apache.ZooKeeperService:name0=ReplicatedServer_id[0-9]+,name1=replica.[0-9]+,name2=(Leader|Follower)', 'OutstandingRequests'),
75 | 'avg_request_latency' => array('org.apache.ZooKeeperService:name0=ReplicatedServer_id[0-9]+,name1=replica.[0-9]+,name2=(Leader|Follower)', 'AvgRequestLatency'),
76 | );
77 |
78 | return ss_jmxproxy($host, $jmxproxy, $jmxcreds, $hadoop_stats[$type]);
79 | }
80 |
--------------------------------------------------------------------------------
/src/test/java/com/github/mk23/jmxproxy/core/tests/MBeanTest.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.core.tests;
2 |
3 | import com.github.mk23.jmxproxy.core.MBean;
4 |
5 | import com.fasterxml.jackson.core.JsonProcessingException;
6 | import com.fasterxml.jackson.databind.JsonNode;
7 | import com.fasterxml.jackson.databind.ObjectMapper;
8 |
9 | import org.junit.Before;
10 | import org.junit.Rule;
11 | import org.junit.Test;
12 | import org.junit.rules.TestName;
13 |
14 | import static org.hamcrest.core.Is.is;
15 | import static org.junit.Assert.assertThat;
16 |
17 | public class MBeanTest {
18 | private final ObjectMapper om = new ObjectMapper();
19 |
20 | @Rule public TestName name = new TestName();
21 |
22 | private String asJson(Object object) throws JsonProcessingException {
23 | return om.writeValueAsString(object);
24 | }
25 |
26 | @Before
27 | public void printTestName() {
28 | System.out.println(" -> " + name.getMethodName());
29 | }
30 |
31 | @Test
32 | public void checkEmptyMBean() throws Exception {
33 | final MBean mbean = new MBean();
34 | final String expected = new String("{}");
35 |
36 | assertThat("check empty mbean", asJson(mbean), is(expected));
37 | }
38 |
39 | @Test
40 | public void checkEmptyMBeanAttributeList() throws Exception {
41 | final MBean mbean = new MBean();
42 | final String expected = new String("[]");
43 |
44 | assertThat("check empty mbean attribute list", asJson(mbean.getAttributes()), is(expected));
45 | }
46 |
47 | @Test
48 | public void checkMissingAttribute() throws Exception {
49 | final MBean mbean = new MBean();
50 | final String expected = new String("null");
51 |
52 | assertThat("check missing attribute", asJson(mbean.getAttribute("attribute")), is(expected));
53 | }
54 |
55 | @Test
56 | public void checkNonexistingAttribute() throws Exception {
57 | final MBean mbean = new MBean();
58 | final String expected = new String("false");
59 |
60 | assertThat("check attribute does not exist", asJson(mbean.hasAttribute("attribute")), is(expected));
61 | }
62 |
63 | @Test
64 | public void checkAddAttributeExists() throws Exception {
65 | final MBean mbean = new MBean();
66 | mbean.addAttribute("attribute", null);
67 |
68 | final String expected = new String("true");
69 |
70 | assertThat("check add attribute exists", asJson(mbean.hasAttribute("attribute")), is(expected));
71 | }
72 |
73 | @Test
74 | public void checkAddSingleDefaultAttributeFull() throws Exception {
75 | final MBean mbean = new MBean();
76 | mbean.addAttribute("attribute", null);
77 |
78 | final String expected = new String("{\"attribute\":null}");
79 |
80 | assertThat("check add single default attribute full", asJson(mbean), is(expected));
81 | }
82 |
83 | @Test
84 | public void checkAddSingleDefaultAttributeList() throws Exception {
85 | final MBean mbean = new MBean();
86 | mbean.addAttribute("attribute", null);
87 |
88 | final String expected = new String("[\"attribute\"]");
89 |
90 | assertThat("check add single default attribute list", asJson(mbean.getAttributes()), is(expected));
91 | }
92 |
93 | @Test
94 | public void checkAddSingleDefaultAttributeBare() throws Exception {
95 | final MBean mbean = new MBean();
96 | mbean.addAttribute("attribute", null);
97 |
98 | final String expected = new String("null");
99 |
100 | assertThat("check add single default attribute bare", asJson(mbean.getAttribute("attribute")), is(expected));
101 | }
102 |
103 | @Test
104 | public void checkAddMultiDefaultAttributeFull() throws Exception {
105 | final MBean mbean = new MBean();
106 | mbean.addAttribute("attribute", "val1");
107 | mbean.addAttribute("attribute", "val2");
108 |
109 | final String expected = new String("{\"attribute\":\"val2\"}");
110 |
111 | assertThat("check add multi default attribute full", asJson(mbean), is(expected));
112 | }
113 |
114 | @Test
115 | public void checkAddMultiDefaultAttributeBare() throws Exception {
116 | final MBean mbean = new MBean();
117 | mbean.addAttribute("attribute", "val1");
118 | mbean.addAttribute("attribute", "val2");
119 |
120 | final String expected = new String("\"val2\"");
121 |
122 | assertThat("check add multi default attribute bare", asJson(mbean.getAttribute("attribute")), is(expected));
123 | }
124 |
125 | @Test
126 | public void checkAddMultiDefaultAttributeHistoryFull() throws Exception {
127 | final MBean mbean = new MBean();
128 | mbean.addAttribute("attribute", "val1");
129 | mbean.addAttribute("attribute", "val2");
130 | mbean.setLimit(0);
131 |
132 | final String expected = new String("{\"attribute\":[\"val2\"]}");
133 |
134 | assertThat("check add single attribute default history full", asJson(mbean), is(expected));
135 | }
136 |
137 | @Test
138 | public void checkAddMultiExplicitAttributeHistoryFull() throws Exception {
139 | final MBean mbean = new MBean(1);
140 | mbean.addAttribute("attribute", "val1");
141 | mbean.addAttribute("attribute", "val2");
142 | mbean.setLimit(0);
143 |
144 | final String expected = new String("{\"attribute\":[\"val2\"]}");
145 |
146 | assertThat("check add multi explicit attribute history full", asJson(mbean), is(expected));
147 | }
148 |
149 | @Test
150 | public void checkAddMultiAttributeHistoryFull() throws Exception {
151 | final MBean mbean = new MBean(2);
152 | mbean.addAttribute("attribute", "val1");
153 | mbean.addAttribute("attribute", "val2");
154 | mbean.setLimit(0);
155 |
156 | final String expected = new String("{\"attribute\":[\"val2\",\"val1\"]}");
157 |
158 | assertThat("check add multiple attributes history full", asJson(mbean), is(expected));
159 | }
160 |
161 | @Test
162 | public void checkAddMultiAttributeHistoryFullLimit() throws Exception {
163 | final MBean mbean = new MBean(2);
164 | mbean.addAttribute("attribute", "val1");
165 | mbean.addAttribute("attribute", "val2");
166 | mbean.setLimit(1);
167 |
168 | final String expected = new String("{\"attribute\":[\"val2\"]}");
169 |
170 | assertThat("check add multiple attributes history full limited", asJson(mbean), is(expected));
171 | }
172 |
173 | @Test
174 | public void checkAddMultiAttributeHistoryBare() throws Exception {
175 | final MBean mbean = new MBean(2);
176 | mbean.addAttribute("attribute", "val1");
177 | mbean.addAttribute("attribute", "val2");
178 |
179 | final String expected = new String("[\"val2\",\"val1\"]");
180 |
181 | assertThat("check add multiple attributes history bare", asJson(mbean.getAttributes("attribute", 0)), is(expected));
182 | }
183 |
184 | @Test
185 | public void checkAddMultiAttributeHistoryBareLimit() throws Exception {
186 | final MBean mbean = new MBean(2);
187 | mbean.addAttribute("attribute", "val1");
188 | mbean.addAttribute("attribute", "val2");
189 |
190 | final String expected = new String("[\"val2\"]");
191 |
192 | assertThat("check add multiple attributes history bare limited", asJson(mbean.getAttributes("attribute", 1)), is(expected));
193 | }
194 | }
195 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/core/MBean.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.core;
2 |
3 | import com.github.mk23.jmxproxy.util.History;
4 |
5 | import com.fasterxml.jackson.core.JsonGenerator;
6 | import com.fasterxml.jackson.core.JsonProcessingException;
7 | import com.fasterxml.jackson.databind.JsonSerializable;
8 | import com.fasterxml.jackson.databind.SerializerProvider;
9 | import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
10 |
11 | import java.io.IOException;
12 |
13 | import java.util.Collections;
14 | import java.util.HashMap;
15 | import java.util.List;
16 | import java.util.Map;
17 | import java.util.Set;
18 |
19 | /**
20 | * JMX MBean tracker and serializer.
21 | *
22 | * Maintains a map of JMX {@link Attribute} names and a {@link History} of
23 | * their values. Implements JsonSerializable interface to convert the
24 | * stored map into JSON.
25 | *
26 | * @see com.fasterxml.jackson.databind.JsonSerializable
27 | *
28 | * @since 2018-02-08
29 | * @author mk23
30 | * @version 3.4.0
31 | */
32 | public class MBean implements JsonSerializable {
33 | private final int historySize;
34 |
35 | private final Map> attributes;
36 | private final ThreadLocal limit = new ThreadLocal() {
37 | @Override protected Integer initialValue() {
38 | return -1;
39 | }
40 | };
41 |
42 | /**
43 | * Default constructor.
44 | *
45 | * Creates a map of {@link Attribute} name to {@link History} of associated values.
46 | */
47 | public MBean() {
48 | this.historySize = 1;
49 | attributes = new HashMap>();
50 | }
51 |
52 | /**
53 | * Default constructor.
54 | *
55 | * Creates a map of {@link Attribute} name to {@link History} of associated values.
56 | *
57 | * @param historySize number of items to preserve in the associated {@link History}.
58 | */
59 | public MBean(final int historySize) {
60 | this.historySize = historySize;
61 | attributes = new HashMap>();
62 | }
63 |
64 | /**
65 | * Inserts a new Attribute name to History association.
66 | *
67 | * Optionally creates a new {@link History} object and inserts into the map store associating
68 | * it to the specified attribute name. Appends the specified {@link Attribute} value to the
69 | * {@link History}.
70 | *
71 | * @param attributeName name of the {@link Attribute} used as the map key.
72 | * @param attributeObject value of the {@link Attribute} added to history.
73 | */
74 | public final void addAttribute(final String attributeName, final Object attributeObject) {
75 | if (!attributes.containsKey(attributeName)) {
76 | attributes.put(attributeName, new History(historySize));
77 | }
78 |
79 | attributes.get(attributeName).add(new Attribute(attributeObject));
80 | }
81 |
82 | /**
83 | * Sets the thread local history request limit.
84 | *
85 | * Set the thread local limit for all {@link History} when serializing to JSON.
86 | * Because this method returns its object, requesting serialization can be done
87 | * with a single statement.
88 | *
89 | * For example
90 | *
91 | * return Response.ok(mbean.setLimit(5)).build();
92 | *
93 | * @see javax.ws.rs.core.Response
94 | *
95 | * @param bound the number of items to retreive from {@link History} for this thread.
96 | *
97 | * @return this mbean object for chaining calls.
98 | */
99 | public final MBean setLimit(final Integer bound) {
100 | limit.set(bound);
101 | return this;
102 | }
103 |
104 | /**
105 | * Tester for attribute name.
106 | *
107 | * Checks for requested {@link Attribute} name in the map store.
108 | *
109 | * @param attribute name of the {@link Attribute} to look up in the map store.
110 | *
111 | * @return true if the {@link Attribute} exists in the map store, false otherwise.
112 | */
113 | public final boolean hasAttribute(final String attribute) {
114 | return attributes.containsKey(attribute);
115 | }
116 |
117 | /**
118 | * Getter for attribute names.
119 | *
120 | * Extracts and returns the unique {@link Set} of all currently stored {@link Attribute} names.
121 | *
122 | * @return {@link Set} of {@link Attribute} name {@link String}s.
123 | */
124 | public final Set getAttributes() {
125 | return attributes.keySet();
126 | }
127 |
128 | /**
129 | * Getter for most recent attribute.
130 | *
131 | * Fetches the most recent {@link Attribute} value for the specified name from the
132 | * associated {@link History} in the map store.
133 | *
134 | * @param attribute name of the {@link Attribute} to look up in the map store.
135 | *
136 | * @return latest {@link Attribute} object from {@link History} if found, null otherwise.
137 | */
138 | public final Attribute getAttribute(final String attribute) {
139 | if (hasAttribute(attribute)) {
140 | return attributes.get(attribute).getLast();
141 | }
142 |
143 | return null;
144 | }
145 |
146 | /**
147 | * Getter for a subset of historical attribute values.
148 | *
149 | * Fetches an array, limited by the requested bound, of most recent {@link Attribute} values
150 | * for the specified name from the associated {@link History} in the map store.
151 | *
152 | * @param attribute name of the {@link Attribute} to look up in the map store.
153 | * @param bound size of the resulting array or full history if this exceeds capacity or less than 1.
154 | *
155 | * @return {@link List} of the latest {@link Attribute} objects from {@link History} if found, empty otherwise.
156 | */
157 | public final List getAttributes(final String attribute, final int bound) {
158 | if (hasAttribute(attribute)) {
159 | return attributes.get(attribute).get(bound);
160 | }
161 |
162 | return Collections.emptyList();
163 | }
164 |
165 | /** {@inheritDoc} */
166 | @Override
167 | public final void serialize(
168 | final JsonGenerator jgen,
169 | final SerializerProvider sp
170 | ) throws IOException, JsonProcessingException {
171 | serializeWithType(jgen, sp, null);
172 | }
173 |
174 | /** {@inheritDoc} */
175 | @Override
176 | public final void serializeWithType(
177 | final JsonGenerator jgen,
178 | final SerializerProvider sp,
179 | final TypeSerializer ts
180 | ) throws IOException, JsonProcessingException {
181 | buildJson(jgen);
182 | }
183 |
184 | private void buildJson(final JsonGenerator jgen) throws IOException, JsonProcessingException {
185 | int bound = limit.get();
186 |
187 | jgen.writeStartObject();
188 | for (Map.Entry> attributeEntry : attributes.entrySet()) {
189 | if (bound < 0) {
190 | jgen.writeObjectField(attributeEntry.getKey(), attributeEntry.getValue().getLast());
191 | } else {
192 | jgen.writeObjectField(attributeEntry.getKey(), attributeEntry.getValue().get(bound));
193 | }
194 | }
195 | jgen.writeEndObject();
196 | }
197 | }
198 |
--------------------------------------------------------------------------------
/src/main/resources/checkstyle.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
32 |
33 |
34 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/conf/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.conf;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
5 | import com.fasterxml.jackson.databind.annotation.JsonSerialize;
6 |
7 | import io.dropwizard.jackson.JsonSnakeCase;
8 |
9 | import io.dropwizard.util.Duration;
10 |
11 | import java.util.ArrayList;
12 | import java.util.List;
13 |
14 | import javax.validation.Valid;
15 | import javax.validation.constraints.Min;
16 |
17 | /**
18 | * Application configuration.
19 | *
20 | * Maintains application configuration fields. The application initializer
21 | * creates and marshals the object from JSON or Yaml config file. Setters
22 | * may be chained together for configuration building.
23 | *
24 | * For example:
25 | *
26 | *
27 | * AppConfig cfg = new AppConfig()
28 | * .setCleanInterval(Duration.minutes(5))
29 | * .setCacheDuration(Duration.minutes(10))
30 | * .setHistorySize(20);
31 | *
32 | *
33 | * @see io.dropwizard.util.Duration
34 | *
35 | * @since 2016-01-28
36 | * @author mk23
37 | * @version 3.3.6
38 | */
39 | @JsonSnakeCase
40 | public class AppConfig {
41 | /** Default clean interval minutes. */
42 | private static final int DEFAULT_CLEAN_INTERVAL = 1;
43 | /** Default cache duration minutes. */
44 | private static final int DEFAULT_CACHE_DURATION = 5;
45 | /** Default access duration minutes. */
46 | private static final int DEFAULT_ACCESS_DURATION = 30;
47 | /** Default jmx connect timeout milliseconds. */
48 | private static final int DEFAULT_CONNECT_TIMEOUT = 10000;
49 |
50 | /**
51 | * Configuration for how often to run the task that finds and
52 | * purges stale endpoints.
53 | */
54 | @Valid
55 | @JsonProperty
56 | @JsonDeserialize(using = DurationDeserializer.class)
57 | @JsonSerialize(using = DurationSerializer.class)
58 | private Duration cleanInterval = Duration.minutes(DEFAULT_CLEAN_INTERVAL);
59 |
60 | /**
61 | * Configuration for how often to reconnect to cached endpoints
62 | * and scrape available attributes.
63 | */
64 | @Valid
65 | @JsonProperty
66 | @JsonDeserialize(using = DurationDeserializer.class)
67 | @JsonSerialize(using = DurationSerializer.class)
68 | private Duration cacheDuration = Duration.minutes(DEFAULT_CACHE_DURATION);
69 |
70 | /**
71 | * Configuration for how long an endpoint goes unaccessed before
72 | * the purger tasks removes it from the cache.
73 | */
74 | @Valid
75 | @JsonProperty
76 | @JsonDeserialize(using = DurationDeserializer.class)
77 | @JsonSerialize(using = DurationSerializer.class)
78 | private Duration accessDuration = Duration.minutes(DEFAULT_ACCESS_DURATION);
79 |
80 | /**
81 | * Configuration for how long to wait for a JMX connection to complete
82 | * before declaring the endpoint as inaccessible.
83 | */
84 | @Valid
85 | @JsonProperty
86 | @JsonDeserialize(using = DurationDeserializer.class)
87 | @JsonSerialize(using = DurationSerializer.class)
88 | private Duration connectTimeout = Duration.minutes(DEFAULT_CONNECT_TIMEOUT);
89 |
90 | /**
91 | * Configuration for how many fetched attribute values to keep for
92 | * each cached endpoint.
93 | */
94 | @Min(1)
95 | @JsonProperty
96 | private int historySize = 1;
97 |
98 | /**
99 | * Configuration for whitelisted endpoints, allowing all when this
100 | * is empty.
101 | */
102 | @JsonProperty
103 | private List allowedEndpoints = new ArrayList();
104 |
105 | /**
106 | * Getter for cleanInterval.
107 | *
108 | * Configuration for how often to run the task that finds and
109 | * purges stale endpoints.
110 | *
111 | * @return Configured clean interval.
112 | */
113 | public final Duration getCleanInterval() {
114 | return cleanInterval;
115 | }
116 | /**
117 | * Setter for cleanInterval.
118 | *
119 | * @param cleanInterval period at which the purger tasks operates.
120 | *
121 | * @return Modified AppConfig for setter chaining.
122 | */
123 | public final AppConfig setCleanInterval(final Duration cleanInterval) {
124 | this.cleanInterval = cleanInterval;
125 | return this;
126 | }
127 |
128 | /**
129 | * Getter for cacheDuration.
130 | *
131 | * Configuration for how often to reconnect to cached endpoints
132 | * and scrape available attributes.
133 | *
134 | * @return Configured cache duration.
135 | */
136 | public final Duration getCacheDuration() {
137 | return cacheDuration;
138 | }
139 | /**
140 | * Setter for cacheDuration.
141 | *
142 | * @param cacheDuration period at which the endpoint cache
143 | * refreshes.
144 | *
145 | * @return Modified AppConfig for setter chaining.
146 | */
147 | public final AppConfig setCacheDuration(final Duration cacheDuration) {
148 | this.cacheDuration = cacheDuration;
149 | return this;
150 | }
151 |
152 | /**
153 | * Getter for accessDuration.
154 | *
155 | * Configuration for how long an endpoint goes unaccessed before
156 | * the purger tasks removes it from the cache.
157 | *
158 | * @return Configured access duration.
159 | */
160 | public final Duration getAccessDuration() {
161 | return accessDuration;
162 | }
163 | /**
164 | * Setter for accessDuration.
165 | *
166 | * @param accessDuration time before an enpoint is removed
167 | * from the cache.
168 | *
169 | * @return Modified AppConfig for setter chaining.
170 | */
171 | public final AppConfig setAccessDuration(final Duration accessDuration) {
172 | this.accessDuration = accessDuration;
173 | return this;
174 | }
175 |
176 | /**
177 | * Getter for connectTimeout.
178 | *
179 | * Configuration for how long to wait for a JMX connection to complete
180 | * before declaring the endpoint as inaccessible.
181 | *
182 | * @return Configured connect timeout.
183 | */
184 | public final Duration getConnectTimeout() {
185 | return connectTimeout;
186 | }
187 | /**
188 | * Setter for connectTimeout.
189 | *
190 | * @param connectTimeout time before an abandoning a new JMX connection.
191 | *
192 | * @return Modified AppConfig for setter chaining.
193 | */
194 | public final AppConfig setConnectTimeout(final Duration connectTimeout) {
195 | this.connectTimeout = connectTimeout;
196 | return this;
197 | }
198 |
199 | /**
200 | * Getter for historySize.
201 | *
202 | * Configuration for how many fetched attribute values to keep for
203 | * each cached endpoint.
204 | *
205 | * @return Configured history size.
206 | */
207 | public final int getHistorySize() {
208 | return historySize;
209 | }
210 | /**
211 | * Setter for historySize.
212 | *
213 | * @param historySize number of values to keep for all cached
214 | * attributes at every requested endpoint.
215 | *
216 | * @return Modified AppConfig for setter chaining.
217 | */
218 | public final AppConfig setHistorySize(final int historySize) {
219 | this.historySize = historySize;
220 | return this;
221 | }
222 |
223 | /**
224 | * Getter for allowedEndpoints.
225 | *
226 | * Configuration for whitelisted endpoints, allowing all when this
227 | * is empty.
228 | *
229 | * @return Configured {@link List} containing whitelisted endpoints.
230 | */
231 | public final List getAllowedEndpoints() {
232 | return allowedEndpoints;
233 | }
234 | /**
235 | * Setter for allowedEndpoints.
236 | *
237 | * @param allowedEndpoints {@link List} containing whitelisted endpoints.
238 | *
239 | * @return Modified AppConfig for setter chaining.
240 | */
241 | public final AppConfig setAllowedEndpoints(final List allowedEndpoints) {
242 | this.allowedEndpoints = allowedEndpoints;
243 | return this;
244 | }
245 | }
246 |
--------------------------------------------------------------------------------
/src/test/java/com/github/mk23/jmxproxy/core/tests/AttributeTest.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.core.tests;
2 |
3 | import com.github.mk23.jmxproxy.core.Attribute;
4 |
5 | import com.fasterxml.jackson.core.JsonProcessingException;
6 | import com.fasterxml.jackson.databind.JsonNode;
7 | import com.fasterxml.jackson.databind.ObjectMapper;
8 |
9 | import java.io.BufferedReader;
10 | import java.io.File;
11 | import java.io.FileReader;
12 | import java.io.IOException;
13 |
14 | import java.math.BigInteger;
15 |
16 | import java.util.Arrays;
17 | import java.util.ArrayList;
18 | import java.util.List;
19 |
20 | import javax.management.ObjectName;
21 |
22 | import org.junit.Before;
23 | import org.junit.Rule;
24 | import org.junit.Test;
25 | import org.junit.rules.TestName;
26 |
27 | import static io.dropwizard.testing.FixtureHelpers.fixture;
28 |
29 | import static org.hamcrest.core.Is.is;
30 | import static org.junit.Assert.assertThat;
31 |
32 | public class AttributeTest {
33 | private final ObjectMapper om = new ObjectMapper();
34 |
35 | @Rule public TestName name = new TestName();
36 |
37 | private String asJson(Object object) throws JsonProcessingException {
38 | return om.writeValueAsString(object);
39 | }
40 |
41 | private String jsonFixture(String filename) throws IOException {
42 | return om.writeValueAsString(om.readValue(fixture(filename), JsonNode.class));
43 | }
44 |
45 | @Before
46 | public void printTestName() {
47 | System.out.println(" -> " + name.getMethodName());
48 | }
49 |
50 | @Test
51 | public void checkBoolean() throws Exception {
52 | final Attribute attribute = new Attribute(true);
53 | final String expected = new String("true");
54 | final String acquired = asJson(attribute);
55 |
56 | assertThat("check boolean serialization", asJson(attribute), is(expected));
57 | }
58 |
59 | @Test
60 | public void checkBoxedBooleanArray() throws Exception {
61 | final Attribute attribute = new Attribute(new Boolean[]{true, !true});
62 | final String expected = jsonFixture("fixtures/boxed_boolean_array.json");
63 | final String acquired = asJson(attribute);
64 |
65 | assertThat("check boolean array serialization", asJson(attribute), is(expected));
66 | }
67 |
68 | @Test
69 | public void checkInt() throws Exception {
70 | final Attribute attribute = new Attribute(1);
71 | final String expected = new String("1");
72 |
73 | assertThat("check int serialization", asJson(attribute), is(expected));
74 | }
75 |
76 | @Test
77 | public void checkNegativeInt() throws Exception {
78 | final Attribute attribute = new Attribute(-1);
79 | final String expected = new String("-1");
80 |
81 | assertThat("check negative int serialization", asJson(attribute), is(expected));
82 | }
83 |
84 | @Test
85 | public void checkBigInt() throws Exception {
86 | final Attribute attribute = new Attribute(new BigInteger("36893488147419103232"));
87 | final String expected = new String("36893488147419103232");
88 |
89 | assertThat("check big int serialization", asJson(attribute), is(expected));
90 | }
91 |
92 | @Test
93 | public void checkNegativeBigInt() throws Exception {
94 | final Attribute attribute = new Attribute(new BigInteger("-36893488147419103232"));
95 | final String expected = new String("-36893488147419103232");
96 |
97 | assertThat("check negative big int serialization", asJson(attribute), is(expected));
98 | }
99 |
100 | @Test
101 | public void checkBoxedIntegerArray() throws Exception {
102 | final Attribute attribute = new Attribute(new Integer[]{1, 1 + 1});
103 | final String expected = jsonFixture("fixtures/boxed_integer_array.json");
104 |
105 | assertThat("check integer array serialization", asJson(attribute), is(expected));
106 | }
107 |
108 | @Test
109 | public void checkDouble() throws Exception {
110 | final Attribute attribute = new Attribute(1.23);
111 | final String expected = new String("1.23");
112 |
113 | assertThat("check double serialization", asJson(attribute), is(expected));
114 | }
115 |
116 | @Test
117 | public void checkNegativeDouble() throws Exception {
118 | final Attribute attribute = new Attribute(-1.23);
119 | final String expected = new String("-1.23");
120 |
121 | assertThat("check negative double serialization", asJson(attribute), is(expected));
122 | }
123 |
124 | @Test
125 | public void checkBoxedDoubleArray() throws Exception {
126 | final Attribute attribute = new Attribute(new Double[]{1.23, Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY});
127 | final String expected = jsonFixture("fixtures/boxed_double_array.json");
128 |
129 | assertThat("check double array serialization", asJson(attribute), is(expected));
130 | }
131 |
132 | @Test
133 | public void checkListInteger() throws Exception {
134 | final Attribute attribute = new Attribute(Arrays.asList(1, 2));
135 | final String expected = jsonFixture("fixtures/list_integer.json");
136 |
137 | assertThat("check integer list serialization", asJson(attribute), is(expected));
138 | }
139 |
140 | @Test
141 | public void checkListListInteger() throws Exception {
142 | final Attribute attribute = new Attribute(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4)));
143 | final String expected = jsonFixture("fixtures/list_list_integer.json");
144 |
145 | assertThat("check list of integer lists serialization", asJson(attribute), is(expected));
146 | }
147 |
148 | @Test
149 | public void checkString() throws Exception {
150 | final Attribute attribute = new Attribute("val");
151 | final String expected = new String("\"val\"");
152 |
153 | assertThat("check string serialization", asJson(attribute), is(expected));
154 | }
155 |
156 |
157 | @Test
158 | public void checkStringArray() throws Exception {
159 | final Attribute attribute = new Attribute(new String[]{"val1", "val2"});
160 | final String expected = jsonFixture("fixtures/list_string.json");
161 |
162 | assertThat("check string array serialization", asJson(attribute), is(expected));
163 | }
164 |
165 | @Test
166 | public void checkListString() throws Exception {
167 | final Attribute attribute = new Attribute(Arrays.asList("val1", "val2"));
168 | final String expected = jsonFixture("fixtures/list_string.json");
169 |
170 | assertThat("check string list serialization", asJson(attribute), is(expected));
171 | }
172 |
173 | @Test
174 | public void checkListListString() throws Exception {
175 | final Attribute attribute = new Attribute(Arrays.asList(Arrays.asList("val1", "val2"), Arrays.asList("val3", "val4")));
176 | final String expected = jsonFixture("fixtures/list_list_string.json");
177 |
178 | assertThat("check list of string lists serialization", asJson(attribute), is(expected));
179 | }
180 |
181 | @Test
182 | public void checkJsonStringString() throws Exception {
183 | final Attribute attribute = new Attribute("\n\"val\"\n");
184 | final String expected = new String("\"val\"");
185 |
186 | assertThat("check single json string serialization", asJson(attribute), is(expected));
187 | }
188 |
189 | @Test
190 | public void checkJsonStringInteger() throws Exception {
191 | final Attribute attribute = new Attribute("1");
192 | final String expected = new String("1");
193 |
194 | assertThat("check single json string serialization", asJson(attribute), is(expected));
195 | }
196 |
197 | @Test
198 | public void checkJsonStringNested() throws Exception {
199 | final Attribute attribute = new Attribute("null true 1 1.23 \"val\" {\"key1\": [\"val1\", [1, 2]], \"key2\": \"val2\"} [1, 1.23]");
200 | final String expected = jsonFixture("fixtures/multi_json_string.json");
201 |
202 | assertThat("check multiple json strings serialization", asJson(attribute), is(expected));
203 | }
204 |
205 | @Test
206 | public void checkNull() throws Exception {
207 | final Attribute attribute = new Attribute(null);
208 | final String expected = new String("null");
209 |
210 | assertThat("check null serialization", asJson(attribute), is(expected));
211 | }
212 | }
213 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/core/Attribute.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.core;
2 |
3 | import com.fasterxml.jackson.core.JsonGenerator;
4 | import com.fasterxml.jackson.core.JsonParser;
5 | import com.fasterxml.jackson.core.JsonParseException;
6 | import com.fasterxml.jackson.core.JsonProcessingException;
7 | import com.fasterxml.jackson.core.JsonToken;
8 | import com.fasterxml.jackson.databind.JsonNode;
9 | import com.fasterxml.jackson.databind.JsonSerializable;
10 | import com.fasterxml.jackson.databind.ObjectMapper;
11 | import com.fasterxml.jackson.databind.SerializerProvider;
12 | import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
13 |
14 | import java.io.IOException;
15 |
16 | import java.lang.reflect.Array;
17 |
18 | import java.util.List;
19 | import java.util.ArrayList;
20 |
21 | import javax.management.openmbean.CompositeData;
22 | import javax.management.openmbean.TabularData;
23 |
24 | /**
25 | * JMX Attribute tracker and serializer.
26 | *
27 | * Saves a JMX Attribute value object. Implements JsonSerializable
28 | * interface to convert the stored value into JSON. On serialization,
29 | * recursively inspects the value type and marshals it to JSON using
30 | * the supplied JsonGenerator. For {@link Array}, {@link Iterable},
31 | * {@link TabularData}, builds a JSON array. For {@link CompositeData},
32 | * builds a JSON object. For any other native types or null values, builds
33 | * a JSON equivalent.
34 | *
35 | * Special cases:
36 | *
37 | *
38 | *
39 | * Any {@link String} that contains valid JSON, will also be recursively
40 | * serialized using a dynamic JsonParser.
41 | *
42 | *
43 | * Any NaN {@link Double} or {@link Float} value will yield
44 | * a JSON string "NaN".
45 | *
46 | *
47 | * Any infinite {@link Double} or {@link Float} value will
48 | * yield a JSON string "Infinity".
49 | *
50 | *
51 | *
52 | * @see com.fasterxml.jackson.core.JsonGenerator
53 | * @see com.fasterxml.jackson.core.JsonParser
54 | * @see com.fasterxml.jackson.databind.JsonSerializable
55 | *
56 | * @since 2015-05-11
57 | * @author mk23
58 | * @version 3.2.0
59 | */
60 | public class Attribute implements JsonSerializable {
61 | private Object attributeValue;
62 |
63 | /**
64 | * Default constructor.
65 | *
66 | * Saves the JMX Attribute object for later serialization.
67 | *
68 | * @param attributeValue object for later serialization.
69 | */
70 | public Attribute(final Object attributeValue) {
71 | this.attributeValue = attributeValue;
72 | }
73 |
74 | /** {@inheritDoc} */
75 | @Override
76 | public final void serialize(
77 | final JsonGenerator jgen,
78 | final SerializerProvider sp
79 | ) throws IOException, JsonProcessingException {
80 | serializeWithType(jgen, sp, null);
81 | }
82 |
83 | /** {@inheritDoc} */
84 | @Override
85 | public final void serializeWithType(
86 | final JsonGenerator jgen,
87 | final SerializerProvider sp,
88 | final TypeSerializer ts
89 | ) throws IOException, JsonProcessingException {
90 | buildJson(jgen, attributeValue);
91 | }
92 |
93 | /**
94 | * JMX Attribute value JSON serializer.
95 | *
96 | * Inspects the stored JMX Attribute value type and serializes it to
97 | * JSON using the supplied JsonGenerator. Recursively calls itself
98 | * if finding JMX collections. For an {@link Array}, {@link Iterable},
99 | * or {@link TabularData}, builds a JSON array. For {@link CompositeData},
100 | * builds a JSON object. For any other native types or null values, builds
101 | * a JSON equivalent.
102 | *
103 | * Special cases:
104 | *
105 | *
106 | *
107 | * Any {@link String} that contains valid JSON, will also be recursively
108 | * serialized using a dynamic JsonParser.
109 | *
110 | *
111 | * Any NaN {@link Double} or {@link Float} value will yield
112 | * a JSON string "NaN".
113 | *
114 | *
115 | * Any infinite {@link Double} or {@link Float} value will
116 | * yield a JSON string "Infinity".
117 | *
118 | *
119 | *
120 | * @see com.fasterxml.jackson.core.JsonGenerator
121 | * @see com.fasterxml.jackson.core.JsonParser
122 | *
123 | * @param jgen The jersey-supplied JSON generator to use for serialization.
124 | * @param objectValue The JMX Attribute value or an element of a collection to serialize.
125 | */
126 | private void buildJson(
127 | final JsonGenerator jgen,
128 | final Object objectValue
129 | ) throws IOException, JsonProcessingException {
130 | if (objectValue == null) {
131 | jgen.writeNull();
132 | } else if (objectValue instanceof Boolean) {
133 | jgen.writeBoolean((Boolean) objectValue);
134 | } else if (objectValue instanceof JsonNode) {
135 | jgen.writeTree((JsonNode) objectValue);
136 | } else if (objectValue.getClass().isArray()) {
137 | jgen.writeStartArray();
138 | int length = Array.getLength(objectValue);
139 | for (int i = 0; i < length; i++) {
140 | buildJson(jgen, Array.get(objectValue, i));
141 | }
142 | jgen.writeEndArray();
143 | } else if (objectValue instanceof Iterable) {
144 | Iterable data = (Iterable) objectValue;
145 | jgen.writeStartArray();
146 | for (Object objectEntry : data) {
147 | buildJson(jgen, objectEntry);
148 | }
149 | jgen.writeEndArray();
150 | } else if (objectValue instanceof TabularData) {
151 | TabularData data = (TabularData) objectValue;
152 | jgen.writeStartArray();
153 | for (Object objectEntry : data.values()) {
154 | buildJson(jgen, objectEntry);
155 | }
156 | jgen.writeEndArray();
157 | } else if (objectValue instanceof CompositeData) {
158 | CompositeData data = (CompositeData) objectValue;
159 | jgen.writeStartObject();
160 | for (String objectEntry : data.getCompositeType().keySet()) {
161 | jgen.writeFieldName(objectEntry);
162 | buildJson(jgen, data.get(objectEntry));
163 | }
164 | jgen.writeEndObject();
165 | } else if (objectValue instanceof Number) {
166 | Double data = ((Number) objectValue).doubleValue();
167 | if (data.isNaN()) {
168 | jgen.writeString("NaN");
169 | } else if (data.isInfinite()) {
170 | jgen.writeString("Infinity");
171 | } else {
172 | jgen.writeNumber(((Number) objectValue).toString());
173 | }
174 | } else {
175 | try {
176 | String input = objectValue.toString();
177 | List parts = new ArrayList();
178 | ObjectMapper mapper = new ObjectMapper();
179 | JsonParser parser = mapper.getFactory().createParser(input);
180 |
181 | for (parser.nextToken(); parser.hasCurrentToken(); parser.nextToken()) {
182 | JsonToken tok = parser.getCurrentToken();
183 | long pos = parser.getTokenLocation().getCharOffset();
184 | if (tok == JsonToken.START_OBJECT || tok == JsonToken.START_ARRAY) {
185 | parser.skipChildren();
186 | }
187 | long end = parser.getTokenLocation().getCharOffset()
188 | + parser.getTextLength()
189 | + (tok == JsonToken.VALUE_STRING ? 2 : 0);
190 | parts.add(mapper.readTree(input.substring((int) pos, (int) end)));
191 | }
192 |
193 | if (parts.isEmpty()) {
194 | jgen.writeString("");
195 | } else if (parts.size() == 1) {
196 | buildJson(jgen, parts.get(0));
197 | } else {
198 | buildJson(jgen, parts);
199 | }
200 | } catch (JsonParseException e) {
201 | jgen.writeString(objectValue.toString());
202 | }
203 | }
204 | }
205 | }
206 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/jmx/ConnectionWorker.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.jmx;
2 |
3 | import com.github.mk23.jmxproxy.core.Host;
4 | import com.github.mk23.jmxproxy.core.MBean;
5 |
6 | import java.io.IOException;
7 |
8 | import java.net.MalformedURLException;
9 |
10 | import java.util.HashMap;
11 | import java.util.HashSet;
12 | import java.util.Map;
13 | import java.util.Set;
14 |
15 | import java.util.concurrent.CountDownLatch;
16 | import java.util.concurrent.Executors;
17 | import java.util.concurrent.ScheduledExecutorService;
18 | import java.util.concurrent.TimeUnit;
19 |
20 | import javax.management.MBeanAttributeInfo;
21 | import javax.management.MBeanServerConnection;
22 | import javax.management.ObjectName;
23 |
24 | import javax.management.remote.JMXConnector;
25 | import javax.management.remote.JMXConnectorFactory;
26 | import javax.management.remote.JMXServiceURL;
27 |
28 | import org.slf4j.Logger;
29 | import org.slf4j.LoggerFactory;
30 |
31 | /**
32 | * JMX fetcher and tracker.
33 | *
34 | * Creates a {@link ScheduledExecutorService} to periodically make to a {@link JMXConnector}
35 | * to a JMX endpoint. At every execution, discovers and fetches all remote registered mbeans
36 | * and populates the local {@link Host} object with assicated {@link MBean}s and their
37 | * {@link com.github.mk23.jmxproxy.core.Attribute}. Also maintains the {@link Host} access
38 | * time to allow reaping of
39 | * unaccessed workers.
40 | *
41 | * @since 2015-05-11
42 | * @author mk23
43 | * @version 3.2.0
44 | */
45 | public class ConnectionWorker {
46 | private static final Logger LOG = LoggerFactory.getLogger(ConnectionWorker.class);
47 |
48 | private Host host;
49 | private ConnectionCredentials authCreds;
50 |
51 | private boolean authValid;
52 | private IOException connError;
53 |
54 | private final Object fetchLock;
55 | private final int historySize;
56 | private final long cacheDuration;
57 |
58 | private final JMXServiceURL url;
59 |
60 | private long accessTime;
61 |
62 | private ScheduledExecutorService pollerSvc;
63 |
64 | /**
65 | * Default constructor.
66 | *
67 | * Initializes the {@link JMXServiceURL} to the specified hostName
68 | * and starts the {@link ScheduledExecutorService} for periodically
69 | * connecting and fetching JMX objects.
70 | *
71 | * @param hostName host:port {@link String} JMX agent target.
72 | * @param cacheDuration period in milliseconds for how often to connect to the JMX agent.
73 | * @param historySize number of {@link com.github.mk23.jmxproxy.core.Attribute}s to keep
74 | * per {@link MBean} {@link com.github.mk23.jmxproxy.util.History}.
75 | *
76 | * @throws MalformedURLException if the specified host is not a valid host:port {@link String}.
77 | */
78 | public ConnectionWorker(
79 | final String hostName,
80 | final long cacheDuration,
81 | final int historySize
82 | ) throws MalformedURLException {
83 | this.historySize = historySize;
84 | this.cacheDuration = cacheDuration;
85 |
86 | fetchLock = new Object();
87 | url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + hostName + "/jmxrmi");
88 | }
89 |
90 | /**
91 | * Getter for host.
92 | *
93 | * Fetches the tracked {@link Host} object and resets the request access time.
94 | *
95 | * @param testCreds optional {@link ConnectionCredentials} for the provided JMX agent or null if none.
96 | *
97 | * @return {@link Host} as populated by the most recent fetch operation.
98 | *
99 | * @throws IOException if the specified host is unreachable.
100 | * @throws SecurityException if the specified credentials to the host are incorrect.
101 | */
102 | public final Host getHost(final ConnectionCredentials testCreds) throws IOException, SecurityException {
103 | accessTime = System.currentTimeMillis();
104 |
105 | if (host == null) {
106 | final CountDownLatch ready = new CountDownLatch(1);
107 |
108 | shutdown();
109 |
110 | host = new Host();
111 | authCreds = (testCreds != null) ? testCreds : new ConnectionCredentials();
112 |
113 | pollerSvc = Executors.newSingleThreadScheduledExecutor();
114 | pollerSvc.scheduleAtFixedRate(new Runnable() {
115 | @Override
116 | public void run() {
117 | try {
118 | fetchJMXValues();
119 | } catch (Exception e) {
120 | e.printStackTrace();
121 | }
122 | ready.countDown();
123 | }
124 | }, 0, cacheDuration, TimeUnit.MILLISECONDS);
125 |
126 | try {
127 | ready.await();
128 | } catch (InterruptedException e) {
129 | LOG.error("unable to finish first run", e);
130 | }
131 | }
132 |
133 | if (connError != null) {
134 | throw connError;
135 | } else if (!authCreds.equals(testCreds) && authValid) {
136 | throw new SecurityException();
137 | } else if (!authValid) {
138 | throw new SecurityException();
139 | } else {
140 | synchronized (fetchLock) {
141 | return host;
142 | }
143 | }
144 | }
145 |
146 | /**
147 | *
Checks expiration of this worker object.
148 | *
149 | * Checks the last access time against the provided duration limit to determine if this worker
150 | * is expired and can be purged.
151 | *
152 | * @param accessDuration time in milliseconds of no access after which this worker is expired.
153 | *
154 | * @return true if this worker hasn't been accessed recently, false otherwise.
155 | */
156 | public final boolean isExpired(final long accessDuration) {
157 | return System.currentTimeMillis() - accessTime > accessDuration;
158 | }
159 |
160 | /**
161 | * Stops the scheduled fetcher.
162 | *
163 | * Signals the {@link ScheduledExecutorService} to shutdown for process termination cleanup.
164 | */
165 | public final void shutdown() {
166 | if (pollerSvc != null && !pollerSvc.isShutdown()) {
167 | pollerSvc.shutdown();
168 | }
169 | }
170 |
171 | private void fetchJMXValues() {
172 | JMXConnector connection = null;
173 | MBeanServerConnection server = null;
174 |
175 | Map environment = new HashMap();
176 | if (authCreds != null) {
177 | environment.put(JMXConnector.CREDENTIALS, new String[]{authCreds.getUsername(), authCreds.getPassword()});
178 | }
179 |
180 | try {
181 | LOG.debug("connecting to mbean server " + url);
182 |
183 | synchronized (fetchLock) {
184 | connection = JMXConnectorFactory.connect(url, environment);
185 | server = connection.getMBeanServerConnection();
186 |
187 | authValid = true;
188 | connError = null;
189 |
190 | Set freshMBeans = new HashSet();
191 |
192 | for (ObjectName mbeanName : server.queryNames(null, null)) {
193 | LOG.debug("discovered mbean " + mbeanName);
194 | freshMBeans.add(mbeanName.toString());
195 |
196 | MBean mbean = host.addMBean(mbeanName.toString(), historySize);
197 | try {
198 | for (MBeanAttributeInfo attributeObject : server.getMBeanInfo(mbeanName).getAttributes()) {
199 | if (attributeObject.isReadable()) {
200 | try {
201 | Object attribute = server.getAttribute(mbeanName, attributeObject.getName());
202 |
203 | mbean.addAttribute(attributeObject.getName(), attribute);
204 | } catch (java.lang.NullPointerException
205 | | java.rmi.RemoteException
206 | | javax.management.JMException
207 | | javax.management.JMRuntimeException e) {
208 | LOG.error("failed to add attribute " + attributeObject.toString() + ": " + e);
209 | }
210 | }
211 | }
212 | } catch (javax.management.JMException e) {
213 | LOG.error("failed to get mbean info for " + mbeanName, e);
214 | }
215 | }
216 |
217 | Set staleMBeans = new HashSet(host.getMBeans());
218 | staleMBeans.removeAll(freshMBeans);
219 | for (String mbeanName : staleMBeans) {
220 | host.removeMBean(mbeanName);
221 | LOG.debug("removed stale mbean " + mbeanName);
222 | }
223 | }
224 | } catch (IOException e) {
225 | host = null;
226 | connError = e;
227 | LOG.error("communication failure with " + url, e);
228 | } catch (SecurityException e) {
229 | host = null;
230 | authValid = false;
231 | LOG.error("invalid credentials for " + url, e);
232 | } finally {
233 | if (connection != null) {
234 | try {
235 | connection.close();
236 | LOG.debug("disconnected from " + url);
237 | } catch (IOException e) {
238 | LOG.error("failed to disconnect from " + url, e);
239 | } finally {
240 | connection = null;
241 | }
242 | }
243 | }
244 | }
245 | }
246 |
--------------------------------------------------------------------------------
/src/main/java/com/github/mk23/jmxproxy/jmx/ConnectionManager.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.jmx;
2 |
3 | import com.github.mk23.jmxproxy.conf.AppConfig;
4 | import com.github.mk23.jmxproxy.core.Host;
5 |
6 | import io.dropwizard.lifecycle.Managed;
7 |
8 | import java.io.IOException;
9 |
10 | import java.net.MalformedURLException;
11 |
12 | import java.rmi.server.RMISocketFactory;
13 |
14 | import java.util.Map;
15 | import java.util.Set;
16 |
17 | import java.util.concurrent.ConcurrentHashMap;
18 | import java.util.concurrent.Executors;
19 | import java.util.concurrent.ScheduledExecutorService;
20 | import java.util.concurrent.TimeUnit;
21 |
22 | import javax.ws.rs.core.Response;
23 | import javax.ws.rs.WebApplicationException;
24 |
25 | import org.slf4j.Logger;
26 | import org.slf4j.LoggerFactory;
27 |
28 | /**
29 | * Main application lifecycle object that manages all JMX Agent Connections.
30 | *
31 | * Implements the dropwizard lifecycle Managed interface to create the object responsible
32 | * for all application data management. Creates workers for connecting to JMX endpoints and
33 | * handles requests for data retreival. Controls purging unaccessed endpoints as well as
34 | * their runtime state.
35 | *
36 | * @see io.dropwizard.lifecycle.Managed
37 | *
38 | * @since 2015-05-11
39 | * @author mk23
40 | * @version 3.2.0
41 | */
42 | public class ConnectionManager implements Managed {
43 | private static final Logger LOG = LoggerFactory.getLogger(ConnectionManager.class);
44 |
45 | private final AppConfig config;
46 |
47 | private final Map hosts;
48 | private final ScheduledExecutorService purge;
49 |
50 | private boolean started = false;
51 |
52 | /**
53 | * Default constructor.
54 | *
55 | * Called by the application initializer. Creates the map of host:port {@link String}s to
56 | * associated {@link ConnectionWorker} instances. Creates an instance of the unaccessed
57 | * endpoints purge thread. Saves the provided applicaiton configuration for later retreival
58 | * request.
59 | *
60 | * @param config configuration as specified by the administrator at application invocation.
61 | */
62 | public ConnectionManager(final AppConfig config) {
63 | this.config = config;
64 |
65 | int timeout = (int) config.getConnectTimeout().toMilliseconds();
66 | try {
67 | RMISocketFactory.setSocketFactory(new TimeoutRMISocketFactory(timeout));
68 | } catch (IOException e) {
69 | LOG.info("socket factory already defined, resetting timeout to " + timeout + "ms");
70 |
71 | TimeoutRMISocketFactory sf = (TimeoutRMISocketFactory) RMISocketFactory.getSocketFactory();
72 | sf.setTimeout(timeout);
73 | }
74 |
75 | hosts = new ConcurrentHashMap();
76 | purge = Executors.newSingleThreadScheduledExecutor();
77 | }
78 |
79 | /**
80 | * Getter for config.
81 | *
82 | * Fetches the application run-time configuration object.
83 | *
84 | * @return application configuration.
85 | */
86 | public final AppConfig getConfiguration() {
87 | return config;
88 | }
89 |
90 | /**
91 | * Getter for hosts.
92 | *
93 | * Fetches the {@link Set} of {@link ConnectionWorker} name {@link String}s.
94 | *
95 | * @return {@link Set} of {@link ConnectionWorker} name {@link String}s.
96 | */
97 | public final Set getHosts() {
98 | return hosts.keySet();
99 | }
100 |
101 | /**
102 | * Deleter for host.
103 | *
104 | * Attempts to remove the specified host from the {@link ConnectionWorker} map store.
105 | *
106 | * @param host endpoint host:port {@link String}.
107 | *
108 | * @return true if the key is found in the map store.
109 | *
110 | * @throws WebApplicationException if key is not found in the map store.
111 | */
112 | public final boolean delHost(final String host) throws WebApplicationException {
113 | ConnectionWorker worker = hosts.remove(host);
114 | if (worker != null) {
115 | LOG.debug("purging " + host);
116 | worker.shutdown();
117 |
118 | return true;
119 | } else {
120 | throw new WebApplicationException(Response.Status.NOT_FOUND);
121 | }
122 | }
123 |
124 | /**
125 | * Anonymous getter for host.
126 | *
127 | * Fetches the specified {@link Host} with anonymous (null) credentials.
128 | * Equivalent to calling:
129 | *
130 | * return getHost(host, null);
131 | *
132 | * @param host endpoint host:port {@link String}.
133 | *
134 | * @return {@link Host} object for the requested endpoint.
135 | *
136 | * @throws WebApplicationException if unauthorized, forbidden, or invalid endpoint.
137 | */
138 | public final Host getHost(final String host) throws WebApplicationException {
139 | return getHost(host, null);
140 | }
141 |
142 | /**
143 | * Authenticated getter for host.
144 | *
145 | * Fetches the specified {@link Host} with provided credentials. Validates endpoint
146 | * access against a configured whitelist. Validates provided credentials against
147 | * previous requests and if different, a new {@link ConnectionWorker} object is
148 | * instanciated and associated with the specified endpoint. Lastly, if specified
149 | * endpoint is not yet in the map store, instanciates a new {@link ConnectionWorker}
150 | * and saves it for later retreival.
151 | *
152 | * @param host endpoint host:port {@link String}.
153 | * @param auth endpoint {@link ConnectionCredentials} or null for anonymous access.
154 | *
155 | * @return {@link Host} object for the requested endpoint.
156 | *
157 | * @throws WebApplicationException if
158 | *
159 | * forbidden (not whitelisted)
160 | * unauthized (incorrect credentials)
161 | * bad request (malformed host:port)
162 | * not found (any other exception)
163 | *
164 | */
165 | public final Host getHost(
166 | final String host,
167 | final ConnectionCredentials auth
168 | ) throws WebApplicationException {
169 | if (!config.getAllowedEndpoints().isEmpty()
170 | && !config.getAllowedEndpoints().contains(host)
171 | && !config.getAllowedEndpoints().contains(host.split(":")[0])) {
172 | throw new WebApplicationException(Response.Status.FORBIDDEN);
173 | }
174 |
175 | try {
176 | if (!hosts.containsKey(host)) {
177 | LOG.info("creating new worker for " + host);
178 | hosts.put(host, new ConnectionWorker(
179 | host,
180 | config.getCacheDuration().toMilliseconds(),
181 | config.getHistorySize()
182 | ));
183 | }
184 | return hosts.get(host).getHost(auth);
185 | } catch (MalformedURLException e) {
186 | throw new WebApplicationException(Response.Status.BAD_REQUEST);
187 | } catch (SecurityException e) {
188 | throw new WebApplicationException(Response.Status.UNAUTHORIZED);
189 | } catch (Exception e) {
190 | throw new WebApplicationException(Response.Status.NOT_FOUND);
191 | }
192 | }
193 |
194 | /**
195 | * Getter for started.
196 | *
197 | * Used by the application health check to verify the manager start() method has been invoked.
198 | *
199 | * @return true if the manager was started, false otherwise.
200 | */
201 | public final boolean isStarted() {
202 | return started;
203 | }
204 |
205 | /**
206 | * Handler for application startup.
207 | *
208 | * Starts the unaccessed endpoint purge thread at application initialization.
209 | */
210 | public final void start() {
211 | LOG.info("starting jmx connection manager");
212 |
213 | LOG.debug("allowedEndpoints: " + config.getAllowedEndpoints().size());
214 | for (String ae : config.getAllowedEndpoints()) {
215 | LOG.debug(" " + ae);
216 | }
217 |
218 | long cleanInterval = config.getCleanInterval().toMilliseconds();
219 |
220 | purge.scheduleAtFixedRate(new Runnable() {
221 | @Override
222 | public void run() {
223 | LOG.debug("begin expiring stale hosts");
224 | for (Map.Entry hostEntry : hosts.entrySet()) {
225 | if (hostEntry.getValue().isExpired(config.getAccessDuration().toMilliseconds())) {
226 | LOG.debug("purging " + hostEntry.getKey());
227 | hosts.remove(hostEntry.getKey()).shutdown();
228 | }
229 | }
230 | LOG.debug("end expiring stale hosts");
231 | }
232 | }, cleanInterval, cleanInterval, TimeUnit.MILLISECONDS);
233 |
234 | started = true;
235 | }
236 |
237 | /**
238 | * Handler for application shutdown.
239 | *
240 | * Stops the purge thread and all currently tracked {@link ConnectionWorker} instances.
241 | */
242 | public final void stop() {
243 | LOG.info("stopping jmx connection manager");
244 | purge.shutdown();
245 | for (Map.Entry hostEntry : hosts.entrySet()) {
246 | LOG.debug("purging " + hostEntry.getKey());
247 | hosts.remove(hostEntry.getKey()).shutdown();
248 | }
249 | hosts.clear();
250 | started = false;
251 | }
252 | }
253 |
--------------------------------------------------------------------------------
/src/test/java/com/github/mk23/jmxproxy/jmx/tests/ConnectionManagerTest.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.jmx.tests;
2 |
3 | import com.github.mk23.jmxproxy.conf.AppConfig;
4 | import com.github.mk23.jmxproxy.jmx.ConnectionCredentials;
5 | import com.github.mk23.jmxproxy.jmx.ConnectionManager;
6 |
7 | import com.github.mk23.jmxproxy.tests.AuthenticatedTests;
8 |
9 | import io.dropwizard.util.Duration;
10 |
11 | import java.io.BufferedReader;
12 | import java.io.File;
13 | import java.io.FileReader;
14 |
15 | import java.lang.management.ManagementFactory;
16 |
17 | import java.util.Arrays;
18 | import java.util.UUID;
19 |
20 | import javax.management.ObjectName;
21 |
22 | import javax.ws.rs.WebApplicationException;
23 |
24 | import org.junit.Before;
25 | import org.junit.Rule;
26 | import org.junit.Test;
27 |
28 | import org.junit.experimental.categories.Category;
29 |
30 | import org.junit.rules.ExpectedException;
31 | import org.junit.rules.TestName;
32 |
33 | import static org.junit.Assert.assertNotNull;
34 | import static org.junit.Assert.assertNull;
35 | import static org.junit.Assert.assertTrue;
36 |
37 | public class ConnectionManagerTest {
38 | private final String passwdFile = System.getProperty("com.sun.management.jmxremote.password.file");
39 |
40 | private final String validHost = "localhost:" + System.getProperty("com.sun.management.jmxremote.port");
41 | private final String invalidPort = "localhost:0";
42 | private final String invalidHost = "192.0.2.1:0";
43 |
44 | private final String localMBean = "ConnectionManagerTest:type=test";
45 | private final String validMBean = "java.lang:type=OperatingSystem";
46 | private final String invalidMBean = "java.lang:type=InvalidMBean";
47 |
48 | private final String validAttribute = "Name";
49 | private final String invalidAttribute = "InvalidAttribute";
50 |
51 | private final ConnectionCredentials validAuth;
52 | private final ConnectionCredentials invalidAuth = new ConnectionCredentials(UUID.randomUUID().toString(), UUID.randomUUID().toString());
53 |
54 | @Rule public ExpectedException thrown = ExpectedException.none();
55 | @Rule public TestName name = new TestName();
56 |
57 | public interface ConnectionManagerTestJMXMBean {
58 | public void setReadOnlyAttribute(int value);
59 | }
60 |
61 | public class ConnectionManagerTestJMX implements ConnectionManagerTestJMXMBean {
62 | public void setReadOnlyAttribute(int value) {
63 | // ignore
64 | }
65 | }
66 |
67 | public ConnectionManagerTest() throws Exception {
68 | if (passwdFile != null) {
69 | String[] creds = new BufferedReader(new FileReader(new File(passwdFile))).readLine().split("\\s+");
70 | validAuth = new ConnectionCredentials(creds[0], creds[1]);
71 | } else {
72 | validAuth = null;
73 | }
74 |
75 | try {
76 | ManagementFactory.getPlatformMBeanServer().registerMBean(
77 | new ConnectionManagerTestJMX(), new ObjectName(localMBean)
78 | );
79 | } catch (javax.management.InstanceAlreadyExistsException e) {
80 | }
81 | }
82 |
83 | @Before
84 | public void printTestName() {
85 | System.out.println(" -> " + name.getMethodName());
86 | }
87 |
88 | /* Auth tests */
89 | @Test
90 | @Category(AuthenticatedTests.class)
91 | public void checkValidHostValidAuth() throws Exception {
92 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
93 |
94 | assertNotNull(manager.getHost(validHost, validAuth));
95 | }
96 | @Test
97 | @Category(AuthenticatedTests.class)
98 | public void checkValidHostNoAuth() throws Exception {
99 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
100 |
101 | thrown.expect(WebApplicationException.class);
102 | thrown.expectMessage("");
103 | manager.getHost(validHost);
104 | }
105 | @Test
106 | @Category(AuthenticatedTests.class)
107 | public void checkValidHostNullAuth() throws Exception {
108 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
109 |
110 | thrown.expect(WebApplicationException.class);
111 | thrown.expectMessage("HTTP 401 Unauthorized");
112 | manager.getHost(validHost, null);
113 | }
114 | @Test
115 | @Category(AuthenticatedTests.class)
116 | public void checkValidHostInvalidAuth() throws Exception {
117 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
118 |
119 | thrown.expect(WebApplicationException.class);
120 | thrown.expectMessage("HTTP 401 Unauthorized");
121 | manager.getHost(validHost, invalidAuth);
122 | }
123 | @Test
124 | @Category(AuthenticatedTests.class)
125 | public void checkValidHostValidAuthSwitch() throws Exception {
126 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
127 |
128 | assertNotNull(manager.getHost(validHost, validAuth));
129 | thrown.expect(WebApplicationException.class);
130 | thrown.expectMessage("HTTP 401 Unauthorized");
131 | manager.getHost(validHost, invalidAuth);
132 | }
133 | @Test
134 | @Category(AuthenticatedTests.class)
135 | public void checkValidHostAnonymousAuthDisallowed() throws Exception {
136 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
137 |
138 | thrown.expect(WebApplicationException.class);
139 | thrown.expectMessage("HTTP 401 Unauthorized");
140 | manager.getHost(validHost);
141 | }
142 | @Test
143 | public void checkValidHostAnonymousAuthAllowed() throws Exception {
144 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
145 |
146 | assertNotNull(manager.getHost(validHost));
147 | }
148 |
149 | /* Host tests */
150 | @Test
151 | public void checkValidHost() throws Exception {
152 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
153 |
154 | assertNotNull(manager.getHost(validHost, validAuth));
155 | }
156 |
157 | @Test(timeout=2000)
158 | public void checkUnknownHost() throws Exception {
159 | AppConfig serviceConfig = new AppConfig();
160 | serviceConfig.setConnectTimeout(Duration.milliseconds(500));
161 |
162 | final ConnectionManager manager = new ConnectionManager(serviceConfig);
163 |
164 | thrown.expect(WebApplicationException.class);
165 | thrown.expectMessage("HTTP 404 Not Found");
166 |
167 | manager.getHost(invalidHost, validAuth);
168 | }
169 |
170 | @Test
171 | public void checkBrokenHost() throws Exception {
172 | AppConfig serviceConfig = new AppConfig();
173 | serviceConfig.setConnectTimeout(Duration.milliseconds(500));
174 |
175 | final ConnectionManager manager = new ConnectionManager(serviceConfig);
176 |
177 | thrown.expect(WebApplicationException.class);
178 | thrown.expectMessage("HTTP 400 Bad Request");
179 |
180 | manager.getHost("\n", validAuth);
181 | }
182 |
183 | @Test
184 | public void checkPartialHost() throws Exception {
185 | AppConfig serviceConfig = new AppConfig();
186 | serviceConfig.setConnectTimeout(Duration.milliseconds(500));
187 |
188 | final ConnectionManager manager = new ConnectionManager(serviceConfig);
189 |
190 | thrown.expect(WebApplicationException.class);
191 | thrown.expectMessage("HTTP 404 Not Found");
192 |
193 | manager.getHost(validHost.split(":")[0], validAuth);
194 | }
195 |
196 | @Test
197 | public void checkInvalidPort() throws Exception {
198 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
199 |
200 | thrown.expect(WebApplicationException.class);
201 | thrown.expectMessage("HTTP 404 Not Found");
202 |
203 | assertNull(manager.getHost(invalidPort, validAuth));
204 | }
205 |
206 | @Test
207 | public void checkValidFullHostWhitelist() throws Exception {
208 | AppConfig serviceConfig = new AppConfig();
209 | serviceConfig.setAllowedEndpoints(Arrays.asList(new String[] { validHost }));
210 |
211 | final ConnectionManager manager = new ConnectionManager(serviceConfig);
212 |
213 | assertNotNull(manager.getHost(validHost, validAuth));
214 | }
215 |
216 | @Test
217 | public void checkValidBareHostWhitelist() throws Exception {
218 | AppConfig serviceConfig = new AppConfig();
219 | serviceConfig.setAllowedEndpoints(Arrays.asList(new String[] { validHost.split(":")[0] }));
220 |
221 | final ConnectionManager manager = new ConnectionManager(serviceConfig);
222 |
223 | assertNotNull(manager.getHost(validHost, validAuth));
224 | }
225 |
226 | @Test
227 | public void checkInvalidPortValidFullHostWhitelist() throws Exception {
228 | AppConfig serviceConfig = new AppConfig();
229 | serviceConfig.setAllowedEndpoints(Arrays.asList(new String[] { validHost }));
230 |
231 | final ConnectionManager manager = new ConnectionManager(serviceConfig);
232 |
233 | thrown.expect(WebApplicationException.class);
234 | thrown.expectMessage("HTTP 403 Forbidden");
235 |
236 | manager.getHost(invalidPort, validAuth);
237 | }
238 |
239 | @Test
240 | public void checkInvalidPortValidBareHostWhitelist() throws Exception {
241 | AppConfig serviceConfig = new AppConfig();
242 | serviceConfig.setAllowedEndpoints(Arrays.asList(new String[] { validHost.split(":")[0] }));
243 |
244 | final ConnectionManager manager = new ConnectionManager(serviceConfig);
245 |
246 | thrown.expect(WebApplicationException.class);
247 | thrown.expectMessage("HTTP 404 Not Found");
248 |
249 | manager.getHost(invalidPort, validAuth);
250 | }
251 |
252 | /* MBean tests */
253 | @Test
254 | public void checkValidHostMBeans() throws Exception {
255 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
256 |
257 | assertTrue(manager.getHost(validHost, validAuth).getMBeans().contains(validMBean));
258 | }
259 |
260 | @Test
261 | public void checkValidHostValidMBean() throws Exception {
262 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
263 |
264 | assertNotNull(manager.getHost(validHost, validAuth).getMBean(validMBean));
265 | }
266 |
267 | @Test
268 | public void checkValidHostInvalidMBean() throws Exception {
269 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
270 |
271 | assertNull(manager.getHost(validHost, validAuth).getMBean(invalidMBean));
272 | }
273 |
274 | /* Attribute tests */
275 | @Test
276 | public void checkValidHostValidMBeanAttributes() throws Exception {
277 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
278 |
279 | assertTrue(manager.getHost(validHost, validAuth).getMBean(validMBean).getAttributes().contains(validAttribute));
280 | }
281 |
282 | @Test
283 | public void checkValidHostValidMBeanValidAttribute() throws Exception {
284 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
285 |
286 | assertNotNull(manager.getHost(validHost, validAuth).getMBean(validMBean).getAttribute(validAttribute));
287 | }
288 |
289 | @Test
290 | public void checkValidHostValidMBeanInvalidAttribute() throws Exception {
291 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
292 |
293 | assertNull(manager.getHost(validHost, validAuth).getMBean(validMBean).getAttribute(invalidAttribute));
294 | }
295 |
296 | @Test
297 | public void checkValidHostValidMBeanInvalidAttributes() throws Exception {
298 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
299 |
300 | assertTrue(manager.getHost(validHost, validAuth).getMBean(validMBean).getAttributes(invalidAttribute, 1).isEmpty());
301 | }
302 |
303 | @Test
304 | public void checkValidHostValidMBeanReadOnlyAttribute() throws Exception {
305 | final ConnectionManager manager = new ConnectionManager(new AppConfig());
306 |
307 | assertTrue(manager.getHost(validHost, validAuth).getMBean(validMBean).getAttribute("ReadOnlyAttribute") == null);
308 | }
309 |
310 | /* Custom MBean tests */
311 | @Test
312 | public void checkValidHostRemovedMBean() throws Exception {
313 | final ConnectionManager manager = new ConnectionManager(new AppConfig().setCacheDuration(Duration.seconds(3)));
314 |
315 | assertNotNull(manager.getHost(validHost, validAuth).getMBean(localMBean));
316 |
317 | ManagementFactory.getPlatformMBeanServer().unregisterMBean(
318 | new ObjectName(localMBean)
319 | );
320 |
321 | java.lang.Thread.sleep(Duration.seconds(5).toMilliseconds());
322 |
323 | assertNull(manager.getHost(validHost, validAuth).getMBean(localMBean));
324 | }
325 | }
326 |
--------------------------------------------------------------------------------
/src/main/resources/assets/js/jquery.flot.time.js:
--------------------------------------------------------------------------------
1 | /* Pretty handling of time axes.
2 |
3 | Copyright (c) 2007-2014 IOLA and Ole Laursen.
4 | Licensed under the MIT license.
5 |
6 | Set axis.mode to "time" to enable. See the section "Time series data" in
7 | API.txt for details.
8 |
9 | */
10 |
11 | (function($) {
12 |
13 | var options = {
14 | xaxis: {
15 | timezone: null, // "browser" for local to the client or timezone for timezone-js
16 | timeformat: null, // format string to use
17 | twelveHourClock: false, // 12 or 24 time in time mode
18 | monthNames: null // list of names of months
19 | }
20 | };
21 |
22 | // round to nearby lower multiple of base
23 |
24 | function floorInBase(n, base) {
25 | return base * Math.floor(n / base);
26 | }
27 |
28 | // Returns a string with the date d formatted according to fmt.
29 | // A subset of the Open Group's strftime format is supported.
30 |
31 | function formatDate(d, fmt, monthNames, dayNames) {
32 |
33 | if (typeof d.strftime == "function") {
34 | return d.strftime(fmt);
35 | }
36 |
37 | var leftPad = function(n, pad) {
38 | n = "" + n;
39 | pad = "" + (pad == null ? "0" : pad);
40 | return n.length == 1 ? pad + n : n;
41 | };
42 |
43 | var r = [];
44 | var escape = false;
45 | var hours = d.getHours();
46 | var isAM = hours < 12;
47 |
48 | if (monthNames == null) {
49 | monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
50 | }
51 |
52 | if (dayNames == null) {
53 | dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
54 | }
55 |
56 | var hours12;
57 |
58 | if (hours > 12) {
59 | hours12 = hours - 12;
60 | } else if (hours == 0) {
61 | hours12 = 12;
62 | } else {
63 | hours12 = hours;
64 | }
65 |
66 | for (var i = 0; i < fmt.length; ++i) {
67 |
68 | var c = fmt.charAt(i);
69 |
70 | if (escape) {
71 | switch (c) {
72 | case 'a': c = "" + dayNames[d.getDay()]; break;
73 | case 'b': c = "" + monthNames[d.getMonth()]; break;
74 | case 'd': c = leftPad(d.getDate()); break;
75 | case 'e': c = leftPad(d.getDate(), " "); break;
76 | case 'h': // For back-compat with 0.7; remove in 1.0
77 | case 'H': c = leftPad(hours); break;
78 | case 'I': c = leftPad(hours12); break;
79 | case 'l': c = leftPad(hours12, " "); break;
80 | case 'm': c = leftPad(d.getMonth() + 1); break;
81 | case 'M': c = leftPad(d.getMinutes()); break;
82 | // quarters not in Open Group's strftime specification
83 | case 'q':
84 | c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
85 | case 'S': c = leftPad(d.getSeconds()); break;
86 | case 'y': c = leftPad(d.getFullYear() % 100); break;
87 | case 'Y': c = "" + d.getFullYear(); break;
88 | case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
89 | case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
90 | case 'w': c = "" + d.getDay(); break;
91 | }
92 | r.push(c);
93 | escape = false;
94 | } else {
95 | if (c == "%") {
96 | escape = true;
97 | } else {
98 | r.push(c);
99 | }
100 | }
101 | }
102 |
103 | return r.join("");
104 | }
105 |
106 | // To have a consistent view of time-based data independent of which time
107 | // zone the client happens to be in we need a date-like object independent
108 | // of time zones. This is done through a wrapper that only calls the UTC
109 | // versions of the accessor methods.
110 |
111 | function makeUtcWrapper(d) {
112 |
113 | function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
114 | sourceObj[sourceMethod] = function() {
115 | return targetObj[targetMethod].apply(targetObj, arguments);
116 | };
117 | };
118 |
119 | var utc = {
120 | date: d
121 | };
122 |
123 | // support strftime, if found
124 |
125 | if (d.strftime != undefined) {
126 | addProxyMethod(utc, "strftime", d, "strftime");
127 | }
128 |
129 | addProxyMethod(utc, "getTime", d, "getTime");
130 | addProxyMethod(utc, "setTime", d, "setTime");
131 |
132 | var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
133 |
134 | for (var p = 0; p < props.length; p++) {
135 | addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
136 | addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
137 | }
138 |
139 | return utc;
140 | };
141 |
142 | // select time zone strategy. This returns a date-like object tied to the
143 | // desired timezone
144 |
145 | function dateGenerator(ts, opts) {
146 | if (opts.timezone == "browser") {
147 | return new Date(ts);
148 | } else if (!opts.timezone || opts.timezone == "utc") {
149 | return makeUtcWrapper(new Date(ts));
150 | } else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
151 | var d = new timezoneJS.Date();
152 | // timezone-js is fickle, so be sure to set the time zone before
153 | // setting the time.
154 | d.setTimezone(opts.timezone);
155 | d.setTime(ts);
156 | return d;
157 | } else {
158 | return makeUtcWrapper(new Date(ts));
159 | }
160 | }
161 |
162 | // map of app. size of time units in milliseconds
163 |
164 | var timeUnitSize = {
165 | "second": 1000,
166 | "minute": 60 * 1000,
167 | "hour": 60 * 60 * 1000,
168 | "day": 24 * 60 * 60 * 1000,
169 | "month": 30 * 24 * 60 * 60 * 1000,
170 | "quarter": 3 * 30 * 24 * 60 * 60 * 1000,
171 | "year": 365.2425 * 24 * 60 * 60 * 1000
172 | };
173 |
174 | // the allowed tick sizes, after 1 year we use
175 | // an integer algorithm
176 |
177 | var baseSpec = [
178 | [1, "second"], [2, "second"], [5, "second"], [10, "second"],
179 | [30, "second"],
180 | [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
181 | [30, "minute"],
182 | [1, "hour"], [2, "hour"], [4, "hour"],
183 | [8, "hour"], [12, "hour"],
184 | [1, "day"], [2, "day"], [3, "day"],
185 | [0.25, "month"], [0.5, "month"], [1, "month"],
186 | [2, "month"]
187 | ];
188 |
189 | // we don't know which variant(s) we'll need yet, but generating both is
190 | // cheap
191 |
192 | var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
193 | [1, "year"]]);
194 | var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
195 | [1, "year"]]);
196 |
197 | function init(plot) {
198 | plot.hooks.processOptions.push(function (plot, options) {
199 | $.each(plot.getAxes(), function(axisName, axis) {
200 |
201 | var opts = axis.options;
202 |
203 | if (opts.mode == "time") {
204 | axis.tickGenerator = function(axis) {
205 |
206 | var ticks = [];
207 | var d = dateGenerator(axis.min, opts);
208 | var minSize = 0;
209 |
210 | // make quarter use a possibility if quarters are
211 | // mentioned in either of these options
212 |
213 | var spec = (opts.tickSize && opts.tickSize[1] ===
214 | "quarter") ||
215 | (opts.minTickSize && opts.minTickSize[1] ===
216 | "quarter") ? specQuarters : specMonths;
217 |
218 | if (opts.minTickSize != null) {
219 | if (typeof opts.tickSize == "number") {
220 | minSize = opts.tickSize;
221 | } else {
222 | minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
223 | }
224 | }
225 |
226 | for (var i = 0; i < spec.length - 1; ++i) {
227 | if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]]
228 | + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
229 | && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
230 | break;
231 | }
232 | }
233 |
234 | var size = spec[i][0];
235 | var unit = spec[i][1];
236 |
237 | // special-case the possibility of several years
238 |
239 | if (unit == "year") {
240 |
241 | // if given a minTickSize in years, just use it,
242 | // ensuring that it's an integer
243 |
244 | if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
245 | size = Math.floor(opts.minTickSize[0]);
246 | } else {
247 |
248 | var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
249 | var norm = (axis.delta / timeUnitSize.year) / magn;
250 |
251 | if (norm < 1.5) {
252 | size = 1;
253 | } else if (norm < 3) {
254 | size = 2;
255 | } else if (norm < 7.5) {
256 | size = 5;
257 | } else {
258 | size = 10;
259 | }
260 |
261 | size *= magn;
262 | }
263 |
264 | // minimum size for years is 1
265 |
266 | if (size < 1) {
267 | size = 1;
268 | }
269 | }
270 |
271 | axis.tickSize = opts.tickSize || [size, unit];
272 | var tickSize = axis.tickSize[0];
273 | unit = axis.tickSize[1];
274 |
275 | var step = tickSize * timeUnitSize[unit];
276 |
277 | if (unit == "second") {
278 | d.setSeconds(floorInBase(d.getSeconds(), tickSize));
279 | } else if (unit == "minute") {
280 | d.setMinutes(floorInBase(d.getMinutes(), tickSize));
281 | } else if (unit == "hour") {
282 | d.setHours(floorInBase(d.getHours(), tickSize));
283 | } else if (unit == "month") {
284 | d.setMonth(floorInBase(d.getMonth(), tickSize));
285 | } else if (unit == "quarter") {
286 | d.setMonth(3 * floorInBase(d.getMonth() / 3,
287 | tickSize));
288 | } else if (unit == "year") {
289 | d.setFullYear(floorInBase(d.getFullYear(), tickSize));
290 | }
291 |
292 | // reset smaller components
293 |
294 | d.setMilliseconds(0);
295 |
296 | if (step >= timeUnitSize.minute) {
297 | d.setSeconds(0);
298 | }
299 | if (step >= timeUnitSize.hour) {
300 | d.setMinutes(0);
301 | }
302 | if (step >= timeUnitSize.day) {
303 | d.setHours(0);
304 | }
305 | if (step >= timeUnitSize.day * 4) {
306 | d.setDate(1);
307 | }
308 | if (step >= timeUnitSize.month * 2) {
309 | d.setMonth(floorInBase(d.getMonth(), 3));
310 | }
311 | if (step >= timeUnitSize.quarter * 2) {
312 | d.setMonth(floorInBase(d.getMonth(), 6));
313 | }
314 | if (step >= timeUnitSize.year) {
315 | d.setMonth(0);
316 | }
317 |
318 | var carry = 0;
319 | var v = Number.NaN;
320 | var prev;
321 |
322 | do {
323 |
324 | prev = v;
325 | v = d.getTime();
326 | ticks.push(v);
327 |
328 | if (unit == "month" || unit == "quarter") {
329 | if (tickSize < 1) {
330 |
331 | // a bit complicated - we'll divide the
332 | // month/quarter up but we need to take
333 | // care of fractions so we don't end up in
334 | // the middle of a day
335 |
336 | d.setDate(1);
337 | var start = d.getTime();
338 | d.setMonth(d.getMonth() +
339 | (unit == "quarter" ? 3 : 1));
340 | var end = d.getTime();
341 | d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
342 | carry = d.getHours();
343 | d.setHours(0);
344 | } else {
345 | d.setMonth(d.getMonth() +
346 | tickSize * (unit == "quarter" ? 3 : 1));
347 | }
348 | } else if (unit == "year") {
349 | d.setFullYear(d.getFullYear() + tickSize);
350 | } else {
351 | d.setTime(v + step);
352 | }
353 | } while (v < axis.max && v != prev);
354 |
355 | return ticks;
356 | };
357 |
358 | axis.tickFormatter = function (v, axis) {
359 |
360 | var d = dateGenerator(v, axis.options);
361 |
362 | // first check global format
363 |
364 | if (opts.timeformat != null) {
365 | return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
366 | }
367 |
368 | // possibly use quarters if quarters are mentioned in
369 | // any of these places
370 |
371 | var useQuarters = (axis.options.tickSize &&
372 | axis.options.tickSize[1] == "quarter") ||
373 | (axis.options.minTickSize &&
374 | axis.options.minTickSize[1] == "quarter");
375 |
376 | var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
377 | var span = axis.max - axis.min;
378 | var suffix = (opts.twelveHourClock) ? " %p" : "";
379 | var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
380 | var fmt;
381 |
382 | if (t < timeUnitSize.minute) {
383 | fmt = hourCode + ":%M:%S" + suffix;
384 | } else if (t < timeUnitSize.day) {
385 | if (span < 2 * timeUnitSize.day) {
386 | fmt = hourCode + ":%M" + suffix;
387 | } else {
388 | fmt = "%b %d " + hourCode + ":%M" + suffix;
389 | }
390 | } else if (t < timeUnitSize.month) {
391 | fmt = "%b %d";
392 | } else if ((useQuarters && t < timeUnitSize.quarter) ||
393 | (!useQuarters && t < timeUnitSize.year)) {
394 | if (span < timeUnitSize.year) {
395 | fmt = "%b";
396 | } else {
397 | fmt = "%b %Y";
398 | }
399 | } else if (useQuarters && t < timeUnitSize.year) {
400 | if (span < timeUnitSize.year) {
401 | fmt = "Q%q";
402 | } else {
403 | fmt = "Q%q %Y";
404 | }
405 | } else {
406 | fmt = "%Y";
407 | }
408 |
409 | var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
410 |
411 | return rt;
412 | };
413 | }
414 | });
415 | });
416 | }
417 |
418 | $.plot.plugins.push({
419 | init: init,
420 | options: options,
421 | name: 'time',
422 | version: '1.0'
423 | });
424 |
425 | // Time-axis support used to be in Flot core, which exposed the
426 | // formatDate function on the plot object. Various plugins depend
427 | // on the function, so we need to re-expose it here.
428 |
429 | $.plot.formatDate = formatDate;
430 | $.plot.dateGenerator = dateGenerator;
431 |
432 | })(jQuery);
433 |
--------------------------------------------------------------------------------
/src/test/java/com/github/mk23/jmxproxy/util/tests/HistoryTest.java:
--------------------------------------------------------------------------------
1 | package com.github.mk23.jmxproxy.util.tests;
2 |
3 | import com.github.mk23.jmxproxy.util.History;
4 |
5 | import java.util.ArrayList;
6 |
7 | import org.junit.Before;
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.rules.TestName;
11 |
12 | import static org.junit.Assert.assertArrayEquals;
13 | import static org.junit.Assert.assertEquals;
14 | import static org.junit.Assert.assertNull;
15 | import static org.junit.Assert.assertTrue;
16 |
17 | public class HistoryTest {
18 | @Rule public TestName name = new TestName();
19 |
20 | @Before
21 | public void printTestName() {
22 | System.out.println(" -> " + name.getMethodName());
23 | }
24 |
25 | @Test
26 | public void check0Single() throws Exception {
27 | History history = new History(3);
28 | assertNull(history.getLast());
29 | }
30 | @Test
31 | public void check0ArrayFull() throws Exception {
32 | History history = new History(3);
33 | assertTrue(history.get().size() == 0);
34 | }
35 | @Test
36 | public void check0ArrayZero() throws Exception {
37 | History history = new History(3);
38 | assertTrue(history.get(0).size() == 0);
39 | }
40 | @Test
41 | public void check0ArrayTen() throws Exception {
42 | History history = new History(3);
43 | assertTrue(history.get(10).size() == 0);
44 | }
45 | @Test
46 | public void check0ArrayTwo() throws Exception {
47 | History history = new History(3);
48 | assertTrue(history.get(2).size() == 0);
49 | }
50 | @Test
51 | public void check0ArrayOne() throws Exception {
52 | History history = new History(3);
53 | assertTrue(history.get(1).size() == 0);
54 | }
55 |
56 | @Test
57 | public void check1Single() throws Exception {
58 | History history = new History(3);
59 | String target = new String("1");
60 |
61 | history.add(new String("1"));
62 | assertEquals(target, history.getLast());
63 | }
64 | @Test
65 | public void check1ArrayFull() throws Exception {
66 | History history = new History(3);
67 | String[] target = new String[] { new String("1") };
68 |
69 | history.add(new String("1"));
70 | assertArrayEquals(target, history.get().toArray());
71 | }
72 | @Test
73 | public void check1ArrayZero() throws Exception {
74 | History history = new History(3);
75 | String[] target = new String[] { new String("1") };
76 |
77 | history.add(new String("1"));
78 | assertArrayEquals(target, history.get(0).toArray());
79 | }
80 | @Test
81 | public void check1ArrayTen() throws Exception {
82 | History history = new History(3);
83 | String[] target = new String[] { new String("1") };
84 |
85 | history.add(new String("1"));
86 | assertArrayEquals(target, history.get(10).toArray());
87 | }
88 | @Test
89 | public void check1ArrayTwo() throws Exception {
90 | History history = new History(3);
91 | String[] target = new String[] { new String("1") };
92 |
93 | history.add(new String("1"));
94 | assertArrayEquals(target, history.get(2).toArray());
95 | }
96 | @Test
97 | public void check1ArrayOne() throws Exception {
98 | History history = new History(3);
99 | String[] target = new String[] { new String("1") };
100 |
101 | history.add(new String("1"));
102 | assertArrayEquals(target, history.get(1).toArray());
103 | }
104 |
105 | @Test
106 | public void check2Single() throws Exception {
107 | History history = new History(3);
108 | String target = new String("2");
109 |
110 | history.add(new String("1"));
111 | history.add(new String("2"));
112 | assertEquals(target, history.getLast());
113 | }
114 | @Test
115 | public void check2ArrayFull() throws Exception {
116 | History history = new History(3);
117 | String[] target = new String[] { new String("2"), new String("1") };
118 |
119 | history.add(new String("1"));
120 | history.add(new String("2"));
121 | assertArrayEquals(target, history.get().toArray());
122 | }
123 | @Test
124 | public void check2ArrayZero() throws Exception {
125 | History history = new History(3);
126 | String[] target = new String[] { new String("2"), new String("1") };
127 |
128 | history.add(new String("1"));
129 | history.add(new String("2"));
130 | assertArrayEquals(target, history.get(0).toArray());
131 | }
132 | @Test
133 | public void check2ArrayTen() throws Exception {
134 | History history = new History(3);
135 | String[] target = new String[] { new String("2"), new String("1") };
136 |
137 | history.add(new String("1"));
138 | history.add(new String("2"));
139 | assertArrayEquals(target, history.get(10).toArray());
140 | }
141 | @Test
142 | public void check2ArrayTwo() throws Exception {
143 | History history = new History(3);
144 | String[] target = new String[] { new String("2"), new String("1") };
145 |
146 | history.add(new String("1"));
147 | history.add(new String("2"));
148 | assertArrayEquals(target, history.get(2).toArray());
149 | }
150 | @Test
151 | public void check2ArrayOne() throws Exception {
152 | History history = new History(3);
153 | String[] target = new String[] { new String("2") };
154 |
155 | history.add(new String("1"));
156 | history.add(new String("2"));
157 | assertArrayEquals(target, history.get(1).toArray());
158 | }
159 |
160 | @Test
161 | public void check3Single() throws Exception {
162 | History history = new History(3);
163 | String target = new String("3");
164 |
165 | history.add(new String("1"));
166 | history.add(new String("2"));
167 | history.add(new String("3"));
168 | assertEquals(target, history.getLast());
169 | }
170 | @Test
171 | public void check3ArrayFull() throws Exception {
172 | History history = new History(3);
173 | String[] target = new String[] { new String("3"), new String("2"), new String("1") };
174 |
175 | history.add(new String("1"));
176 | history.add(new String("2"));
177 | history.add(new String("3"));
178 | assertArrayEquals(target, history.get().toArray());
179 | }
180 | @Test
181 | public void check3ArrayZero() throws Exception {
182 | History history = new History(3);
183 | String[] target = new String[] { new String("3"), new String("2"), new String("1") };
184 |
185 | history.add(new String("1"));
186 | history.add(new String("2"));
187 | history.add(new String("3"));
188 | assertArrayEquals(target, history.get(0).toArray());
189 | }
190 | @Test
191 | public void check3ArrayTen() throws Exception {
192 | History history = new History(3);
193 | String[] target = new String[] { new String("3"), new String("2"), new String("1") };
194 |
195 | history.add(new String("1"));
196 | history.add(new String("2"));
197 | history.add(new String("3"));
198 | assertArrayEquals(target, history.get(10).toArray());
199 | }
200 | @Test
201 | public void check3ArrayTwo() throws Exception {
202 | History history = new History(3);
203 | String[] target = new String[] { new String("3"), new String("2") };
204 |
205 | history.add(new String("1"));
206 | history.add(new String("2"));
207 | history.add(new String("3"));
208 | assertArrayEquals(target, history.get(2).toArray());
209 | }
210 | @Test
211 | public void check3ArrayOne() throws Exception {
212 | History history = new History(3);
213 | String[] target = new String[] { new String("3") };
214 |
215 | history.add(new String("1"));
216 | history.add(new String("2"));
217 | history.add(new String("3"));
218 | assertArrayEquals(target, history.get(1).toArray());
219 | }
220 |
221 | @Test
222 | public void check4Single() throws Exception {
223 | History history = new History(3);
224 | String target = new String("4");
225 |
226 | history.add(new String("1"));
227 | history.add(new String("2"));
228 | history.add(new String("3"));
229 | history.add(new String("4"));
230 | assertEquals(target, history.getLast());
231 | }
232 | @Test
233 | public void check4ArrayFull() throws Exception {
234 | History history = new History(3);
235 | String[] target = new String[] { new String("4"), new String("3"), new String("2") };
236 |
237 | history.add(new String("1"));
238 | history.add(new String("2"));
239 | history.add(new String("3"));
240 | history.add(new String("4"));
241 | assertArrayEquals(target, history.get().toArray());
242 | }
243 | @Test
244 | public void check4ArrayZero() throws Exception {
245 | History history = new History(3);
246 | String[] target = new String[] { new String("4"), new String("3"), new String("2") };
247 |
248 | history.add(new String("1"));
249 | history.add(new String("2"));
250 | history.add(new String("3"));
251 | history.add(new String("4"));
252 | assertArrayEquals(target, history.get(0).toArray());
253 | }
254 | @Test
255 | public void check4ArrayTen() throws Exception {
256 | History history = new History(3);
257 | String[] target = new String[] { new String("4"), new String("3"), new String("2") };
258 |
259 | history.add(new String("1"));
260 | history.add(new String("2"));
261 | history.add(new String("3"));
262 | history.add(new String("4"));
263 | assertArrayEquals(target, history.get(10).toArray());
264 | }
265 | @Test
266 | public void check4ArrayTwo() throws Exception {
267 | History history = new History(3);
268 | String[] target = new String[] { new String("4"), new String("3") };
269 |
270 | history.add(new String("1"));
271 | history.add(new String("2"));
272 | history.add(new String("3"));
273 | history.add(new String("4"));
274 | assertArrayEquals(target, history.get(2).toArray());
275 | }
276 | @Test
277 | public void check4ArrayOne() throws Exception {
278 | History history = new History(3);
279 | String[] target = new String[] { new String("4") };
280 |
281 | history.add(new String("1"));
282 | history.add(new String("2"));
283 | history.add(new String("3"));
284 | history.add(new String("4"));
285 | assertArrayEquals(target, history.get(1).toArray());
286 | }
287 |
288 | @Test
289 | public void check100Single() throws Exception {
290 | History history = new History(3);
291 | String target = new String("99");
292 |
293 | for (int i = 0; i < 100; i++) {
294 | history.add(new String(Integer.toString(i)));
295 | }
296 | assertEquals(target, history.getLast());
297 | }
298 | @Test
299 | public void check100ArrayFull() throws Exception {
300 | History history = new History(3);
301 | String[] target = new String[] { new String("99"), new String("98"), new String("97"), };
302 |
303 | for (int i = 0; i < 100; i++) {
304 | history.add(new String(Integer.toString(i)));
305 | }
306 | assertArrayEquals(target, history.get().toArray());
307 | }
308 | @Test
309 | public void check100ArrayZero() throws Exception {
310 | History history = new History(3);
311 | String[] target = new String[] { new String("99"), new String("98"), new String("97"), };
312 |
313 | for (int i = 0; i < 100; i++) {
314 | history.add(new String(Integer.toString(i)));
315 | }
316 | assertArrayEquals(target, history.get(0).toArray());
317 | }
318 | @Test
319 | public void check100ArrayTen() throws Exception {
320 | History history = new History(3);
321 | String[] target = new String[] { new String("99"), new String("98"), new String("97"), };
322 |
323 | for (int i = 0; i < 100; i++) {
324 | history.add(new String(Integer.toString(i)));
325 | }
326 | assertArrayEquals(target, history.get(10).toArray());
327 | }
328 | @Test
329 | public void check100ArrayTwo() throws Exception {
330 | History history = new History(3);
331 | String[] target = new String[] { new String("99"), new String("98") };
332 |
333 | for (int i = 0; i < 100; i++) {
334 | history.add(new String(Integer.toString(i)));
335 | }
336 | assertArrayEquals(target, history.get(2).toArray());
337 | }
338 | @Test
339 | public void check100ArrayOne() throws Exception {
340 | History history = new History(3);
341 | String[] target = new String[] { new String("99") };
342 |
343 | for (int i = 0; i < 100; i++) {
344 | history.add(new String(Integer.toString(i)));
345 | }
346 |
347 | assertArrayEquals(target, history.get(1).toArray());
348 | }
349 | }
350 |
--------------------------------------------------------------------------------