├── .gitignore ├── .travis.yml ├── Rakefile ├── NOTICE.TXT ├── .github ├── PULL_REQUEST_TEMPLATE.md ├── ISSUE_TEMPLATE.md └── CONTRIBUTING.md ├── Gemfile ├── CONTRIBUTORS ├── CHANGELOG.md ├── logstash-input-jmx.gemspec ├── README.md ├── docs └── index.asciidoc ├── spec └── inputs │ └── jmx_spec.rb ├── LICENSE └── lib └── logstash └── inputs └── jmx.rb /.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | Gemfile.lock 3 | .bundle 4 | vendor 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | import: 2 | - logstash-plugins/.ci:travis/travis.yml@1.x -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | @files=[] 2 | 3 | task :default do 4 | system("rake -T") 5 | end 6 | 7 | require "logstash/devutils/rake" 8 | -------------------------------------------------------------------------------- /NOTICE.TXT: -------------------------------------------------------------------------------- 1 | Elasticsearch 2 | Copyright 2012-2015 Elasticsearch 3 | 4 | This product includes software developed by The Apache Software 5 | Foundation (http://www.apache.org/). -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thanks for contributing to Logstash! If you haven't already signed our CLA, here's a handy link: https://www.elastic.co/contributor-agreement/ 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gemspec 4 | 5 | logstash_path = ENV["LOGSTASH_PATH"] || "../../logstash" 6 | use_logstash_source = ENV["LOGSTASH_SOURCE"] && ENV["LOGSTASH_SOURCE"].to_s == "1" 7 | 8 | if Dir.exist?(logstash_path) && use_logstash_source 9 | gem 'logstash-core', :path => "#{logstash_path}/logstash-core" 10 | gem 'logstash-core-plugin-api', :path => "#{logstash_path}/logstash-core-plugin-api" 11 | end 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Please post all product and debugging questions on our [forum](https://discuss.elastic.co/c/logstash). Your questions will reach our wider community members there, and if we confirm that there is a bug, then we can open a new issue here. 2 | 3 | For all general issues, please provide the following details for fast resolution: 4 | 5 | - Version: 6 | - Operating System: 7 | - Config File (if you have sensitive info, please remove it): 8 | - Sample Data: 9 | - Steps to Reproduce: 10 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | The following is a list of people who have contributed ideas, code, bug 2 | reports, or in general have helped logstash along its way. 3 | 4 | Contributors: 5 | * Nicolas Fraison (ashangit) 6 | * Pier-Hugues Pellerin (ph) 7 | * Richard Pijnenburg (electrical) 8 | * Pere Urbon-Bayes (purbon) 9 | * Colin Surprenant (colinsurprenant) 10 | 11 | Note: If you've sent us patches, bug reports, or otherwise contributed to 12 | Logstash, and you aren't on the list above and want to be, please let us know 13 | and we'll make sure you're here. Contributions from folks like you are what make 14 | open source awesome. 15 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 3.0.7 2 | - Fixed shutdown handling [#47](https://github.com/logstash-plugins/logstash-input-jmx/pull/47) 3 | 4 | ## 3.0.6 5 | - Fix documentation issue (correct subheading format) 6 | 7 | ## 3.0.5 8 | - Docs: Set the default_codec doc attribute. 9 | 10 | ## 3.0.4 11 | - Update gemspec summary 12 | 13 | ## 3.0.3 14 | - Fix some documentation issues 15 | 16 | # 3.0.1 17 | - fix left-over usage of old event api, migrated to using `event#set` 18 | 19 | # 3.0.0 20 | - Breaking: depend on logstash-core-plugin-api between 1.60 and 2.99 21 | 22 | # 2.0.4 23 | - Depend on logstash-core-plugin-api instead of logstash-core, removing the need to mass update plugins on major releases of logstash 24 | 25 | # 2.0.3 26 | - New dependency requirements for logstash-core for the 5.0 release 27 | 28 | ## 2.0.0 29 | - Plugins were updated to follow the new shutdown semantic, this mainly allows Logstash to instruct input plugins to terminate gracefully, 30 | instead of using Thread.raise on the plugins' threads. Ref: https://github.com/elastic/logstash/pull/3895 31 | - Dependency on logstash-core update to 2.0 32 | 33 | -------------------------------------------------------------------------------- /logstash-input-jmx.gemspec: -------------------------------------------------------------------------------- 1 | Gem::Specification.new do |s| 2 | 3 | s.name = 'logstash-input-jmx' 4 | s.version = '3.0.7' 5 | s.licenses = ['Apache License (2.0)'] 6 | s.summary = "Retrieves metrics from remote Java applications over JMX" 7 | s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program" 8 | s.authors = ["Elastic"] 9 | s.email = 'info@elastic.co' 10 | s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html" 11 | s.require_paths = ["lib"] 12 | 13 | # Files 14 | s.files = Dir["lib/**/*","spec/**/*","*.gemspec","*.md","CONTRIBUTORS","Gemfile","LICENSE","NOTICE.TXT", "vendor/jar-dependencies/**/*.jar", "vendor/jar-dependencies/**/*.rb", "VERSION", "docs/**/*"] 15 | 16 | # Tests 17 | s.test_files = s.files.grep(%r{^(test|spec|features)/}) 18 | 19 | # Special flag to let us know this is actually a logstash plugin 20 | s.metadata = { "logstash_plugin" => "true", "logstash_group" => "input" } 21 | 22 | # Gem dependencies 23 | s.add_runtime_dependency "logstash-core-plugin-api", ">= 1.60", "<= 2.99" 24 | 25 | s.add_runtime_dependency 'jmx4r' 26 | 27 | s.add_development_dependency 'logstash-devutils' 28 | s.add_development_dependency 'logstash-codec-plain' 29 | end 30 | 31 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Logstash 2 | 3 | All contributions are welcome: ideas, patches, documentation, bug reports, 4 | complaints, etc! 5 | 6 | Programming is not a required skill, and there are many ways to help out! 7 | It is more important to us that you are able to contribute. 8 | 9 | That said, some basic guidelines, which you are free to ignore :) 10 | 11 | ## Want to learn? 12 | 13 | Want to lurk about and see what others are doing with Logstash? 14 | 15 | * The irc channel (#logstash on irc.freenode.org) is a good place for this 16 | * The [forum](https://discuss.elastic.co/c/logstash) is also 17 | great for learning from others. 18 | 19 | ## Got Questions? 20 | 21 | Have a problem you want Logstash to solve for you? 22 | 23 | * You can ask a question in the [forum](https://discuss.elastic.co/c/logstash) 24 | * Alternately, you are welcome to join the IRC channel #logstash on 25 | irc.freenode.org and ask for help there! 26 | 27 | ## Have an Idea or Feature Request? 28 | 29 | * File a ticket on [GitHub](https://github.com/elastic/logstash/issues). Please remember that GitHub is used only for issues and feature requests. If you have a general question, the [forum](https://discuss.elastic.co/c/logstash) or IRC would be the best place to ask. 30 | 31 | ## Something Not Working? Found a Bug? 32 | 33 | If you think you found a bug, it probably is a bug. 34 | 35 | * If it is a general Logstash or a pipeline issue, file it in [Logstash GitHub](https://github.com/elasticsearch/logstash/issues) 36 | * If it is specific to a plugin, please file it in the respective repository under [logstash-plugins](https://github.com/logstash-plugins) 37 | * or ask the [forum](https://discuss.elastic.co/c/logstash). 38 | 39 | # Contributing Documentation and Code Changes 40 | 41 | If you have a bugfix or new feature that you would like to contribute to 42 | logstash, and you think it will take more than a few minutes to produce the fix 43 | (ie; write code), it is worth discussing the change with the Logstash users and developers first! You can reach us via [GitHub](https://github.com/elastic/logstash/issues), the [forum](https://discuss.elastic.co/c/logstash), or via IRC (#logstash on freenode irc) 44 | Please note that Pull Requests without tests will not be merged. If you would like to contribute but do not have experience with writing tests, please ping us on IRC/forum or create a PR and ask our help. 45 | 46 | ## Contributing to plugins 47 | 48 | Check our [documentation](https://www.elastic.co/guide/en/logstash/current/contributing-to-logstash.html) on how to contribute to plugins or write your own! It is super easy! 49 | 50 | ## Contribution Steps 51 | 52 | 1. Test your changes! [Run](https://github.com/elastic/logstash#testing) the test suite 53 | 2. Please make sure you have signed our [Contributor License 54 | Agreement](https://www.elastic.co/contributor-agreement/). We are not 55 | asking you to assign copyright to us, but to give us the right to distribute 56 | your code without restriction. We ask this of all contributors in order to 57 | assure our users of the origin and continuing existence of the code. You 58 | only need to sign the CLA once. 59 | 3. Send a pull request! Push your changes to your fork of the repository and 60 | [submit a pull 61 | request](https://help.github.com/articles/using-pull-requests). In the pull 62 | request, describe what your changes do and mention any bugs/issues related 63 | to the pull request. 64 | 65 | 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Logstash Plugin 2 | 3 | [![Travis Build Status](https://travis-ci.com/logstash-plugins/logstash-input-jmx.svg)](https://travis-ci.com/logstash-plugins/logstash-input-jmx) 4 | 5 | This is a plugin for [Logstash](https://github.com/elastic/logstash). 6 | 7 | It is fully free and fully open source. The license is Apache 2.0, meaning you are pretty much free to use it however you want in whatever way. 8 | 9 | ## Documentation 10 | 11 | Logstash provides infrastructure to automatically generate documentation for this plugin. We use the asciidoc format to write documentation so any comments in the source code will be first converted into asciidoc and then into html. All plugin documentation are placed under one [central location](http://www.elastic.co/guide/en/logstash/current/). 12 | 13 | - For formatting code or config example, you can use the asciidoc `[source,ruby]` directive 14 | - For more asciidoc formatting tips, see the excellent reference here https://github.com/elastic/docs#asciidoc-guide 15 | 16 | ## Need Help? 17 | 18 | Need help? Try #logstash on freenode IRC or the https://discuss.elastic.co/c/logstash discussion forum. 19 | 20 | ## Developing 21 | 22 | ### 1. Plugin Developement and Testing 23 | 24 | #### Code 25 | - To get started, you'll need JRuby with the Bundler gem installed. 26 | 27 | - Create a new plugin or clone and existing from the GitHub [logstash-plugins](https://github.com/logstash-plugins) organization. We also provide [example plugins](https://github.com/logstash-plugins?query=example). 28 | 29 | - Install dependencies 30 | ```sh 31 | bundle install 32 | ``` 33 | 34 | #### Test 35 | 36 | - Update your dependencies 37 | 38 | ```sh 39 | bundle install 40 | ``` 41 | 42 | - Run tests 43 | 44 | ```sh 45 | bundle exec rspec 46 | ``` 47 | 48 | ### 2. Running your unpublished Plugin in Logstash 49 | 50 | #### 2.1 Run in a local Logstash clone 51 | 52 | - Edit Logstash `Gemfile` and add the local plugin path, for example: 53 | ```ruby 54 | gem "logstash-filter-awesome", :path => "/your/local/logstash-filter-awesome" 55 | ``` 56 | - Install plugin 57 | ```sh 58 | # Logstash 2.3 and higher 59 | bin/logstash-plugin install --no-verify 60 | 61 | # Prior to Logstash 2.3 62 | bin/plugin install --no-verify 63 | 64 | ``` 65 | - Run Logstash with your plugin 66 | ```sh 67 | bin/logstash -e 'filter {awesome {}}' 68 | ``` 69 | At this point any modifications to the plugin code will be applied to this local Logstash setup. After modifying the plugin, simply rerun Logstash. 70 | 71 | #### 2.2 Run in an installed Logstash 72 | 73 | You can use the same **2.1** method to run your plugin in an installed Logstash by editing its `Gemfile` and pointing the `:path` to your local plugin development directory or you can build the gem and install it using: 74 | 75 | - Build your plugin gem 76 | ```sh 77 | gem build logstash-filter-awesome.gemspec 78 | ``` 79 | - Install the plugin from the Logstash home 80 | ```sh 81 | # Logstash 2.3 and higher 82 | bin/logstash-plugin install --no-verify 83 | 84 | # Prior to Logstash 2.3 85 | bin/plugin install --no-verify 86 | 87 | ``` 88 | - Start Logstash and proceed to test the plugin 89 | 90 | ## Contributing 91 | 92 | All contributions are welcome: ideas, patches, documentation, bug reports, complaints, and even something you drew up on a napkin. 93 | 94 | Programming is not a required skill. Whatever you've seen about open source and maintainers or community members saying "send patches or die" - you will not see that here. 95 | 96 | It is more important to the community that you are able to contribute. 97 | 98 | For more information about contributing, see the [CONTRIBUTING](https://github.com/elastic/logstash/blob/master/CONTRIBUTING.md) file. -------------------------------------------------------------------------------- /docs/index.asciidoc: -------------------------------------------------------------------------------- 1 | :plugin: jmx 2 | :type: input 3 | :default_codec: plain 4 | 5 | /////////////////////////////////////////// 6 | START - GENERATED VARIABLES, DO NOT EDIT! 7 | /////////////////////////////////////////// 8 | :version: %VERSION% 9 | :release_date: %RELEASE_DATE% 10 | :changelog_url: %CHANGELOG_URL% 11 | :include_path: ../../../../logstash/docs/include 12 | /////////////////////////////////////////// 13 | END - GENERATED VARIABLES, DO NOT EDIT! 14 | /////////////////////////////////////////// 15 | 16 | [id="plugins-{type}s-{plugin}"] 17 | 18 | === Jmx input plugin 19 | 20 | include::{include_path}/plugin_header.asciidoc[] 21 | 22 | ==== Description 23 | 24 | This input plugin permits to retrieve metrics from remote Java applications using JMX. 25 | Every `polling_frequency`, it scans a folder containing json configuration 26 | files describing JVMs to monitor with metrics to retrieve. 27 | Then a pool of threads will retrieve metrics and create events. 28 | 29 | ==== The configuration 30 | 31 | In Logstash configuration, you must set the polling frequency, 32 | the number of thread used to poll metrics and a directory absolute path containing 33 | json files with the configuration per jvm of metrics to retrieve. 34 | Logstash input configuration example: 35 | [source,ruby] 36 | jmx { 37 | //Required 38 | path => "/apps/logstash_conf/jmxconf" 39 | //Optional, default 60s 40 | polling_frequency => 15 41 | type => "jmx" 42 | //Optional, default 4 43 | nb_thread => 4 44 | } 45 | 46 | Json JMX configuration example: 47 | [source,js] 48 | { 49 | //Required, JMX listening host/ip 50 | "host" : "192.168.1.2", 51 | //Required, JMX listening port 52 | "port" : 1335, 53 | //Optional, the username to connect to JMX 54 | "username" : "user", 55 | //Optional, the password to connect to JMX 56 | "password": "pass", 57 | //Optional, use this alias as a prefix in the metric name. If not set use _ 58 | "alias" : "test.homeserver.elasticsearch", 59 | //Required, list of JMX metrics to retrieve 60 | "queries" : [ 61 | { 62 | //Required, the object name of Mbean to request 63 | "object_name" : "java.lang:type=Memory", 64 | //Optional, use this alias in the metrics value instead of the object_name 65 | "object_alias" : "Memory" 66 | }, { 67 | "object_name" : "java.lang:type=Runtime", 68 | //Optional, set of attributes to retrieve. If not set retrieve 69 | //all metrics available on the configured object_name. 70 | "attributes" : [ "Uptime", "StartTime" ], 71 | "object_alias" : "Runtime" 72 | }, { 73 | //object_name can be configured with * to retrieve all matching Mbeans 74 | "object_name" : "java.lang:type=GarbageCollector,name=*", 75 | "attributes" : [ "CollectionCount", "CollectionTime" ], 76 | //object_alias can be based on specific value from the object_name thanks to ${}. 77 | //In this case ${type} will be replaced by GarbageCollector... 78 | "object_alias" : "${type}.${name}" 79 | }, { 80 | "object_name" : "java.nio:type=BufferPool,name=*", 81 | "object_alias" : "${type}.${name}" 82 | } ] 83 | } 84 | 85 | Here are examples of generated events. When returned metrics value type is 86 | number/boolean it is stored in `metric_value_number` event field 87 | otherwise it is stored in `metric_value_string` event field. 88 | [source,ruby] 89 | { 90 | "@version" => "1", 91 | "@timestamp" => "2014-02-18T20:57:27.688Z", 92 | "host" => "192.168.1.2", 93 | "path" => "/apps/logstash_conf/jmxconf", 94 | "type" => "jmx", 95 | "metric_path" => "test.homeserver.elasticsearch.GarbageCollector.ParNew.CollectionCount", 96 | "metric_value_number" => 2212 97 | } 98 | 99 | [source,ruby] 100 | { 101 | "@version" => "1", 102 | "@timestamp" => "2014-02-18T20:58:06.376Z", 103 | "host" => "localhost", 104 | "path" => "/apps/logstash_conf/jmxconf", 105 | "type" => "jmx", 106 | "metric_path" => "test.homeserver.elasticsearch.BufferPool.mapped.ObjectName", 107 | "metric_value_string" => "java.nio:type=BufferPool,name=mapped" 108 | } 109 | 110 | 111 | [id="plugins-{type}s-{plugin}-options"] 112 | ==== Jmx Input Configuration Options 113 | 114 | This plugin supports the following configuration options plus the <> described later. 115 | 116 | [cols="<,<,<",options="header",] 117 | |======================================================================= 118 | |Setting |Input type|Required 119 | | <> |<>|No 120 | | <> |<>|Yes 121 | | <> |<>|No 122 | |======================================================================= 123 | 124 | Also see <> for a list of options supported by all 125 | input plugins. 126 | 127 |   128 | 129 | [id="plugins-{type}s-{plugin}-nb_thread"] 130 | ===== `nb_thread` 131 | 132 | * Value type is <> 133 | * Default value is `4` 134 | 135 | Indicate number of thread launched to retrieve metrics 136 | 137 | [id="plugins-{type}s-{plugin}-path"] 138 | ===== `path` 139 | 140 | * This is a required setting. 141 | * Value type is <> 142 | * There is no default value for this setting. 143 | 144 | Path where json conf files are stored 145 | 146 | [id="plugins-{type}s-{plugin}-polling_frequency"] 147 | ===== `polling_frequency` 148 | 149 | * Value type is <> 150 | * Default value is `60` 151 | 152 | Indicate interval between two jmx metrics retrieval 153 | (in s) 154 | 155 | 156 | 157 | [id="plugins-{type}s-{plugin}-common-options"] 158 | include::{include_path}/{type}.asciidoc[] 159 | 160 | :default_codec!: -------------------------------------------------------------------------------- /spec/inputs/jmx_spec.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | require "logstash/devutils/rspec/spec_helper" 3 | require "logstash/devutils/rspec/shared_examples" 4 | require "logstash/inputs/jmx" 5 | require "logstash/codecs/plain" 6 | require 'stud/temporary' 7 | require "jmx4r" 8 | 9 | describe LogStash::Inputs::Jmx do 10 | 11 | let(:jmx_config_path) { Stud::Temporary.directory } 12 | after(:each) do 13 | FileUtils.remove_dir(jmx_config_path) 14 | end 15 | 16 | it_behaves_like "an interruptible input plugin" do 17 | let(:config) {{"path" => jmx_config_path, "nb_thread" => 1, "polling_frequency" => 1}} 18 | end 19 | 20 | subject { LogStash::Inputs::Jmx.new("path" => jmx_config_path)} 21 | 22 | context "#validate_configuration(conf_hash)" do 23 | #Reference to error messages 24 | MISSING_CONFIG_PARAMETER = LogStash::Inputs::Jmx::MISSING_CONFIG_PARAMETER 25 | BAD_TYPE_CONFIG_PARAMETER = LogStash::Inputs::Jmx::BAD_TYPE_CONFIG_PARAMETER 26 | BAD_TYPE_QUERY = LogStash::Inputs::Jmx::BAD_TYPE_QUERY 27 | MISSING_QUERY_PARAMETER = LogStash::Inputs::Jmx::MISSING_QUERY_PARAMETER 28 | BAD_TYPE_QUERY_PARAMETER = LogStash::Inputs::Jmx::BAD_TYPE_QUERY_PARAMETER 29 | 30 | let(:minimal_config) { {"host"=>"localhost","port"=>1234,"queries" => [] } } 31 | 32 | context "global configuration" do 33 | it "return [] for valid configuration" do 34 | #Minimal configuration 35 | expect(subject.validate_configuration(minimal_config)).to eq([]) 36 | # Re-test with java objects from JrJackson serialization 37 | require "java" 38 | expect(subject.validate_configuration({"host"=>"localhost","port"=>1234,"queries" => java.util.ArrayList.new})).to eq([]) 39 | end 40 | 41 | it "return error message for missing mandatory parameters" do 42 | expect(subject.validate_configuration({})).to eq([MISSING_CONFIG_PARAMETER % "host", MISSING_CONFIG_PARAMETER % "port", MISSING_CONFIG_PARAMETER % "queries"]) 43 | end 44 | 45 | it "return error message for invalid parameters type" do 46 | expect(subject.validate_configuration({"host"=>1234,"port"=>1234,"queries" => []})).to eq([BAD_TYPE_CONFIG_PARAMETER % {:param => "host", :expected => String, :actual => Fixnum}]) 47 | expect(subject.validate_configuration({"host"=>"localhost","port"=>"1234","queries" => []})).to eq([BAD_TYPE_CONFIG_PARAMETER % {:param => "port", :expected => Fixnum, :actual => String}]) 48 | expect(subject.validate_configuration({"host"=>"localhost","port"=>1234,"queries" => "my_query"})).to eq([BAD_TYPE_CONFIG_PARAMETER % {:param => "queries", :expected => Enumerable, :actual => String}]) 49 | end 50 | end 51 | 52 | context "query objects in configuration" do 53 | it "return [] for valid query message" do 54 | #Minimal query object 55 | minimal_config["queries"] = [{"object_name" => "minimal"}] 56 | expect(subject.validate_configuration(minimal_config)).to eq([]) 57 | #Full query object 58 | minimal_config["queries"] = [{ 59 | "object_name" => "java.lang:type=Runtime", 60 | "attributes" => [ "Uptime", "StartTime" ], 61 | "object_alias" => "Runtime"}] 62 | expect(subject.validate_configuration(minimal_config)).to eq([]) 63 | end 64 | it "return error message for invalid query object type" do 65 | minimal_config["queries"] = [ "1234" ] 66 | expect(subject.validate_configuration(minimal_config)).to eq([BAD_TYPE_QUERY % { :index => 0, :expected => Hash, :actual => String }]) 67 | end 68 | 69 | it "return error message for missing mandatory query parameter" do 70 | minimal_config["queries"] = [ {} ] 71 | expect(subject.validate_configuration(minimal_config)).to eq([MISSING_QUERY_PARAMETER % ["object_name",0] ]) 72 | end 73 | 74 | it "return error message for invalid query parameters type" do 75 | minimal_config["queries"] = [ { "object_name" => 1234} ] 76 | expect(subject.validate_configuration(minimal_config)).to eq([BAD_TYPE_QUERY_PARAMETER % {:param => "object_name", :index => 0, :expected => String, :actual => Fixnum} ]) 77 | 78 | minimal_config["queries"] = [ { "object_name" => "1234", "object_alias" => 1234} ] 79 | expect(subject.validate_configuration(minimal_config)).to eq([BAD_TYPE_QUERY_PARAMETER % {:param => "object_alias", :index => 0, :expected => String, :actual => Fixnum} ]) 80 | 81 | minimal_config["queries"] = [ { "object_name" => "1234", "attributes" => 1234} ] 82 | expect(subject.validate_configuration(minimal_config)).to eq([BAD_TYPE_QUERY_PARAMETER % {:param => "attributes", :index => 0, :expected => Enumerable, :actual => Fixnum} ]) 83 | end 84 | end 85 | end 86 | 87 | context "establish JMX connection" do 88 | subject { LogStash::Inputs::Jmx.new("path" => jmx_config_path, "nb_thread" => 1, "polling_frequency" => 1)} 89 | 90 | let(:queue) { Queue.new } 91 | 92 | it "pass host/port connection parameters to jmx4r" do 93 | File.open(File.join(jmx_config_path,"my.config.json"), "wb") { |file| file.write(<<-EOT) 94 | { 95 | "host" : "localhost", 96 | "port" : 1234, 97 | "queries": [] 98 | } 99 | EOT 100 | } 101 | 102 | expect(JMX::MBean).to receive(:connection).with({ 103 | :host => "localhost", 104 | :port => 1234, 105 | :url => nil 106 | }).and_return(nil) 107 | 108 | subject.register 109 | Thread.new(subject) { sleep 0.5; subject.do_stop } # force the plugin to exit 110 | subject.run(queue) 111 | end 112 | 113 | it "pass custom url in addition of host/port connection parameters to jmx4r" do 114 | File.open(File.join(jmx_config_path,"my.config.json"), "wb") { |file| file.write(<<-EOT) 115 | { 116 | "host" : "localhost", 117 | "port" : 1234, 118 | "url" : "abcdefg", 119 | "queries": [] 120 | } 121 | EOT 122 | } 123 | 124 | expect(JMX::MBean).to receive(:connection).with({ 125 | :host => "localhost", 126 | :port => 1234, 127 | :url => "abcdefg" 128 | }).and_return(nil) 129 | 130 | subject.register 131 | Thread.new(subject) { sleep 0.5; subject.do_stop } # force the plugin to exit 132 | subject.run(queue) 133 | end 134 | 135 | it "pass host/port username/password connection parameters to jmx4r" do 136 | File.open(File.join(jmx_config_path,"my.config.json"), "wb") { |file| file.write(<<-EOT) 137 | { 138 | "host" : "localhost", 139 | "port" : 1234, 140 | "username" : "me", 141 | "password" : "secret", 142 | "queries": [] 143 | } 144 | EOT 145 | } 146 | 147 | expect(JMX::MBean).to receive(:connection).with({ 148 | :host => "localhost", 149 | :port => 1234, 150 | :url => nil, 151 | :username => "me", 152 | :password => "secret" 153 | }).and_return(nil) 154 | 155 | subject.register 156 | Thread.new(subject) { sleep 0.5; subject.do_stop } # force the plugin to exit 157 | subject.run(queue) 158 | end 159 | end 160 | end 161 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2020 Elastic and contributors 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /lib/logstash/inputs/jmx.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | require "logstash/inputs/base" 3 | require "logstash/namespace" 4 | require "logstash/json" 5 | 6 | # This input plugin permits to retrieve metrics from remote Java applications using JMX. 7 | # Every `polling_frequency`, it scans a folder containing json configuration 8 | # files describing JVMs to monitor with metrics to retrieve. 9 | # Then a pool of threads will retrieve metrics and create events. 10 | # 11 | # ## The configuration: 12 | # 13 | # In Logstash configuration, you must set the polling frequency, 14 | # the number of thread used to poll metrics and a directory absolute path containing 15 | # json files with the configuration per jvm of metrics to retrieve. 16 | # Logstash input configuration example: 17 | # [source,ruby] 18 | # jmx { 19 | # //Required 20 | # path => "/apps/logstash_conf/jmxconf" 21 | # //Optional, default 60s 22 | # polling_frequency => 15 23 | # type => "jmx" 24 | # //Optional, default 4 25 | # nb_thread => 4 26 | # } 27 | # 28 | # Json JMX configuration example: 29 | # [source,js] 30 | # { 31 | # //Required, JMX listening host/ip 32 | # "host" : "192.168.1.2", 33 | # //Required, JMX listening port 34 | # "port" : 1335, 35 | # //Optional, the username to connect to JMX 36 | # "username" : "user", 37 | # //Optional, the password to connect to JMX 38 | # "password": "pass", 39 | # //Optional, use this alias as a prefix in the metric name. If not set use _ 40 | # "alias" : "test.homeserver.elasticsearch", 41 | # //Required, list of JMX metrics to retrieve 42 | # "queries" : [ 43 | # { 44 | # //Required, the object name of Mbean to request 45 | # "object_name" : "java.lang:type=Memory", 46 | # //Optional, use this alias in the metrics value instead of the object_name 47 | # "object_alias" : "Memory" 48 | # }, { 49 | # "object_name" : "java.lang:type=Runtime", 50 | # //Optional, set of attributes to retrieve. If not set retrieve 51 | # //all metrics available on the configured object_name. 52 | # "attributes" : [ "Uptime", "StartTime" ], 53 | # "object_alias" : "Runtime" 54 | # }, { 55 | # //object_name can be configured with * to retrieve all matching Mbeans 56 | # "object_name" : "java.lang:type=GarbageCollector,name=*", 57 | # "attributes" : [ "CollectionCount", "CollectionTime" ], 58 | # //object_alias can be based on specific value from the object_name thanks to ${}. 59 | # //In this case ${type} will be replaced by GarbageCollector... 60 | # "object_alias" : "${type}.${name}" 61 | # }, { 62 | # "object_name" : "java.nio:type=BufferPool,name=*", 63 | # "object_alias" : "${type}.${name}" 64 | # } ] 65 | # } 66 | # 67 | # Here are examples of generated events. When returned metrics value type is 68 | # number/boolean it is stored in `metric_value_number` event field 69 | # otherwise it is stored in `metric_value_string` event field. 70 | # [source,ruby] 71 | # { 72 | # "@version" => "1", 73 | # "@timestamp" => "2014-02-18T20:57:27.688Z", 74 | # "host" => "192.168.1.2", 75 | # "path" => "/apps/logstash_conf/jmxconf", 76 | # "type" => "jmx", 77 | # "metric_path" => "test.homeserver.elasticsearch.GarbageCollector.ParNew.CollectionCount", 78 | # "metric_value_number" => 2212 79 | # } 80 | # 81 | # [source,ruby] 82 | # { 83 | # "@version" => "1", 84 | # "@timestamp" => "2014-02-18T20:58:06.376Z", 85 | # "host" => "localhost", 86 | # "path" => "/apps/logstash_conf/jmxconf", 87 | # "type" => "jmx", 88 | # "metric_path" => "test.homeserver.elasticsearch.BufferPool.mapped.ObjectName", 89 | # "metric_value_string" => "java.nio:type=BufferPool,name=mapped" 90 | # } 91 | # 92 | class LogStash::Inputs::Jmx < LogStash::Inputs::Base 93 | config_name 'jmx' 94 | 95 | #Class Var 96 | attr_accessor :regexp_group_alias_object 97 | attr_accessor :queue_conf 98 | 99 | # Path where json conf files are stored 100 | config :path, :validate => :string, :required => true 101 | 102 | # Indicate interval between two jmx metrics retrieval 103 | # (in s) 104 | config :polling_frequency, :validate => :number, :default => 60 105 | 106 | # Indicate number of thread launched to retrieve metrics 107 | config :nb_thread, :validate => :number, :default => 4 108 | 109 | #Error messages 110 | MISSING_CONFIG_PARAMETER = "Missing parameter '%s'." 111 | BAD_TYPE_CONFIG_PARAMETER = "Bad type for parameter '%{param}', expecting '%{expected}', found '%{actual}'." 112 | MISSING_QUERY_PARAMETER = "Missing parameter '%s' in queries[%d]." 113 | BAD_TYPE_QUERY = "Bad type for queries[%{index}], expecting '%{expected}', found '%{actual}'." 114 | BAD_TYPE_QUERY_PARAMETER = "Bad type for parameter '%{param}' in queries[%{index}], expecting '%{expected}', found '%{actual}'." 115 | # Verify that all required parameter are present in the conf_hash 116 | public 117 | def validate_configuration(conf_hash) 118 | validation_errors = [] 119 | #Check required parameters in configuration 120 | ["host", "port","queries"].each do |param| 121 | validation_errors << MISSING_CONFIG_PARAMETER % param unless conf_hash.has_key?(param) 122 | end 123 | 124 | #Validate parameters type in configuration 125 | {"host" => String, "port" => Fixnum, "alias" => String }.each do |param, expected_type| 126 | if conf_hash.has_key?(param) && !conf_hash[param].instance_of?(expected_type) 127 | validation_errors << BAD_TYPE_CONFIG_PARAMETER % { :param => param, :expected => expected_type, :actual => conf_hash[param].class } 128 | end 129 | end 130 | 131 | if conf_hash.has_key?("queries") 132 | if !conf_hash["queries"].respond_to?(:each) 133 | validation_errors << BAD_TYPE_CONFIG_PARAMETER % { :param => 'queries', :expected => Enumerable, :actual => conf_hash['queries'].class } 134 | else 135 | conf_hash['queries'].each_with_index do |query,index| 136 | unless query.respond_to?(:[]) && query.respond_to?(:has_key?) 137 | validation_errors << BAD_TYPE_QUERY % {:index => index, :expected => Hash, :actual => query.class} 138 | next 139 | end 140 | #Check required parameters in each query 141 | ["object_name"].each do |param| 142 | validation_errors << MISSING_QUERY_PARAMETER % [param,index] unless query.has_key?(param) 143 | end 144 | #Validate parameters type in each query 145 | {"object_name" => String, "object_alias" => String }.each do |param, expected_type| 146 | if query.has_key?(param) && !query[param].instance_of?(expected_type) 147 | validation_errors << BAD_TYPE_QUERY_PARAMETER % { :param => param, :index => index, :expected => expected_type, :actual => query[param].class } 148 | end 149 | end 150 | 151 | if query.has_key?("attributes") && !query["attributes"].respond_to?(:each) 152 | validation_errors << BAD_TYPE_QUERY_PARAMETER % { :param => 'attributes', :index => index, :expected => Enumerable, :actual => query['attributes'].class } 153 | end 154 | end 155 | end 156 | end 157 | return validation_errors 158 | end 159 | 160 | private 161 | def replace_alias_object(r_alias_object,object_name) 162 | @logger.debug("Replace ${.*} variables from #{r_alias_object} using #{object_name}") 163 | group_alias = @regexp_group_alias_object.match(r_alias_object) 164 | if group_alias 165 | r_alias_object = r_alias_object.gsub('${'+group_alias[1]+'}',object_name.split(group_alias[1]+'=')[1].split(',')[0]) 166 | r_alias_object = replace_alias_object(r_alias_object,object_name) 167 | end 168 | r_alias_object 169 | end 170 | 171 | private 172 | def send_event_to_queue(queue,host,metric_path,metric_value) 173 | @logger.debug('Send event to queue to be processed by filters/outputs') 174 | event = LogStash::Event.new 175 | event.set('host', host) 176 | event.set('path', @path) 177 | event.set('type', @type) 178 | number_type = [Fixnum, Bignum, Float] 179 | boolean_type = [TrueClass, FalseClass] 180 | metric_path_substituted = metric_path.gsub(' ','_').gsub('"','') 181 | if number_type.include?(metric_value.class) 182 | @logger.debug("The value #{metric_value} is of type number: #{metric_value.class}") 183 | event.set('metric_path', metric_path_substituted) 184 | event.set('metric_value_number', metric_value) 185 | elsif boolean_type.include?(metric_value.class) 186 | @logger.debug("The value #{metric_value} is of type boolean: #{metric_value.class}") 187 | event.set('metric_path', metric_path_substituted+'_bool') 188 | event.set('metric_value_number', metric_value ? 1 : 0) 189 | else 190 | @logger.debug("The value #{metric_value} is not of type number: #{metric_value.class}") 191 | event.set('metric_path', metric_path_substituted) 192 | event.set('metric_value_string', metric_value.to_s) 193 | end 194 | decorate(event) 195 | queue << event 196 | end 197 | 198 | # Thread function to retrieve metrics from JMX 199 | private 200 | def thread_jmx(queue_conf,queue) 201 | while true 202 | begin 203 | @logger.debug('Wait config to retrieve from queue conf') 204 | thread_hash_conf = queue_conf.pop 205 | 206 | if thread_hash_conf == :END 207 | # the :END symbol is a signal to terminate the thread 208 | @logger.debug? && @logger.debug("Received jmx thread termination signal") 209 | return 210 | else 211 | @logger.debug? && @logger.debug("Retrieve config #{thread_hash_conf} from queue conf") 212 | end 213 | 214 | @logger.debug('Check if jmx connection need a user/password') 215 | if thread_hash_conf.has_key?('username') and thread_hash_conf.has_key?('password') 216 | @logger.debug("Connect to #{thread_hash_conf['host']}:#{thread_hash_conf['port']} with user #{thread_hash_conf['username']}") 217 | jmx_connection = JMX::MBean.connection :host => thread_hash_conf['host'], 218 | :port => thread_hash_conf['port'], 219 | :url => thread_hash_conf['url'], 220 | :username => thread_hash_conf['username'], 221 | :password => thread_hash_conf['password'] 222 | else 223 | @logger.debug("Connect to #{thread_hash_conf['host']}:#{thread_hash_conf['port']}:#{thread_hash_conf['url']}") 224 | jmx_connection = JMX::MBean.connection :host => thread_hash_conf['host'], 225 | :port => thread_hash_conf['port'], 226 | :url => thread_hash_conf['url'] 227 | end 228 | 229 | if jmx_connection.nil? 230 | @logger.warn("Invalid nil jmx connection, ignoring", :host => thread_hash_conf['host'], :port => thread_hash_conf['port'], :url => thread_hash_conf['url']) 231 | next 232 | end 233 | 234 | if thread_hash_conf.has_key?('alias') 235 | @logger.debug("Set base_metric_path to alias: #{thread_hash_conf['alias']}") 236 | base_metric_path = thread_hash_conf['alias'] 237 | else 238 | @logger.debug("Set base_metric_path to host_port: #{thread_hash_conf['host']}_#{thread_hash_conf['port']}") 239 | base_metric_path = "#{thread_hash_conf['host']}_#{thread_hash_conf['port']}" 240 | end 241 | 242 | 243 | @logger.debug("Treat queries #{thread_hash_conf['queries']}") 244 | thread_hash_conf['queries'].each do |query| 245 | @logger.debug("Find all objects name #{query['object_name']}") 246 | jmx_object_name_s = JMX::MBean.find_all_by_name(query['object_name'], :connection => jmx_connection) 247 | 248 | if jmx_object_name_s.length > 0 249 | jmx_object_name_s.each do |jmx_object_name| 250 | if query.has_key?('object_alias') 251 | object_name = replace_alias_object(query['object_alias'],jmx_object_name.object_name.to_s) 252 | @logger.debug("Set object_name to object_alias: #{object_name}") 253 | else 254 | object_name = jmx_object_name.object_name.to_s 255 | @logger.debug("Set object_name to jmx object_name: #{object_name}") 256 | end 257 | 258 | if query.has_key?('attributes') 259 | @logger.debug("Retrieves attributes #{query['attributes']} to #{jmx_object_name.object_name}") 260 | query['attributes'].each do |attribute| 261 | begin 262 | jmx_attribute_value = jmx_object_name.send(attribute.snake_case) 263 | if jmx_attribute_value.instance_of? Java::JavaxManagementOpenmbean::CompositeDataSupport 264 | @logger.debug('The jmx value is a composite_data one') 265 | jmx_attribute_value.each do |jmx_attribute_value_composite| 266 | @logger.debug("Get jmx value #{jmx_attribute_value[jmx_attribute_value_composite]} for attribute #{attribute}.#{jmx_attribute_value_composite} to #{jmx_object_name.object_name}") 267 | send_event_to_queue(queue, thread_hash_conf['host'], "#{base_metric_path}.#{object_name}.#{attribute}.#{jmx_attribute_value_composite}", jmx_attribute_value[jmx_attribute_value_composite]) 268 | end 269 | else 270 | @logger.debug("Get jmx value #{jmx_attribute_value} for attribute #{attribute} to #{jmx_object_name.object_name}") 271 | send_event_to_queue(queue, thread_hash_conf['host'], "#{base_metric_path}.#{object_name}.#{attribute}", jmx_attribute_value) 272 | end 273 | rescue Exception => ex 274 | @logger.warn("Failed retrieving metrics for attribute #{attribute} on object #{jmx_object_name.object_name}") 275 | @logger.warn(ex.message) 276 | end 277 | end 278 | else 279 | @logger.debug("No attribute to retrieve define on #{jmx_object_name.object_name}, will retrieve all") 280 | jmx_object_name.attributes.each_key do |attribute| 281 | begin 282 | jmx_attribute_value = jmx_object_name.send(attribute) 283 | if jmx_attribute_value.instance_of? Java::JavaxManagementOpenmbean::CompositeDataSupport 284 | @logger.debug('The jmx value is a composite_data one') 285 | jmx_attribute_value.each do |jmx_attribute_value_composite| 286 | @logger.debug("Get jmx value #{jmx_attribute_value[jmx_attribute_value_composite]} for attribute #{jmx_object_name.attributes[attribute]}.#{jmx_attribute_value_composite} to #{jmx_object_name.object_name}") 287 | send_event_to_queue(queue, thread_hash_conf['host'], "#{base_metric_path}.#{object_name}.#{jmx_object_name.attributes[attribute]}.#{jmx_attribute_value_composite}", jmx_attribute_value[jmx_attribute_value_composite]) 288 | end 289 | else 290 | @logger.debug("Get jmx value #{jmx_attribute_value} for attribute #{jmx_object_name.attributes[attribute]} to #{jmx_object_name.object_name}") 291 | send_event_to_queue(queue, thread_hash_conf['host'], "#{base_metric_path}.#{object_name}.#{jmx_object_name.attributes[attribute]}", jmx_attribute_value) 292 | end 293 | rescue Exception => ex 294 | @logger.warn("Failed retrieving metrics for attribute #{attribute} on object #{jmx_object_name.object_name}") 295 | @logger.warn(ex.message) 296 | end 297 | end 298 | end 299 | end 300 | else 301 | @logger.warn("No jmx object found for #{query['object_name']}") 302 | end 303 | end 304 | jmx_connection.close 305 | rescue Exception => ex 306 | @logger.error(ex.message) 307 | @logger.error(ex.backtrace.join("\n")) 308 | end 309 | end 310 | end 311 | 312 | public 313 | def register 314 | require 'thread' 315 | require 'jmx4r' 316 | 317 | @logger.info("Create queue dispatching JMX requests to threads") 318 | @queue_conf = Queue.new 319 | 320 | @logger.info("Compile regexp for group alias object replacement") 321 | @regexp_group_alias_object = Regexp.new('(?:\${(.*?)})+') 322 | end 323 | 324 | public 325 | def run(queue) 326 | begin 327 | threads = [] 328 | @logger.info("Initialize #{@nb_thread} threads for JMX metrics collection") 329 | @nb_thread.times do 330 | threads << Thread.new { thread_jmx(@queue_conf,queue) } 331 | end 332 | 333 | while !stop? 334 | @logger.info("Loading configuration files in path", :path => @path) 335 | Dir.foreach(@path) do |item| 336 | next if item == '.' or item == '..' 337 | begin 338 | file_conf = File.join(@path, item) 339 | @logger.debug? && @logger.debug("Loading configuration from file", :file => file_conf) 340 | config_string = File.read(file_conf) 341 | conf_hash = LogStash::Json.load(config_string) 342 | validation_errors = validate_configuration(conf_hash) 343 | if validation_errors.empty? 344 | @logger.debug? && @logger.debug("Add configuration to the queue", :config => conf_hash) 345 | @queue_conf << conf_hash 346 | else 347 | @logger.warn("Issue with configuration file", :file => file_conf, 348 | :validation_errors => validation_errors) 349 | end 350 | rescue Exception => ex 351 | @logger.warn("Issue loading configuration from file", :file => file_conf, 352 | :exception => ex.message, :backtrace => ex.backtrace) 353 | end 354 | end 355 | 356 | @logger.debug('Wait until the queue conf is empty') 357 | delta=0 358 | until @queue_conf.empty? 359 | @logger.debug("There are still #{@queue_conf.size} messages in the queue conf. Sleep 1s.") 360 | delta=delta+1 361 | sleep(1) 362 | end 363 | 364 | wait_time=@polling_frequency-delta 365 | if wait_time>0 366 | @logger.debug("Wait #{wait_time}s (#{@polling_frequency}-#{delta}(seconds wait until queue conf empty)) before to launch again a new jmx metrics collection") 367 | Stud.stoppable_sleep(wait_time) { stop? } 368 | else 369 | @logger.warn("The time taken to retrieve metrics is more important than the retrieve_interval time set. 370 | \nYou must adapt nb_thread, retrieve_interval to the number of jvm/metrics you want to retrieve.") 371 | end 372 | end 373 | rescue Exception => ex 374 | @logger.error(ex.message) 375 | @logger.error(ex.backtrace.join("\n")) 376 | ensure 377 | @nb_thread.times do |i| 378 | @logger.debug? && @logger.debug("Signaling termination to jmx thread #{i + 1}") 379 | @queue_conf << :END 380 | end 381 | threads.each {|t| t.join } 382 | end 383 | end 384 | end 385 | --------------------------------------------------------------------------------