diff --git a/plugins/inputs/all/jolokia.go b/plugins/inputs/all/jolokia.go deleted file mode 100644 index c01c9244f..000000000 --- a/plugins/inputs/all/jolokia.go +++ /dev/null @@ -1,5 +0,0 @@ -//go:build !custom || inputs || inputs.jolokia - -package all - -import _ "github.com/influxdata/telegraf/plugins/inputs/jolokia" // register plugin diff --git a/plugins/inputs/jolokia/README.md b/plugins/inputs/jolokia/README.md deleted file mode 100644 index 6654d84c1..000000000 --- a/plugins/inputs/jolokia/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# Jolokia Input Plugin - -**Deprecated in version 1.5: Please use the [jolokia2][] plugin** - -## Global configuration options - -In addition to the plugin-specific configuration settings, plugins support -additional global and plugin configuration settings. These settings are used to -modify metrics, tags, and field or create aliases and configure ordering, etc. -See the [CONFIGURATION.md][CONFIGURATION.md] for more details. - -[CONFIGURATION.md]: ../../../docs/CONFIGURATION.md#plugins - -## Configuration - -```toml @sample.conf -# Read JMX metrics through Jolokia -[[inputs.jolokia]] - ## This is the context root used to compose the jolokia url - ## NOTE that Jolokia requires a trailing slash at the end of the context root - context = "/jolokia/" - - ## This specifies the mode used - # mode = "proxy" - # - ## When in proxy mode this section is used to specify further - ## proxy address configurations. - ## Remember to change host address to fit your environment. - # [inputs.jolokia.proxy] - # host = "127.0.0.1" - # port = "8080" - - ## Optional http timeouts - ## - ## response_header_timeout, if non-zero, specifies the amount of time to wait - ## for a server's response headers after fully writing the request. - # response_header_timeout = "3s" - ## - ## client_timeout specifies a time limit for requests made by this client. - ## Includes connection time, any redirects, and reading the response body. - # client_timeout = "4s" - - ## List of servers exposing jolokia read service - [[inputs.jolokia.servers]] - name = "as-server-01" - host = "127.0.0.1" - port = "8080" - # username = "myuser" - # password = "mypassword" - - ## List of metrics collected on above servers - ## Each metric consists in a name, a jmx path and either - ## a pass or drop slice attribute. - ## This collect all heap memory usage metrics. - [[inputs.jolokia.metrics]] - name = "heap_memory_usage" - mbean = "java.lang:type=Memory" - attribute = "HeapMemoryUsage" - - ## This collect thread counts metrics. - [[inputs.jolokia.metrics]] - name = "thread_count" - mbean = "java.lang:type=Threading" - attribute = "TotalStartedThreadCount,ThreadCount,DaemonThreadCount,PeakThreadCount" - - ## This collect number of class loaded/unloaded counts metrics. - [[inputs.jolokia.metrics]] - name = "class_count" - mbean = "java.lang:type=ClassLoading" - attribute = "LoadedClassCount,UnloadedClassCount,TotalLoadedClassCount" -``` - -## Description - -The Jolokia plugin collects JVM metrics exposed as MBean's attributes through -jolokia REST endpoint. All metrics are collected for each server configured. -See [official Jolokia website](https://jolokia.org/) for more information. - -## Metrics - -Jolokia plugin produces one measure for each metric configured, -adding Server's `jolokia_name`, `jolokia_host` and `jolokia_port` as tags. - -[jolokia2]: /plugins/inputs/jolokia2 - -## Example Output diff --git a/plugins/inputs/jolokia/jolokia.go b/plugins/inputs/jolokia/jolokia.go deleted file mode 100644 index 06d8fd3ed..000000000 --- a/plugins/inputs/jolokia/jolokia.go +++ /dev/null @@ -1,264 +0,0 @@ -//go:generate ../../../tools/readme_config_includer/generator -package jolokia - -import ( - "bytes" - _ "embed" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "time" - - "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/config" - "github.com/influxdata/telegraf/plugins/inputs" -) - -//go:embed sample.conf -var sampleConfig string - -// Default http timeouts -var DefaultResponseHeaderTimeout = config.Duration(3 * time.Second) -var DefaultClientTimeout = config.Duration(4 * time.Second) - -type Server struct { - Name string - Host string - Username string - Password string - Port string -} - -type Metric struct { - Name string - Mbean string - Attribute string - Path string -} - -type JolokiaClient interface { - MakeRequest(req *http.Request) (*http.Response, error) -} - -type JolokiaClientImpl struct { - client *http.Client -} - -func (c JolokiaClientImpl) MakeRequest(req *http.Request) (*http.Response, error) { - return c.client.Do(req) -} - -type Jolokia struct { - jClient JolokiaClient - Context string - Mode string - Servers []Server - Metrics []Metric - Proxy Server - Delimiter string - - ResponseHeaderTimeout config.Duration `toml:"response_header_timeout"` - ClientTimeout config.Duration `toml:"client_timeout"` - Log telegraf.Logger `toml:"-"` -} - -func (j *Jolokia) doRequest(req *http.Request) ([]map[string]interface{}, error) { - resp, err := j.jClient.MakeRequest(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - // Process response - if resp.StatusCode != http.StatusOK { - err = fmt.Errorf("response from url %q has status code %d (%s), expected %d (%s)", - req.RequestURI, - resp.StatusCode, - http.StatusText(resp.StatusCode), - http.StatusOK, - http.StatusText(http.StatusOK)) - return nil, err - } - - // read body - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - // Unmarshal json - var jsonOut []map[string]interface{} - if err = json.Unmarshal(body, &jsonOut); err != nil { - return nil, fmt.Errorf("error decoding JSON response %q: %w", body, err) - } - - return jsonOut, nil -} - -func (j *Jolokia) prepareRequest(server Server, metrics []Metric) (*http.Request, error) { - var jolokiaURL *url.URL - context := j.Context // Usually "/jolokia/" - - bulkBodyContent := make([]map[string]interface{}, 0, len(metrics)) - for _, metric := range metrics { - // Create bodyContent - bodyContent := map[string]interface{}{ - "type": "read", - "mbean": metric.Mbean, - } - - if metric.Attribute != "" { - bodyContent["attribute"] = metric.Attribute - if metric.Path != "" { - bodyContent["path"] = metric.Path - } - } - - // Add target, only in proxy mode - if j.Mode == "proxy" { - serviceURL := fmt.Sprintf("service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi", - server.Host, server.Port) - - target := map[string]string{ - "url": serviceURL, - } - - if server.Username != "" { - target["user"] = server.Username - } - - if server.Password != "" { - target["password"] = server.Password - } - - bodyContent["target"] = target - - proxy := j.Proxy - - // Prepare ProxyURL - proxyURL, err := url.Parse("http://" + proxy.Host + ":" + proxy.Port + context) - if err != nil { - return nil, err - } - if proxy.Username != "" || proxy.Password != "" { - proxyURL.User = url.UserPassword(proxy.Username, proxy.Password) - } - - jolokiaURL = proxyURL - } else { - serverURL, err := url.Parse("http://" + server.Host + ":" + server.Port + context) - if err != nil { - return nil, err - } - if server.Username != "" || server.Password != "" { - serverURL.User = url.UserPassword(server.Username, server.Password) - } - - jolokiaURL = serverURL - } - - bulkBodyContent = append(bulkBodyContent, bodyContent) - } - - requestBody, err := json.Marshal(bulkBodyContent) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", jolokiaURL.String(), bytes.NewBuffer(requestBody)) - if err != nil { - return nil, err - } - - req.Header.Add("Content-type", "application/json") - - return req, nil -} - -func (j *Jolokia) extractValues(measurement string, value interface{}, fields map[string]interface{}) { - if mapValues, ok := value.(map[string]interface{}); ok { - for k2, v2 := range mapValues { - j.extractValues(measurement+j.Delimiter+k2, v2, fields) - } - } else { - fields[measurement] = value - } -} - -func (*Jolokia) SampleConfig() string { - return sampleConfig -} - -func (j *Jolokia) Gather(acc telegraf.Accumulator) error { - if j.jClient == nil { - j.Log.Warn("DEPRECATED: the jolokia plugin has been deprecated " + - "in favor of the jolokia2 plugin " + - "(https://github.com/influxdata/telegraf/tree/master/plugins/inputs/jolokia2)") - - tr := &http.Transport{ResponseHeaderTimeout: time.Duration(j.ResponseHeaderTimeout)} - j.jClient = &JolokiaClientImpl{&http.Client{ - Transport: tr, - Timeout: time.Duration(j.ClientTimeout), - }} - } - - servers := j.Servers - metrics := j.Metrics - tags := make(map[string]string) - - for _, server := range servers { - tags["jolokia_name"] = server.Name - tags["jolokia_port"] = server.Port - tags["jolokia_host"] = server.Host - fields := make(map[string]interface{}) - - req, err := j.prepareRequest(server, metrics) - if err != nil { - acc.AddError(fmt.Errorf("unable to create request: %w", err)) - continue - } - out, err := j.doRequest(req) - if err != nil { - acc.AddError(fmt.Errorf("error performing request: %w", err)) - continue - } - - if len(out) != len(metrics) { - acc.AddError(fmt.Errorf("did not receive the correct number of metrics in response. expected %d, received %d", len(metrics), len(out))) - continue - } - for i, resp := range out { - if status, ok := resp["status"]; ok && status != float64(200) { - acc.AddError(fmt.Errorf("not expected status value in response body (%s:%s mbean=%q attribute=%q): %3.f", - server.Host, server.Port, metrics[i].Mbean, metrics[i].Attribute, status)) - continue - } else if !ok { - acc.AddError(errors.New("missing status in response body")) - continue - } - - if values, ok := resp["value"]; ok { - j.extractValues(metrics[i].Name, values, fields) - } else { - acc.AddError(errors.New("missing key 'value' in output response")) - } - } - - acc.AddFields("jolokia", fields, tags) - } - - return nil -} - -func init() { - inputs.Add("jolokia", func() telegraf.Input { - return &Jolokia{ - ResponseHeaderTimeout: DefaultResponseHeaderTimeout, - ClientTimeout: DefaultClientTimeout, - Delimiter: "_", - } - }) -} diff --git a/plugins/inputs/jolokia/jolokia_test.go b/plugins/inputs/jolokia/jolokia_test.go deleted file mode 100644 index 1b4280fb9..000000000 --- a/plugins/inputs/jolokia/jolokia_test.go +++ /dev/null @@ -1,248 +0,0 @@ -package jolokia - -import ( - "io" - "net/http" - "strings" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/influxdata/telegraf/testutil" -) - -const validThreeLevelMultiValueJSON = ` -[ - { - "request":{ - "mbean":"java.lang:type=*", - "type":"read" - }, - "value":{ - "java.lang:type=Memory":{ - "ObjectPendingFinalizationCount":0, - "Verbose":false, - "HeapMemoryUsage":{ - "init":134217728, - "committed":173015040, - "max":1908932608, - "used":16840016 - }, - "NonHeapMemoryUsage":{ - "init":2555904, - "committed":51380224, - "max":-1, - "used":49944048 - }, - "ObjectName":{ - "objectName":"java.lang:type=Memory" - } - } - }, - "timestamp":1446129191, - "status":200 - } -]` - -const validBulkResponseJSON = ` -[ - { - "request":{ - "mbean":"java.lang:type=Memory", - "attribute":"HeapMemoryUsage", - "type":"read" - }, - "value":{ - "init":67108864, - "committed":456130560, - "max":477626368, - "used":203288528 - }, - "timestamp":1446129191, - "status":200 - }, - { - "request":{ - "mbean":"java.lang:type=Memory", - "attribute":"NonHeapMemoryUsage", - "type":"read" - }, - "value":{ - "init":2555904, - "committed":51380224, - "max":-1, - "used":49944048 - }, - "timestamp":1446129191, - "status":200 - } -]` - -const validMultiValueJSON = ` -[ - { - "request":{ - "mbean":"java.lang:type=Memory", - "attribute":"HeapMemoryUsage", - "type":"read" - }, - "value":{ - "init":67108864, - "committed":456130560, - "max":477626368, - "used":203288528 - }, - "timestamp":1446129191, - "status":200 - } -]` - -const invalidJSON = "I don't think this is JSON" - -var Servers = []Server{{Name: "as1", Host: "127.0.0.1", Port: "8080"}} -var HeapMetric = Metric{Name: "heap_memory_usage", - Mbean: "java.lang:type=Memory", Attribute: "HeapMemoryUsage"} -var UsedHeapMetric = Metric{Name: "heap_memory_usage", - Mbean: "java.lang:type=Memory", Attribute: "HeapMemoryUsage"} -var NonHeapMetric = Metric{Name: "non_heap_memory_usage", - Mbean: "java.lang:type=Memory", Attribute: "NonHeapMemoryUsage"} - -type jolokiaClientStub struct { - responseBody string - statusCode int -} - -func (c jolokiaClientStub) MakeRequest(_ *http.Request) (*http.Response, error) { - resp := http.Response{} - resp.StatusCode = c.statusCode - resp.Body = io.NopCloser(strings.NewReader(c.responseBody)) - return &resp, nil -} - -// Generates a pointer to an HttpJson object that uses a mock HTTP client. -// Parameters: -// -// response : Body of the response that the mock HTTP client should return -// statusCode: HTTP status code the mock HTTP client should return -// -// Returns: -// -// *HttpJson: Pointer to an HttpJson object that uses the generated mock HTTP client -func genJolokiaClientStub(response string, statusCode int, servers []Server, metrics []Metric) *Jolokia { - return &Jolokia{ - jClient: jolokiaClientStub{responseBody: response, statusCode: statusCode}, - Servers: servers, - Metrics: metrics, - Delimiter: "_", - } -} - -// Test that the proper values are ignored or collected -func TestHttpJsonMultiValue(t *testing.T) { - jolokia := genJolokiaClientStub(validMultiValueJSON, 200, Servers, []Metric{HeapMetric}) - - var acc testutil.Accumulator - err := acc.GatherError(jolokia.Gather) - - require.NoError(t, err) - require.Len(t, acc.Metrics, 1) - - fields := map[string]interface{}{ - "heap_memory_usage_init": 67108864.0, - "heap_memory_usage_committed": 456130560.0, - "heap_memory_usage_max": 477626368.0, - "heap_memory_usage_used": 203288528.0, - } - tags := map[string]string{ - "jolokia_host": "127.0.0.1", - "jolokia_port": "8080", - "jolokia_name": "as1", - } - acc.AssertContainsTaggedFields(t, "jolokia", fields, tags) -} - -// Test that bulk responses are handled -func TestHttpJsonBulkResponse(t *testing.T) { - jolokia := genJolokiaClientStub(validBulkResponseJSON, 200, Servers, []Metric{HeapMetric, NonHeapMetric}) - - var acc testutil.Accumulator - err := jolokia.Gather(&acc) - - require.NoError(t, err) - require.Len(t, acc.Metrics, 1) - - fields := map[string]interface{}{ - "heap_memory_usage_init": 67108864.0, - "heap_memory_usage_committed": 456130560.0, - "heap_memory_usage_max": 477626368.0, - "heap_memory_usage_used": 203288528.0, - "non_heap_memory_usage_init": 2555904.0, - "non_heap_memory_usage_committed": 51380224.0, - "non_heap_memory_usage_max": -1.0, - "non_heap_memory_usage_used": 49944048.0, - } - tags := map[string]string{ - "jolokia_host": "127.0.0.1", - "jolokia_port": "8080", - "jolokia_name": "as1", - } - acc.AssertContainsTaggedFields(t, "jolokia", fields, tags) -} - -// Test that the proper values are ignored or collected -func TestHttpJsonThreeLevelMultiValue(t *testing.T) { - jolokia := genJolokiaClientStub(validThreeLevelMultiValueJSON, 200, Servers, []Metric{HeapMetric}) - - var acc testutil.Accumulator - err := acc.GatherError(jolokia.Gather) - - require.NoError(t, err) - require.Len(t, acc.Metrics, 1) - - fields := map[string]interface{}{ - "heap_memory_usage_java.lang:type=Memory_ObjectPendingFinalizationCount": 0.0, - "heap_memory_usage_java.lang:type=Memory_Verbose": false, - "heap_memory_usage_java.lang:type=Memory_HeapMemoryUsage_init": 134217728.0, - "heap_memory_usage_java.lang:type=Memory_HeapMemoryUsage_max": 1908932608.0, - "heap_memory_usage_java.lang:type=Memory_HeapMemoryUsage_used": 16840016.0, - "heap_memory_usage_java.lang:type=Memory_HeapMemoryUsage_committed": 173015040.0, - "heap_memory_usage_java.lang:type=Memory_NonHeapMemoryUsage_init": 2555904.0, - "heap_memory_usage_java.lang:type=Memory_NonHeapMemoryUsage_committed": 51380224.0, - "heap_memory_usage_java.lang:type=Memory_NonHeapMemoryUsage_max": -1.0, - "heap_memory_usage_java.lang:type=Memory_NonHeapMemoryUsage_used": 49944048.0, - "heap_memory_usage_java.lang:type=Memory_ObjectName_objectName": "java.lang:type=Memory", - } - - tags := map[string]string{ - "jolokia_host": "127.0.0.1", - "jolokia_port": "8080", - "jolokia_name": "as1", - } - acc.AssertContainsTaggedFields(t, "jolokia", fields, tags) -} - -// Test that the proper values are ignored or collected -func TestHttp404(t *testing.T) { - jolokia := genJolokiaClientStub(invalidJSON, 404, Servers, []Metric{UsedHeapMetric}) - - var acc testutil.Accumulator - acc.SetDebug(true) - err := acc.GatherError(jolokia.Gather) - - require.Error(t, err) - require.Empty(t, acc.Metrics) - require.Contains(t, err.Error(), "has status code 404") -} - -// Test that the proper values are ignored or collected -func TestHttpInvalidJson(t *testing.T) { - jolokia := genJolokiaClientStub(invalidJSON, 200, Servers, []Metric{UsedHeapMetric}) - - var acc testutil.Accumulator - acc.SetDebug(true) - err := acc.GatherError(jolokia.Gather) - - require.Error(t, err) - require.Empty(t, acc.Metrics) - require.Contains(t, err.Error(), "error decoding JSON response") -} diff --git a/plugins/inputs/jolokia/sample.conf b/plugins/inputs/jolokia/sample.conf deleted file mode 100644 index 3cb875ad6..000000000 --- a/plugins/inputs/jolokia/sample.conf +++ /dev/null @@ -1,54 +0,0 @@ -# Read JMX metrics through Jolokia -[[inputs.jolokia]] - ## This is the context root used to compose the jolokia url - ## NOTE that Jolokia requires a trailing slash at the end of the context root - context = "/jolokia/" - - ## This specifies the mode used - # mode = "proxy" - # - ## When in proxy mode this section is used to specify further - ## proxy address configurations. - ## Remember to change host address to fit your environment. - # [inputs.jolokia.proxy] - # host = "127.0.0.1" - # port = "8080" - - ## Optional http timeouts - ## - ## response_header_timeout, if non-zero, specifies the amount of time to wait - ## for a server's response headers after fully writing the request. - # response_header_timeout = "3s" - ## - ## client_timeout specifies a time limit for requests made by this client. - ## Includes connection time, any redirects, and reading the response body. - # client_timeout = "4s" - - ## List of servers exposing jolokia read service - [[inputs.jolokia.servers]] - name = "as-server-01" - host = "127.0.0.1" - port = "8080" - # username = "myuser" - # password = "mypassword" - - ## List of metrics collected on above servers - ## Each metric consists in a name, a jmx path and either - ## a pass or drop slice attribute. - ## This collect all heap memory usage metrics. - [[inputs.jolokia.metrics]] - name = "heap_memory_usage" - mbean = "java.lang:type=Memory" - attribute = "HeapMemoryUsage" - - ## This collect thread counts metrics. - [[inputs.jolokia.metrics]] - name = "thread_count" - mbean = "java.lang:type=Threading" - attribute = "TotalStartedThreadCount,ThreadCount,DaemonThreadCount,PeakThreadCount" - - ## This collect number of class loaded/unloaded counts metrics. - [[inputs.jolokia.metrics]] - name = "class_count" - mbean = "java.lang:type=ClassLoading" - attribute = "LoadedClassCount,UnloadedClassCount,TotalLoadedClassCount"