├── .github
└── workflows
│ └── main.yaml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── compose-example
├── Dockerfile
├── metrics-accumulator.yml
└── prometheus
│ └── prometheus.yml
├── compose.yaml
├── documentation
└── images
│ ├── Logo.png
│ └── logo.svg
├── libraries
└── prometheus-scraper-1.0.0.Final-cli.jar
├── metrics-accumulator.yml
├── pom.xml
└── src
├── main
├── java
│ └── io
│ │ └── bpoole6
│ │ └── accumulator
│ │ ├── MetricsConsumerApplication.java
│ │ ├── ScheduledTasks.java
│ │ ├── Task.java
│ │ ├── controller
│ │ ├── MetricsController.java
│ │ ├── MetricsControllerInterface.java
│ │ └── response
│ │ │ ├── ConfigurationResponse.java
│ │ │ └── ServiceDiscovery.java
│ │ ├── security
│ │ ├── ApiKeyAuthentication.java
│ │ ├── AuthenticationFilter.java
│ │ ├── AuthenticationService.java
│ │ └── CustomWebSecurityConfigurerAdapter.java
│ │ ├── service
│ │ ├── MetricKey.java
│ │ ├── MetricManager.java
│ │ ├── MetricService.java
│ │ ├── MetricValue.java
│ │ ├── MetricsAccumulatorConfiguration.java
│ │ ├── RegistryRepository.java
│ │ └── metricgroup
│ │ │ ├── Global.java
│ │ │ ├── Group.java
│ │ │ └── Root.java
│ │ └── util
│ │ ├── RunnableThrowable.java
│ │ └── Utils.java
└── resources
│ ├── application.yaml
│ ├── banner.txt
│ ├── static
│ └── blah.txt
│ └── templates
│ └── configuration.html
└── test
├── java
└── io
│ └── bpoole6
│ └── accumulator
│ ├── BasicTest.java
│ ├── MetricsConsumerApplicationTests.java
│ ├── ResetConfigurationTest.java
│ ├── TestControllers.java
│ └── TestUtils.java
└── resources
├── application.yaml
├── data
├── created_total
│ └── metrics
├── default
│ └── metrics
└── label_timestamp
│ ├── metrics-future
│ └── metrics-old
└── metric-groups.yml
/.github/workflows/main.yaml:
--------------------------------------------------------------------------------
1 | name: Deploy website
2 | on:
3 | push:
4 | branches:
5 | - main
6 | workflow_dispatch:
7 |
8 |
9 |
10 | jobs:
11 | buildAndDeploy:
12 | runs-on: ubuntu-latest
13 | permissions:
14 | contents: write
15 | steps:
16 | - name: Checkout Code
17 | uses: actions/checkout@v3
18 | with:
19 | ref: ${{ github.head_ref }} # checkout the correct branch name
20 | fetch-depth: 0 # fetch the whole repo history
21 | - uses: actions/cache@v4
22 | with:
23 | path: ~/.m2/repository
24 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
25 | restore-keys: |
26 | ${{ runner.os }}-maven-
27 | - name: build and test
28 | id: build_test
29 | run: |
30 | echo "previous_pom_version=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)" >> $GITHUB_OUTPUT
31 | JAVA_HOME=$JAVA_HOME_17_X64 && mvn clean \
32 | && mvn install build-helper:parse-version \
33 | versions:set -DnewVersion=\${parsedVersion.majorVersion}.\${parsedVersion.minorVersion}.\${parsedVersion.nextIncrementalVersion} -DgenerateBackupPoms=false
34 | echo "current_pom_version=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)" >> $GITHUB_OUTPUT
35 |
36 | - name: Login to Docker Hub
37 | uses: docker/login-action@v3
38 | with:
39 | username: bpoole6
40 | password: ${{ secrets.DOCKERHUB_TOKEN }}
41 | - name: Build Dockerfile
42 | run: |
43 | POM_VERSION=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)
44 | docker build -t bpoole6/metrics-accumulator:$POM_VERSION -t bpoole6/metrics-accumulator:latest .
45 | docker push bpoole6/metrics-accumulator --all-tags
46 | - name: Commit Message
47 | id: commit_message
48 | run: echo "commit_message=\"Updating version from ${{ steps.build_test.outputs.previous_pom_version }} to ${{ steps.build_test.outputs.current_pom_version }}\"" >> $GITHUB_OUTPUT
49 | - name: Commit Changes
50 | uses: stefanzweifel/git-auto-commit-action@v5
51 | with:
52 | commit_message: "AUTO-GENERATED: ${{steps.commit_message.outputs.commit_message}}"
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 | /.mvn/
35 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM openjdk:17-alpine
2 | COPY metrics-accumulator.yml /etc/metrics-accumulator/metrics-accumulator.yml
3 | COPY target/app.jar /
4 | ENTRYPOINT ["java","-jar","/app.jar"]
5 | CMD ["--config-file=/etc/metrics-accumulator/metrics-accumulator.yml"]
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | Metrics Accumulator
3 |
4 |
5 |
6 | * [Description](#description)
7 | * [Features](#features)
8 | * [Program Arguments](#program-arguments)
9 | * [API](#api)
10 | * [Getting Started](#getting-started)
11 | * [Docker](#docker)
12 | * [Locally](#locally)
13 | * [Supported Types](#supported-types)
14 | * [Counters](#counters)
15 | * [Gauges](#gauges)
16 | * [How to Utilize this service.](#how-to-utilize-this-service)
17 | * [Configurations](#configurations)
18 | * [Under Global](#under-global)
19 | * [Under MetricGroups](#under-metricgroups)
20 | * [Service Discovery](#service-discovery)
21 | * [How Does It Work?](#how-does-it-work)
22 | * [Metrics Accumulator Clients](#metrics-accumulator-clients)
23 | * [Python](#python)
24 | * [Nodejs](#nodejs)
25 |
26 |
27 | ## Description
28 | The metric accumulator will accumulate additively time-series metrics for ephemeral jobs such as.
29 |
30 | - GCP CloudRun
31 | - GCP Functions
32 | - AWS Lambdas
33 | - Kubernetes Jobs
34 | - Cron Jobs running somewhere
35 | - ETC
36 |
37 | This is an alternative to Prometheus Pushgateway for when you need persistent data on "subsequent" metric pushes.
38 |
39 | ## Features
40 | - Aggregates metrics
41 | - Has TTL for metrics
42 | - Hot reload configurations
43 |
44 | ## Program Arguments
45 | |Argument| Description | Example | Required |
46 | | --- |--------------------------------|-------------------------------------------------------------|----------|
47 | |--config-file | path to the configuration file | /metrics-accumulator.jar --config-file=/path/to/configs.yml | yes |
48 |
49 | ## API
50 | | Api Endpoint | Method | Required Headers | Description |
51 | |-----------------------------------|--------|------------------|--------------------------------------------------------------------------------------------------------------------------------------|
52 | | /reset-metric-group/{metricGroup} | PUT | N/A | Erases the metric group metrics out of memory. |
53 | | /reload-configuration | PUT | N/A | Reloads configuration that were passed in via --config-file. The File source will be reread from storage. All Metrics will be erased |
54 | | /update/{metricGroup} | POST | X-API-KEY | Updates metric group metrics. |
55 | | /service-discovery | GET | N/A | A service discovery mechanism for prometheus Please see documentation https://prometheus.io/docs/prometheus/latest/http_sd/ |
56 | | /metrics/{metricGroup} | GET | N/A | Returns the metrics for a metrics group. |
57 | | /current-configurations | GET | N/A | Displays the current loaded configurations |
58 | | /swagger-ui/index.html#/ | GET | N/A | Swagger Endpoint |
59 |
60 | ## Getting Started
61 |
62 | ### Docker
63 | Start docker container
64 | ```bash
65 | docker run \
66 | -p 8080:8080 \
67 | bpoole6/metrics-accumulator
68 | ```
69 | ### Locally
70 |
71 | **Build the project**
72 | ```bash
73 | mvn clean package -DskipTests=true
74 | ```
75 |
76 | **Start The Application**
77 | ```bash
78 | java -jar target/app.jar --config-file ./metrics-accumulator.yml
79 | ```
80 |
81 | Navigate to http://localhost:8080
82 |
83 | **Pushing Data**
84 |
85 | run the following command twice
86 | ```bash
87 | curl -X 'POST' \
88 | 'http://localhost:8080/update/default' \
89 | -H 'accept: */*' \
90 | -H 'X-API-KEY: 0d98f65f-074b-4d56-b834-576e15a3bfa5' \
91 | -H 'Content-Type: text/plain' \
92 | -d '# TYPE test_total counter
93 | # HELP test_total
94 | test_total {span_id="321",trace_id="123"} 5.0'
95 | ```
96 |
97 | Then get the metric data
98 | ```bash
99 | curl -X 'GET' \
100 | 'http://localhost:8080/metrics/default' \
101 | -H 'accept: text/plain'
102 | ```
103 |
104 | You should receive this
105 | ```text
106 | # TYPE test_total counter
107 | test_total{span_id="321",trace_id="123"} 10.0
108 | ```
109 |
110 | You'll notice that `test_total` has a value of 10
111 |
112 | **Swagger**
113 |
114 | You can run this example at the swagger endpoint http://localhost:8080/swagger-ui/index.html#/
115 | ## Supported Types
116 |
117 | ### Counters
118 | Counters will be combined additively
119 |
120 |
121 | ### Gauges
122 | Gauges are a special case. When a new gauge value comes then the last guage value to be added will be preserved. To change this behavior you can set the label `_metrics_accumulator_latest` with the value of a number such as the epoch time. Subsequent pushes on the same gauge will compare the vlaue of `_metrics_accumulator_latest` and largest number will be persisted.
123 |
124 | `_metrics_accumulator_latest` is not displayed when scraping.
125 |
126 |
127 |
128 | ## How to Utilize this service.
129 | In the [metric-groups.yml](src%2Fmain%2Fresources%2Fprod%2Fmetric-groups.yml) file add your metric group
130 |
131 | For example
132 | ```yaml
133 | global:
134 | restartCronExpression: "0 0 0 ? * *"
135 | hostAddress: localhost:8080
136 |
137 | metricGroups:
138 | default:
139 | displayMetrics: true
140 | name: default
141 | maxTimeSeries: 2500
142 | apiKey: 0d98f65f-074b-4d56-b834-576e15a3bfa5
143 | restartCronExpression: "0 0 0 ? * *"
144 | serviceDiscoveryLabels:
145 | env: qa
146 | version: v31
147 | metricGroup1:
148 | displayMetrics: true
149 | name: metric-group
150 | maxTimeSeries: 100
151 | apiKey: 0d98f65f-074b-4d56-b834-576e15a3bfa5
152 | restartCronExpression: "0 0 0 ? * *"
153 | serviceDiscoveryLabels:
154 | env: test
155 | version: v45
156 | ```
157 | ### Configurations
158 |
159 | #### Under Global
160 |
161 | **restartCronExpression**
162 |
163 | | Attributes | Description |
164 | |-----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|
165 | | restartCronExpression | Used to set when your metrics are wiped from memory. This is useful getting rid of stale data. Ideally your data should be wiped at least once a week or more. |
166 | | hostAddress | This is the address of the metrics accumulator used for service discovery. For example, you might set up in DNS an A record pointing to the ip address of the instance running this service such as `metrics-accumulator.internal.com`. |
167 |
168 |
169 |
170 | #### Under MetricGroups
171 |
172 | | Attributes | Description |
173 | |-----------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
174 | | displayMetrics | Determines if prometheus should read your metrics or not. |
175 | | name | The name of the endpoint you'll push your metrics to. For example if the `name` was *super-app* then the endpoint you'd need to POST your prometheus metrics is: `http://prometheus-metrics-accumulator.internal.q6cyber.com/update/super-app` |
176 | | maxTimeSeries | The maximum number of timeseries you can have in memory for your service. To deal with stale time series we have the *restartCronExpression* your metrics from history. |
177 | | apiKey | The apikey must be passed in the header `X-API-KEY` when you POST your metrics. This helps to prevent an accidental POST to another metric Group or another environment such as prod/dev/qa. |
178 | | restartCronExpression | Used to set when your metrics are wiped from memory. This is useful getting rid of stale data. Ideally your data should be wiped at least once a week or more. |
179 | | serviceDiscoveryLabels | Additional labels to be added when scraping the serviceDiscovery endpoint. This is useful during the relabeling |
180 |
181 |
182 | ## Service Discovery
183 |
184 | There's an example of service discovery via docker compose. In the root directory of the project.
185 |
186 | ```bash
187 | mvn clean install -DskipTests=true
188 | docker compose up --build --force-recreate
189 | ```
190 |
191 | Then navigate to http://localhost:9090/targets?search= and make sure your applicationis being scraped. Follow the example [Getting Started](#getting-started)/pushing data to see metrics being consumed
192 | ### How Does It Work?
193 |
194 |
195 | The endpoint `/service-discovery` returns a json structure that prometheus uses for [service discovery](https://prometheus.io/docs/prometheus/latest/http_sd/)
196 |
197 | ```json
198 | [
199 | {
200 | "targets": [ ""],
201 | "labels": {
202 | "__meta_metrics_path": "metrics/"
203 | }
204 | },
205 | ...
206 | ]
207 | ```
208 |
209 | In the Prometheus config you'll need to setup a scrape config for service discovery
210 |
211 | ```yaml
212 | scrape_configs:
213 | # The job name is added as a label `job=` to any time-series scraped from this config.
214 | - job_name: "metrics-accumulator"
215 | scrape_interval: 5s
216 | relabel_configs:
217 | - source_labels: ["__meta_metrics_path"]
218 | target_label: "__metrics_path__"
219 | http_sd_configs:
220 | - url: "http://localhost:8080/service-discovery"
221 | ```
222 |
223 | Prometheus will query the service discovery endpoint `http://localhost:8080/service-discovery` and relabel will replace the metrics path with `/metrics/`. A target is created for every metric as defined in your configuration file
224 |
225 | ## Metrics Accumulator Clients
226 |
227 | There's full client support
228 | - [python](https://pypi.org/project/metrics-accumulator-client/)
229 | - [nodejs](https://www.npmjs.com/package/metrics-accumulator-client)
230 |
231 | There is a java example of a client found here
232 | - https://github.com/bpoole6/metrics-accumulator-clients/tree/main/java-client
233 | ### Python
234 |
235 | **Installation**
236 | ```bash
237 | python -m pip install metrics-accumulator-client
238 | ```
239 |
240 | Example
241 | ```python
242 | from Client import Client
243 | from prometheus_client import Counter,Gauge, CollectorRegistry, metrics
244 | metrics.disable_created_metrics() #*****Important****** If you don't set this then metrics accumulator will Amber Heard the bed
245 | registry = CollectorRegistry()
246 | c = Counter("hello_total", "dock", labelnames=['application'], registry=registry)
247 | c.labels(["app"]).inc()
248 |
249 | g = Gauge("man", "dock", labelnames=['application'], registry=registry)
250 | g.labels(["app"]).inc()
251 |
252 | client = Client("http://localhost:8080", "0d98f65f-074b-4d56-b834-576e15a3bfa5")
253 | client.update_metrics("default", registry)
254 | print(client.get_metric_group("default").content.decode())
255 | print(client.reload_configurations().status_code)
256 | print(client.reset_metric_group("default").status_code)
257 | print(client.service_discovery().status_code)
258 | print(client.current_configurations().status_code)
259 | ```
260 |
261 | ### Nodejs
262 |
263 | **Installation**
264 | ```bash
265 | npm install metrics-accumulator-client
266 | ```
267 |
268 | Example
269 |
270 | ```node
271 | import {Registry, Counter} from "prom-client"
272 |
273 | const registry = new Registry()
274 | new Counter({
275 | name : "counter_example_total",
276 | help: "help",
277 | registers: [registry]
278 | })
279 |
280 | let client = new Client("http://localhost:8080", "0d98f65f-074b-4d56-b834-576e15a3bfa5")
281 | client.updateMetrics('default', registry).then(res=> console.log(res.statusCode + " " + res.content))
282 | client.getMetricGroup('default').then(res=> console.log(res.statusCode + " " + res.content))
283 | client.reloadConfigurations().then(res=> console.log(res.statusCode + " " + res.content))
284 | client.resetMetricGroup("default").then(res=> console.log(res.statusCode + " " + res.content))
285 | client.serviceDiscovery().then(res=> console.log(res.statusCode + " " + res.content))
286 | client.currentConfigurations().then(res=> console.log(res.statusCode + " " + res.content))
287 | ```
--------------------------------------------------------------------------------
/compose-example/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM openjdk:17-alpine
2 | COPY compose-example/metrics-accumulator.yml /etc/metrics-accumulator/metrics-accumulator.yml
3 | COPY target/app.jar /
4 | ENTRYPOINT ["java","-jar","/app.jar"]
5 | CMD ["--config-file=/etc/metrics-accumulator/metrics-accumulator.yml"]
--------------------------------------------------------------------------------
/compose-example/metrics-accumulator.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | global:
4 | restartCronExpression: "0 0 0 ? * *"
5 | hostAddress: metrics-accumulator:8080
6 |
7 | metricGroups:
8 | default:
9 | displayMetrics: true
10 | name: default
11 | maxTimeSeries: 2500
12 | apiKey: 0d98f65f-074b-4d56-b834-576e15a3bfa5
13 | restartCronExpression: "0 0 0 ? * *"
14 | serviceDiscoveryLabels:
15 | env: test
16 | job_name: default
17 | tps-report-lambda-function:
18 | displayMetrics: true
19 | name: tps-report
20 | maxTimeSeries: 2500
21 | apiKey: n6985y5f-074b-4d96-y834-976e15a3bfBm
22 | restartCronExpression: "0 0 0 ? * *"
23 | serviceDiscoveryLabels:
24 | env: accounting-prod
25 | job_name: accounting-tps
--------------------------------------------------------------------------------
/compose-example/prometheus/prometheus.yml:
--------------------------------------------------------------------------------
1 | # my global config
2 | global:
3 | scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
4 | evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
5 | # scrape_timeout is set to the global default (10s).
6 |
7 | # Alertmanager configuration
8 | alerting:
9 | alertmanagers:
10 | - static_configs:
11 | - targets:
12 | # - alertmanager:9093
13 |
14 | # Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
15 | rule_files:
16 | # - "first_rules.yml"
17 | # - "second_rules.yml"
18 |
19 | # A scrape configuration containing exactly one endpoint to scrape:
20 | # Here it's Prometheus itself.
21 | scrape_configs:
22 | # The job name is added as a label `job=` to any time-series scraped from this config.
23 | - job_name: "metrics-accumulator"
24 | scrape_interval: 5s
25 | relabel_configs:
26 | - source_labels: ["__meta_metrics_path"]
27 | target_label: "__metrics_path__"
28 | - source_labels: ["job_name"]
29 | target_label: "job"
30 | http_sd_configs:
31 | - url: "http://metrics-accumulator:8080/service-discovery"
32 |
--------------------------------------------------------------------------------
/compose.yaml:
--------------------------------------------------------------------------------
1 | services:
2 | web:
3 | container_name: metrics-accumulator
4 | build:
5 | dockerfile: compose-example/Dockerfile
6 | ports:
7 | - "8080:8080"
8 | environment:
9 | PORT: 8080
10 | networks:
11 | - private-network
12 | healthcheck:
13 | test: [ "CMD", "wget", "-O", "-", "http://localhost:8080" ]
14 | interval: 20s
15 | timeout: 2s
16 | retries: 5
17 |
18 | prometheus:
19 | container_name: prometheus-server
20 | image: "prom/prometheus:v2.52.0"
21 | ports:
22 | - "9090:9090"
23 | command:
24 | - "--config.file=/etc/prometheus/prometheus.yml"
25 | - "--storage.tsdb.path=/prometheus"
26 | volumes:
27 | - prometheus:/etc/prometheus
28 | networks:
29 | - private-network
30 | depends_on:
31 | web:
32 | condition: service_healthy
33 | volumes:
34 | prometheus:
35 | driver: local
36 | driver_opts:
37 | o: bind
38 | type: none
39 | device: ./compose-example/prometheus
40 | networks:
41 | private-network:
42 | driver: bridge
43 |
44 |
--------------------------------------------------------------------------------
/documentation/images/Logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bpoole6/metrics-accumulator/3f5f7f121ba0e97ec4cebda607b0e45e1ee8c977/documentation/images/Logo.png
--------------------------------------------------------------------------------
/libraries/prometheus-scraper-1.0.0.Final-cli.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bpoole6/metrics-accumulator/3f5f7f121ba0e97ec4cebda607b0e45e1ee8c977/libraries/prometheus-scraper-1.0.0.Final-cli.jar
--------------------------------------------------------------------------------
/metrics-accumulator.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | global:
4 | restartCronExpression: "0 0 0 ? * *"
5 | hostAddress: localhost:8080
6 |
7 | metricGroups:
8 | default:
9 | displayMetrics: true
10 | name: default
11 | maxTimeSeries: 2500
12 | apiKey: 0d98f65f-074b-4d56-b834-576e15a3bfa5
13 | restartCronExpression: "0 0 0 ? * *"
14 | serviceDiscoveryLabels:
15 | env: "dev"
16 | version: "2.3"
17 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.3.3
9 |
10 |
11 | io.bpoole6
12 | metrics-accumulator
13 | 1.3.2
14 | metrics-accumulator
15 | Aggregate metrics for ephemeral jobs
16 |
17 | 17
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-web
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-actuator
27 |
28 |
29 | io.micrometer
30 | micrometer-registry-prometheus
31 | 1.13.2
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | org.projectlombok
45 | lombok
46 | true
47 |
48 |
49 | org.apache.commons
50 | commons-lang3
51 | 3.15.0
52 |
53 |
54 | org.springframework.boot
55 | spring-boot-starter-security
56 |
57 |
58 |
59 | org.springdoc
60 | springdoc-openapi-starter-webmvc-ui
61 | 2.0.2
62 |
63 |
64 | org.springframework.boot
65 | spring-boot-starter-thymeleaf
66 |
67 |
68 | org.springframework.boot
69 | spring-boot-starter-test
70 | test
71 |
72 |
73 | org.github.jmazzitelli
74 | prometheus-scraper
75 | 1.0.0.Final
76 |
77 |
78 |
79 |
80 | app
81 |
82 |
83 | org.springframework.boot
84 | spring-boot-maven-plugin
85 |
86 |
87 | org.apache.maven.plugins
88 | maven-install-plugin
89 | 3.1.2
90 |
91 |
92 | clean
93 |
94 |
95 | install-file
96 |
97 |
98 |
99 |
100 |
101 | ${project.basedir}/libraries/prometheus-scraper-1.0.0.Final-cli.jar
102 | org.github.jmazzitelli
103 | prometheus-scraper
104 | 1.0.0.Final
105 | jar
106 |
107 |
108 |
109 |
110 |
111 |
--------------------------------------------------------------------------------
/src/main/java/io/bpoole6/accumulator/MetricsConsumerApplication.java:
--------------------------------------------------------------------------------
1 | package io.bpoole6.accumulator;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
6 | import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
7 | import org.springframework.scheduling.annotation.EnableScheduling;
8 |
9 | @SpringBootApplication(exclude = {SecurityAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class})
10 | @EnableScheduling
11 | public class MetricsConsumerApplication {
12 |
13 | public static void main(String[] args) {
14 | SpringApplication.run(MetricsConsumerApplication.class, args);
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/io/bpoole6/accumulator/ScheduledTasks.java:
--------------------------------------------------------------------------------
1 | package io.bpoole6.accumulator;
2 |
3 | import io.bpoole6.accumulator.service.RegistryRepository;
4 | import io.bpoole6.accumulator.service.MetricsAccumulatorConfiguration;
5 | import lombok.Getter;
6 | import lombok.extern.slf4j.Slf4j;
7 | import org.springframework.beans.factory.annotation.Qualifier;
8 | import org.springframework.scheduling.TaskScheduler;
9 | import org.springframework.scheduling.support.CronTrigger;
10 | import org.springframework.stereotype.Component;
11 |
12 | import java.util.ArrayList;
13 | import java.util.Collections;
14 | import java.util.List;
15 | import java.util.concurrent.ScheduledFuture;
16 |
17 | @Component
18 | @Slf4j
19 | public class ScheduledTasks {
20 |
21 | private final TaskScheduler executor;
22 | private final RegistryRepository metrics;
23 | private final MetricsAccumulatorConfiguration metricsAccumulatorConfiguration;
24 |
25 | private final List tasks = new ArrayList<>();
26 |
27 | public ScheduledTasks(@Qualifier("taskScheduler") TaskScheduler taskExecutor,
28 | RegistryRepository metrics,
29 | MetricsAccumulatorConfiguration metricsAccumulatorConfiguration) {
30 | this.executor = taskExecutor;
31 | this.metrics = metrics;
32 | this.metricsAccumulatorConfiguration = metricsAccumulatorConfiguration;
33 | reset();
34 | }
35 |
36 | public void scheduling(String name, final Runnable task, String cronExpression) {
37 | CronTrigger trigger = new CronTrigger(cronExpression);
38 |
39 | ScheduledFuture> f = executor.schedule(task,trigger );
40 | Task t= new Task(name, trigger, f);
41 | tasks.add(t);
42 | }
43 |
44 | public void reset(){
45 | for (int i = 0; i < tasks.size(); i++) {
46 | try{
47 | tasks.get(i).getFuture().cancel(true);
48 | }catch (Exception e){
49 | log.error("Failed to cancel %s".formatted(tasks.get(i).getName()));
50 | }
51 | }
52 | tasks.clear();
53 | metrics.getRegistryMap().forEach((group, metricManager) -> {
54 | String restartCronExpression = group.getRestartCronExpression();
55 | if(restartCronExpression == null) {
56 | restartCronExpression = metricsAccumulatorConfiguration.getGlobal().getRestartCronExpression();
57 | }
58 | scheduling(group.getName(), () -> {
59 | try {
60 | metricManager.resetRegistries();
61 | } catch (Exception e) {
62 | log.error(e.getMessage(), e);
63 | }
64 | }, restartCronExpression);
65 | });
66 | }
67 |
68 | public List getTasks() {
69 | return new ArrayList<>(tasks);
70 | }
71 | }
--------------------------------------------------------------------------------
/src/main/java/io/bpoole6/accumulator/Task.java:
--------------------------------------------------------------------------------
1 | package io.bpoole6.accumulator;
2 |
3 | import lombok.Data;
4 | import org.springframework.scheduling.support.CronTrigger;
5 |
6 | import java.util.concurrent.ScheduledFuture;
7 |
8 | @Data
9 | public class Task {
10 | private final String name;
11 | private final CronTrigger cronTrigger;
12 | private final ScheduledFuture> future;
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/io/bpoole6/accumulator/controller/MetricsController.java:
--------------------------------------------------------------------------------
1 | package io.bpoole6.accumulator.controller;
2 |
3 | import io.bpoole6.accumulator.controller.response.ConfigurationResponse;
4 | import io.bpoole6.accumulator.controller.response.ServiceDiscovery;
5 | import io.bpoole6.accumulator.service.MetricService;
6 | import io.bpoole6.accumulator.service.metricgroup.Group;
7 | import io.bpoole6.accumulator.service.MetricsAccumulatorConfiguration;
8 |
9 | import java.io.IOException;
10 | import java.util.List;
11 | import java.util.Objects;
12 | import java.util.Optional;
13 |
14 | import org.springframework.http.HttpStatus;
15 | import org.springframework.http.ResponseEntity;
16 | import org.springframework.security.core.context.SecurityContextHolder;
17 | import org.springframework.ui.ModelMap;
18 | import org.springframework.web.bind.annotation.*;
19 | import org.springframework.web.servlet.ModelAndView;
20 |
21 | @RestController
22 | @RequestMapping("/")
23 | public class MetricsController implements MetricsControllerInterface{
24 |
25 | private MetricService metricService;
26 | private final MetricsAccumulatorConfiguration metricsAccumulatorConfiguration;
27 | public MetricsController(MetricService metricService,
28 | MetricsAccumulatorConfiguration metricsAccumulatorConfiguration) {
29 | this.metricService = metricService;
30 | this.metricsAccumulatorConfiguration = metricsAccumulatorConfiguration;
31 | }
32 |
33 |
34 | @Override
35 | public ModelAndView serverStatus(ModelMap map) {
36 | ConfigurationResponse response = new ConfigurationResponse();
37 | response.setConfiguration("\n"+this.metricsAccumulatorConfiguration.getFileContent());
38 | response.setConfigurationFile(this.metricsAccumulatorConfiguration.getConfigurationFile());
39 | map.addAttribute("config", response);
40 | return new ModelAndView("configuration", map);
41 | }
42 | @Override
43 | public ResponseEntity