├── .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
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 reloadConfig() throws InterruptedException { 44 | boolean reset = this.metricService.resetConfigs(); 45 | if(reset) { 46 | return new ResponseEntity<>("configurations has been reloaded", HttpStatus.OK); 47 | }else { 48 | return new ResponseEntity<>("Failed to reload configuration", HttpStatus.EXPECTATION_FAILED); 49 | } 50 | } 51 | 52 | 53 | public ResponseEntity resetMetricGroup(@PathVariable("metricGroup") String metricGroup) throws InterruptedException { 54 | Group group = this.metricsAccumulatorConfiguration.getMetricGroups().get(metricGroup); 55 | 56 | if( metricService.resetMetricGroup(group)) { 57 | return new ResponseEntity<>("Metrics reset for %s".formatted(metricGroup), HttpStatus.OK); 58 | }else { 59 | return new ResponseEntity<>("Failed to reset metrics for %s".formatted(metricGroup), HttpStatus.EXPECTATION_FAILED); 60 | } 61 | } 62 | 63 | 64 | 65 | public ResponseEntity updateMetrics(@PathVariable("metricGroup") String metricGroup, @RequestBody String metrics) 66 | throws IOException, InterruptedException { 67 | Optional contextMetricGroup = getMetricGroupFromSecurityContext(); 68 | Group group = this.metricsAccumulatorConfiguration.getMetricGroups().get(metricGroup); 69 | 70 | if (Objects.nonNull(group)) { 71 | if(contextMetricGroup.isPresent() && !group.equals(contextMetricGroup.get())) { 72 | return new ResponseEntity<>("Wrong api key for metric group: " + metricGroup,HttpStatus.UNAUTHORIZED); 73 | } 74 | 75 | this.metricService.modifyMetrics(metrics, group); 76 | return new ResponseEntity<>(HttpStatus.CREATED); 77 | } 78 | return new ResponseEntity<>(HttpStatus.NOT_FOUND); 79 | } 80 | 81 | 82 | public ResponseEntity metrics(@PathVariable("metricGroup") String metricName) { 83 | Group group = this.metricsAccumulatorConfiguration.getMetricGroups().get(metricName); 84 | if (Objects.isNull(group)) { 85 | return new ResponseEntity<>(HttpStatus.NOT_FOUND); 86 | } 87 | 88 | Optional optSnapshot = metricService.getMetricSnapshot(group); 89 | if (optSnapshot.isPresent()) { 90 | return new ResponseEntity<>(optSnapshot.get(), HttpStatus.OK); 91 | }else{ 92 | return new ResponseEntity<>(HttpStatus.NOT_FOUND); 93 | } 94 | } 95 | 96 | public ResponseEntity> serviceDiscovery() { 97 | List list = this.metricsAccumulatorConfiguration.getMetricGroups().values().stream() 98 | .filter(Group::isDisplayMetrics) 99 | .map(i-> new ServiceDiscovery("metrics/" + i.getName(), metricsAccumulatorConfiguration.getHostAddress(), i.getServiceDiscoveryLabels())).toList(); 100 | 101 | return new ResponseEntity<>(list, HttpStatus.OK); 102 | } 103 | 104 | 105 | public ResponseEntity currentConfigurations(){ 106 | ConfigurationResponse response = new ConfigurationResponse(); 107 | response.setConfiguration(this.metricsAccumulatorConfiguration.getFileContent()); 108 | response.setConfigurationFile(this.metricsAccumulatorConfiguration.getConfigurationFile()); 109 | return new ResponseEntity<>(response,HttpStatus.OK); 110 | } 111 | 112 | public Optional getMetricGroupFromSecurityContext() { 113 | if(SecurityContextHolder.getContext().getAuthentication().getCredentials() instanceof Group){ 114 | return Optional.of((Group) SecurityContextHolder.getContext().getAuthentication().getCredentials()); 115 | } 116 | return Optional.empty(); 117 | } 118 | 119 | 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/controller/MetricsControllerInterface.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.metricgroup.Group; 6 | import io.swagger.v3.oas.annotations.Operation; 7 | import io.swagger.v3.oas.annotations.Parameter; 8 | import io.swagger.v3.oas.annotations.enums.ParameterIn; 9 | import io.swagger.v3.oas.annotations.responses.ApiResponse; 10 | import io.swagger.v3.oas.annotations.responses.ApiResponses; 11 | import org.springframework.http.ResponseEntity; 12 | import org.springframework.ui.ModelMap; 13 | import org.springframework.web.bind.annotation.*; 14 | import org.springframework.web.servlet.ModelAndView; 15 | 16 | import java.io.IOException; 17 | import java.util.List; 18 | import java.util.Optional; 19 | 20 | 21 | 22 | interface MetricsControllerInterface { 23 | 24 | 25 | @GetMapping("/") 26 | public ModelAndView serverStatus(ModelMap map); 27 | @Operation( 28 | summary = "Reloaded the loaded configuration. All Metrics will be erased", 29 | description = "Reloads configuration that were passed in via --config-file. The File source will be reread from storage. All Metrics will be erased") 30 | @ApiResponses(value = { 31 | @ApiResponse(responseCode = "200", description = "succeeded to reload configurations"), 32 | @ApiResponse(responseCode = "417", description = "failed to reload configurations") 33 | }) 34 | 35 | @PutMapping(value = "reload-configuration") 36 | ResponseEntity reloadConfig() throws InterruptedException; 37 | 38 | @Operation( 39 | summary = "Erases the metric group metrics out of memory.", 40 | description = "Erases the metric group metrics out of memory.", 41 | parameters = { 42 | @Parameter(name = "metricGroup", required = true, in = ParameterIn.PATH,description = "The name of your metric group",example = "default") 43 | } 44 | ) 45 | @ApiResponses(value = { 46 | @ApiResponse(responseCode = "200", description = "succeeded to erase metrics for metric group"), 47 | @ApiResponse(responseCode = "417", description = "failed to erase metrics for metric group") 48 | }) 49 | @PutMapping(value = "reset-metric-group/{metricGroup}") 50 | ResponseEntity resetMetricGroup(@PathVariable("metricGroup") String metricGroup) throws InterruptedException; 51 | 52 | 53 | @Operation( 54 | summary = "Updates metric group metrics.", 55 | description = "Updates metric group metrics.", 56 | parameters = { 57 | @Parameter(name = "X-API-KEY", required = true, in = ParameterIn.HEADER, example = "0d98f65f-074b-4d56-b834-576e15a3bfa5"), 58 | @Parameter(name = "metricGroup", required = true, in = ParameterIn.PATH,description = "The name of your metric group",example = "default") 59 | }) 60 | @ApiResponses(value = { 61 | @ApiResponse(responseCode = "201", description = "Succeeded to update the configurations"), 62 | @ApiResponse(responseCode = "404", description = "Metric group doesn't exist"), 63 | @ApiResponse(responseCode = "401", description = "You authenticated but apiKey doesn't correspond to metric Group supplied"), 64 | }) 65 | @PostMapping(value = "update/{metricGroup}", consumes = {"text/plain"}) 66 | ResponseEntity updateMetrics(@PathVariable("metricGroup") String metricGroup, @RequestBody String metrics) 67 | throws IOException, InterruptedException; 68 | 69 | @Operation( 70 | summary = "Returns the metrics for a metrics group.", 71 | description = "Returns the metrics for a metrics group.", 72 | parameters = { 73 | @Parameter(name = "metricGroup", required = true, in = ParameterIn.PATH, example = "default") 74 | }) 75 | @ApiResponses(value = { 76 | @ApiResponse(responseCode = "200", description = "Succeeded to get metric group's metrics"), 77 | @ApiResponse(responseCode = "404", description = "Metric group doesn't exist"), 78 | }) 79 | @GetMapping(value = "metrics/{metricGroup}", produces = {"text/plain"}) 80 | ResponseEntity metrics(@PathVariable("metricGroup") String metricName); 81 | 82 | @Operation( 83 | summary = "A service discovery mechanism for prometheus", 84 | description = "A service discovery mechanism for prometheus\nPlease see documentation https://prometheus.io/docs/prometheus/latest/http_sd/") 85 | @ApiResponses(value = { 86 | @ApiResponse(responseCode = "200", description = "Returns service discovery successfully"), 87 | }) 88 | @GetMapping(value = "service-discovery", produces = "application/json") 89 | ResponseEntity> serviceDiscovery(); 90 | 91 | @Operation( 92 | summary = "The current configurations loaded", 93 | description = "Copy string literal text to the clipboard") 94 | @ApiResponses(value = { 95 | @ApiResponse(responseCode = "200"), 96 | }) 97 | @GetMapping(value = "current-configurations") 98 | ResponseEntity currentConfigurations(); 99 | 100 | Optional getMetricGroupFromSecurityContext(); 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/controller/response/ConfigurationResponse.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.controller.response; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class ConfigurationResponse { 7 | private String configuration; 8 | private String configurationFile; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/controller/response/ServiceDiscovery.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.controller.response; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | import lombok.Data; 8 | 9 | @Data 10 | public class ServiceDiscovery { 11 | 12 | private List targets; 13 | private Map labels; 14 | public ServiceDiscovery(String metricGroupName, String target, Map serviceDiscoveryLabels) { 15 | labels = new HashMap<>(serviceDiscoveryLabels); 16 | targets = new ArrayList<>(); 17 | targets.add(target); 18 | labels.put("__meta_metrics_path", metricGroupName); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/security/ApiKeyAuthentication.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.security; 2 | 3 | import io.bpoole6.accumulator.service.metricgroup.Group; 4 | import java.util.Collection; 5 | import java.util.Objects; 6 | import org.springframework.security.authentication.AbstractAuthenticationToken; 7 | import org.springframework.security.core.GrantedAuthority; 8 | 9 | public class ApiKeyAuthentication extends AbstractAuthenticationToken { 10 | private final String apiKey; 11 | private final Group metricGroup; 12 | public ApiKeyAuthentication(String apiKey, Group metricGroup, Collection authorities) { 13 | super(authorities); 14 | this.apiKey = apiKey; 15 | this.metricGroup = metricGroup; 16 | 17 | setAuthenticated(Objects.nonNull(metricGroup)); 18 | } 19 | 20 | @Override 21 | public Object getCredentials() { 22 | return metricGroup; 23 | } 24 | 25 | @Override 26 | public Object getPrincipal() { 27 | return apiKey; 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/security/AuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.security; 2 | 3 | import io.bpoole6.accumulator.service.MetricsAccumulatorConfiguration; 4 | import jakarta.servlet.FilterChain; 5 | import jakarta.servlet.ServletException; 6 | import jakarta.servlet.ServletRequest; 7 | import jakarta.servlet.ServletResponse; 8 | import jakarta.servlet.http.HttpServletRequest; 9 | import jakarta.servlet.http.HttpServletResponse; 10 | import java.io.IOException; 11 | import java.io.PrintWriter; 12 | import org.springframework.http.MediaType; 13 | import org.springframework.security.core.Authentication; 14 | import org.springframework.security.core.context.SecurityContextHolder; 15 | import org.springframework.web.filter.GenericFilterBean; 16 | 17 | public class AuthenticationFilter extends GenericFilterBean { 18 | 19 | private final MetricsAccumulatorConfiguration metricsAccumulatorConfiguration; 20 | 21 | public AuthenticationFilter(MetricsAccumulatorConfiguration metricsAccumulatorConfiguration) { 22 | 23 | this.metricsAccumulatorConfiguration = metricsAccumulatorConfiguration; 24 | } 25 | @Override 26 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) 27 | throws IOException, ServletException { 28 | try { 29 | Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request, metricsAccumulatorConfiguration); 30 | SecurityContextHolder.getContext().setAuthentication(authentication); 31 | } catch (Exception exp) { 32 | HttpServletResponse httpResponse = (HttpServletResponse) response; 33 | httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 34 | httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); 35 | PrintWriter writer = httpResponse.getWriter(); 36 | writer.print(exp.getMessage()); 37 | writer.flush(); 38 | writer.close(); 39 | } 40 | 41 | filterChain.doFilter(request, response); 42 | } 43 | 44 | 45 | } -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/security/AuthenticationService.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.security; 2 | 3 | import io.bpoole6.accumulator.service.metricgroup.Group; 4 | import io.bpoole6.accumulator.service.MetricsAccumulatorConfiguration; 5 | import jakarta.servlet.http.HttpServletRequest; 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.core.authority.AuthorityUtils; 8 | 9 | public class AuthenticationService { 10 | 11 | private static final String AUTH_TOKEN_HEADER_NAME = "X-API-KEY"; 12 | public static Authentication getAuthentication(HttpServletRequest request, 13 | MetricsAccumulatorConfiguration metricsAccumulatorConfiguration) { 14 | String apiKey = request.getHeader(AUTH_TOKEN_HEADER_NAME); 15 | Group group = metricsAccumulatorConfiguration.getMetricGroupByApiKey().get(apiKey); 16 | return new ApiKeyAuthentication(apiKey, group, AuthorityUtils.NO_AUTHORITIES); 17 | } 18 | 19 | 20 | } -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/security/CustomWebSecurityConfigurerAdapter.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.security; 2 | 3 | import io.bpoole6.accumulator.service.MetricsAccumulatorConfiguration; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.http.HttpMethod; 7 | import org.springframework.security.config.Customizer; 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 10 | import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; 11 | import org.springframework.security.config.http.SessionCreationPolicy; 12 | import org.springframework.security.web.SecurityFilterChain; 13 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 14 | 15 | @Configuration 16 | @EnableWebSecurity 17 | public class CustomWebSecurityConfigurerAdapter { 18 | private final MetricsAccumulatorConfiguration metricsAccumulatorConfiguration; 19 | 20 | public CustomWebSecurityConfigurerAdapter(MetricsAccumulatorConfiguration metricsAccumulatorConfiguration) { 21 | this.metricsAccumulatorConfiguration = metricsAccumulatorConfiguration; 22 | } 23 | 24 | @Bean 25 | public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { 26 | http.csrf(AbstractHttpConfigurer::disable) 27 | 28 | .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> 29 | authorizationManagerRequestMatcherRegistry 30 | .requestMatchers(HttpMethod.POST).authenticated() 31 | .anyRequest().permitAll()) 32 | 33 | .httpBasic(Customizer.withDefaults()) 34 | .sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy( 35 | SessionCreationPolicy.STATELESS)) 36 | .addFilterBefore(new AuthenticationFilter(this.metricsAccumulatorConfiguration), UsernamePasswordAuthenticationFilter.class); 37 | return http.build(); 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/service/MetricKey.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.service; 2 | 3 | import io.bpoole6.accumulator.service.metricgroup.Group; 4 | import lombok.Data; 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | import java.util.Objects; 9 | 10 | @Data 11 | public class MetricKey { 12 | 13 | private final Group metricGroup; 14 | private final String metricName; 15 | private final String help; 16 | private final Map tags = new HashMap<>(); 17 | 18 | public MetricKey(Group metricGroup, String metricName, String help, Map tags) { 19 | this.metricGroup = metricGroup; 20 | this.metricName = metricName; 21 | this.help = help; 22 | setTags(tags); 23 | } 24 | 25 | private void setTags(Map tags) { 26 | if (this.tags.isEmpty()) 27 | this.tags.putAll(tags); 28 | } 29 | 30 | @Override 31 | public boolean equals(Object o) { 32 | if (this == o) { 33 | return true; 34 | } 35 | if (o == null || getClass() != o.getClass()) { 36 | return false; 37 | } 38 | MetricKey metricKey = (MetricKey) o; 39 | return metricGroup == metricKey.metricGroup && Objects.equals(metricName, 40 | metricKey.metricName) && Objects.equals(RegistryRepository.stripMetaData(tags), RegistryRepository.stripMetaData(metricKey.tags)); 41 | } 42 | 43 | @Override 44 | public int hashCode() { 45 | return Objects.hash(metricGroup, metricName, RegistryRepository.stripMetaData(tags)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/service/MetricManager.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.service; 2 | 3 | import io.bpoole6.accumulator.util.RunnableThrowable; 4 | import io.bpoole6.accumulator.util.Utils; 5 | import io.micrometer.core.instrument.Counter; 6 | import io.micrometer.core.instrument.Gauge; 7 | import io.micrometer.core.instrument.Tag; 8 | import io.micrometer.prometheusmetrics.PrometheusConfig; 9 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 10 | import io.prometheus.metrics.model.registry.PrometheusRegistry; 11 | import lombok.Getter; 12 | import org.apache.commons.lang3.math.NumberUtils; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | 16 | import java.util.*; 17 | import java.util.concurrent.ConcurrentHashMap; 18 | import java.util.concurrent.TimeUnit; 19 | import java.util.concurrent.locks.ReentrantReadWriteLock; 20 | import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; 21 | import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; 22 | 23 | public class MetricManager { 24 | 25 | @Getter 26 | private final PrometheusMeterRegistry prometheusRegistry; 27 | private static final Logger log = LoggerFactory.getLogger(RegistryRepository.class); 28 | private final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(); 29 | private final Map counters = new ConcurrentHashMap<>(); 30 | private final Map gauges = new ConcurrentHashMap<>(); 31 | 32 | private final String metricGroup; 33 | 34 | public MetricManager(String metricGroup) { 35 | prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); 36 | this.metricGroup = metricGroup; 37 | } 38 | 39 | public void incrementCounter(MetricKey key, prometheus.types.Counter incrementer) { 40 | 41 | RunnableThrowable runnable = () -> { 42 | StringJoiner sj = new StringJoiner(","); 43 | key.getTags().forEach((k, v) -> { 44 | sj.add(k); 45 | sj.add(v); 46 | }); 47 | String[] labels = sj.toString().split(","); 48 | PrometheusMeterRegistry pr = prometheusRegistry; 49 | Counter counter = this.counters.computeIfAbsent(key, (k) -> { 50 | if (Utils.exceedsMaxTimeSeriesLimit(key.getMetricGroup(), pr)) { 51 | return null; 52 | } 53 | Counter.Builder builder = Counter.builder( 54 | key.getMetricName()).description(key.getHelp()); 55 | if (!key.getTags().isEmpty()) { 56 | builder.tags(labels); 57 | } 58 | return builder.register(pr); 59 | }); 60 | 61 | counter.increment(incrementer.getValue()); 62 | }; 63 | runReadLockProcess(runnable); 64 | } 65 | 66 | public void setGauge(MetricKey key, prometheus.types.Gauge metric) { 67 | RunnableThrowable runnable = () -> { 68 | StringJoiner sj = new StringJoiner(","); 69 | Map tags = RegistryRepository.stripMetaData(key.getTags()); 70 | Long timestampOpt = latestTimestamp(key.getTags()).orElse(0L); 71 | 72 | tags.forEach((k, v) -> { 73 | sj.add(k); 74 | sj.add(v); 75 | }); 76 | String[] labels = sj.toString().split(","); 77 | PrometheusMeterRegistry pr = prometheusRegistry; 78 | MetricValue mv = new MetricValue(metric.getValue(), timestampOpt); 79 | 80 | MetricValue foundGague = gauges.computeIfAbsent(key, k -> { 81 | if (Utils.exceedsMaxTimeSeriesLimit(key.getMetricGroup(), pr)) { 82 | return null; 83 | } 84 | Gauge.Builder builder = Gauge.builder(k.getMetricName(), mv, MetricValue::getValue) 85 | .description(key.getHelp()); 86 | if (!tags.isEmpty()) { 87 | builder.tags(labels); 88 | } 89 | builder.register(pr); 90 | return mv; 91 | }); 92 | 93 | if (foundGague != null && foundGague.getTimestamp() <= timestampOpt) { 94 | foundGague.setValue(mv.getValue()); 95 | foundGague.setTimestamp(mv.getTimestamp()); 96 | } 97 | }; 98 | runReadLockProcess(runnable); 99 | } 100 | 101 | public Optional latestTimestamp(Map tags) { 102 | if (tags.containsKey(RegistryRepository.META_DATA_LATEST) && NumberUtils.isCreatable(tags.get( 103 | RegistryRepository.META_DATA_LATEST))) { 104 | return Optional.of(Long.parseLong(tags.get(RegistryRepository.META_DATA_LATEST))); 105 | } 106 | return Optional.empty(); 107 | } 108 | 109 | 110 | public void resetRegistries() throws InterruptedException { 111 | RunnableThrowable runnable = () -> { 112 | this.counters.clear(); 113 | this.gauges.clear(); 114 | this.prometheusRegistry.clear(); 115 | }; 116 | runWriteLockProcess(runnable); 117 | } 118 | 119 | public void runWriteLockProcess(RunnableThrowable runnableThrowable) throws InterruptedException { 120 | WriteLock lock = reentrantReadWriteLock.writeLock(); 121 | if (lock.tryLock(10, TimeUnit.SECONDS)) { 122 | try { 123 | runnableThrowable.run(); 124 | } catch (Throwable e) { 125 | log.error(e.getMessage(), e); 126 | } finally { 127 | lock.unlock(); 128 | } 129 | } else { 130 | throw new RuntimeException("Write lock fail for %s".formatted(this.metricGroup)); 131 | } 132 | } 133 | 134 | public void runReadLockProcess(RunnableThrowable runnableThrowable) { 135 | ReadLock lock = reentrantReadWriteLock.readLock(); 136 | try { 137 | if (lock.tryLock(10, TimeUnit.SECONDS)) { 138 | try { 139 | runnableThrowable.run(); 140 | } catch (Throwable e) { 141 | } finally { 142 | lock.unlock(); 143 | } 144 | } else { 145 | throw new RuntimeException("Read lock fail for %s".formatted(this.metricGroup)); 146 | } 147 | } catch (InterruptedException e) { 148 | throw new RuntimeException(e); 149 | } 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/service/MetricService.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.service; 2 | 3 | import io.bpoole6.accumulator.ScheduledTasks; 4 | import io.bpoole6.accumulator.service.metricgroup.Group; 5 | import io.bpoole6.accumulator.util.Utils; 6 | import lombok.Data; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.stereotype.Service; 10 | import prometheus.types.Metric; 11 | import prometheus.types.MetricFamily; 12 | import prometheus.types.MetricType; 13 | 14 | import java.io.IOException; 15 | import java.util.LinkedList; 16 | import java.util.List; 17 | import java.util.Optional; 18 | import java.util.Queue; 19 | import java.util.concurrent.*; 20 | import java.util.concurrent.locks.ReentrantReadWriteLock; 21 | 22 | @Service 23 | @Slf4j 24 | public class MetricService { 25 | 26 | @Data 27 | private static class MetricQueueItem { 28 | private final Metric metric; 29 | private final MetricKey metricKey; 30 | private final MetricType metricType; 31 | } 32 | 33 | private final int maxBatchedMetrics; 34 | public final int sleepTimeBtwMetrics; 35 | private final MetricsAccumulatorConfiguration metricsAccumulatorConfiguration; 36 | private final ScheduledTasks scheduledTasks; 37 | private final RegistryRepository registryRepository; 38 | private final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(); 39 | 40 | private final BlockingDeque metricQueueItems = new LinkedBlockingDeque<>(); 41 | 42 | public MetricService(RegistryRepository registryRepository, MetricsAccumulatorConfiguration metricsAccumulatorConfiguration, 43 | ScheduledTasks scheduledTasks, @Value("${maxBatchedMetrics}") int maxBatchedMetrics, 44 | @Value("${sleepTimeBtwMetrics}")int sleepTimeBtwMetrics) { 45 | this.registryRepository = registryRepository; 46 | this.metricsAccumulatorConfiguration = metricsAccumulatorConfiguration; 47 | this.scheduledTasks = scheduledTasks; 48 | this.maxBatchedMetrics = maxBatchedMetrics; 49 | this.sleepTimeBtwMetrics = sleepTimeBtwMetrics; 50 | ExecutorService executorService = Executors.newSingleThreadExecutor(); 51 | executorService.execute(this::pollQueue); 52 | 53 | } 54 | 55 | public void modifyMetrics(String metrics, Group metricGroup) throws IOException, InterruptedException { 56 | 57 | List metricFamilies = Utils.readMetrics(metrics); 58 | for (MetricFamily metricFamily : metricFamilies) { 59 | for (Metric metric : metricFamily.getMetrics()) { 60 | MetricKey metricKey = new MetricKey(metricGroup, metricFamily.getName(), metricFamily.getHelp(), metric.getLabels()); 61 | metricQueueItems.push(new MetricQueueItem(metric, metricKey, metricFamily.getType())); 62 | } 63 | } 64 | } 65 | 66 | private void persistMetrics(Queue itemsToBeProcessed) throws InterruptedException { 67 | ReentrantReadWriteLock.ReadLock readlock = reentrantReadWriteLock.readLock(); 68 | if (readlock.tryLock(20, TimeUnit.SECONDS)) { 69 | try { 70 | MetricQueueItem item; 71 | while ((item = itemsToBeProcessed.poll()) != null) { 72 | if (item.getMetricType() == MetricType.COUNTER) { 73 | this.registryRepository.incrementCounter(item.getMetricKey(), (prometheus.types.Counter) item.getMetric()); 74 | } else if (item.getMetricType() == MetricType.GAUGE) { 75 | this.registryRepository.setGauge(item.getMetricKey(), (prometheus.types.Gauge) item.getMetric()); 76 | } 77 | } 78 | } catch (Exception e) { 79 | log.error("Failed to modify metrics", e); 80 | } finally { 81 | readlock.unlock(); 82 | } 83 | } 84 | } 85 | 86 | public void pollQueue() { 87 | while (true) { 88 | try { 89 | 90 | MetricQueueItem item; 91 | int count = 0; 92 | Queue itemsToBeProcessed = new LinkedList<>(); 93 | while ((item = metricQueueItems.poll()) != null && count < maxBatchedMetrics) { 94 | itemsToBeProcessed.add(item); 95 | count++; 96 | } 97 | persistMetrics(itemsToBeProcessed); 98 | 99 | } catch (Exception e) { 100 | log.error(e.getMessage(), e); 101 | } 102 | try { 103 | Thread.sleep(sleepTimeBtwMetrics); 104 | } catch (InterruptedException e) { 105 | log.error(e.getMessage(), e); 106 | } 107 | } 108 | } 109 | 110 | public Optional getMetricSnapshot(Group metricGroup) { 111 | 112 | MetricManager mm = registryRepository.getRegistry(metricGroup); 113 | if (mm != null) { 114 | return Optional.of(mm.getPrometheusRegistry().scrape()); 115 | } 116 | return Optional.empty(); 117 | } 118 | 119 | public boolean resetMetricGroup(Group group) { 120 | try { 121 | MetricManager metricManager = this.registryRepository.getRegistry(group); 122 | metricManager.resetRegistries(); 123 | } catch (Exception e) { 124 | return false; 125 | } 126 | return true; 127 | } 128 | 129 | public boolean resetConfigs() throws InterruptedException { 130 | ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock(); 131 | if (writeLock.tryLock(20, TimeUnit.SECONDS)) { 132 | try { 133 | metricsAccumulatorConfiguration.resetConfiguration(); 134 | registryRepository.reset(); 135 | scheduledTasks.reset(); 136 | return true; 137 | } catch (Throwable e) { 138 | log.error("Failed to reset. Please reset configurations"); 139 | return false; 140 | } finally { 141 | writeLock.unlock(); 142 | } 143 | } else { 144 | return false; 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/service/MetricValue.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.service; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class MetricValue { 7 | private Double value; 8 | private long timestamp; 9 | public MetricValue(Double value, long timestamp) { 10 | this.value = value; 11 | this.timestamp = timestamp; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/service/MetricsAccumulatorConfiguration.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.service; 2 | 3 | import io.bpoole6.accumulator.service.metricgroup.Global; 4 | import io.bpoole6.accumulator.service.metricgroup.Group; 5 | import io.bpoole6.accumulator.service.metricgroup.Root; 6 | import java.util.function.Function; 7 | import lombok.Data; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.boot.ApplicationArguments; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.util.ResourceUtils; 12 | import org.yaml.snakeyaml.Yaml; 13 | 14 | import java.io.File; 15 | import java.io.IOException; 16 | import java.nio.file.Files; 17 | import java.nio.file.Paths; 18 | import java.util.List; 19 | import java.util.Map; 20 | import java.util.Objects; 21 | import java.util.StringJoiner; 22 | import java.util.stream.Collectors; 23 | 24 | /** 25 | * Reason for using a configuration file over an Enum. 26 | *

27 | * 1.) Because we are using an apikey to control access to updating the metrics we need a seperation 28 | * between dev/prod. An enum class wouldn't be able to easily differentiate between the two profiles 29 | * like you can do with configurations files 30 | */ 31 | @Component 32 | @Data 33 | @Slf4j 34 | public class MetricsAccumulatorConfiguration { 35 | public static final String CONFIGURATION_OPTS = "config-file"; 36 | private String hostAddress; 37 | private Global global; 38 | private Map metricGroups; 39 | private Map metricGroupByApiKey; 40 | private String configurationFile; 41 | private String fileContent; 42 | public MetricsAccumulatorConfiguration(ApplicationArguments arguments) 43 | throws IOException { 44 | if(!arguments.containsOption(CONFIGURATION_OPTS)){ 45 | log.error("--%s option is not set".formatted(CONFIGURATION_OPTS)); 46 | throw new RuntimeException(); 47 | } 48 | configurationFile = Paths.get(arguments.getOptionValues(CONFIGURATION_OPTS).get(0)).toAbsolutePath().toString(); 49 | resetConfiguration(); 50 | } 51 | 52 | public void resetConfiguration() throws IOException { 53 | File file = ResourceUtils.getFile(configurationFile); 54 | Yaml yaml = new Yaml(); 55 | String content = Files.readString(file.toPath()); 56 | Root root = yaml.loadAs(content, Root.class); 57 | validateConfigs(root); 58 | this.metricGroups = root.getMetricGroups().values().stream().collect(Collectors.toMap(i->i.getName(), 59 | Function.identity())); 60 | this.hostAddress = root.getGlobal().getHostAddress(); 61 | this.metricGroupByApiKey = metricGroups.values().stream().collect(Collectors.toMap(Group::getApiKey, g -> g)); 62 | this.global = root.getGlobal(); 63 | this.fileContent = content; 64 | } 65 | 66 | public List getNames() { 67 | return metricGroups.values().stream().filter(Group::isDisplayMetrics).map( 68 | Group::getName).toList(); 69 | } 70 | 71 | private void validateConfigs(Root root){ 72 | StringJoiner sj = new StringJoiner(System.lineSeparator()); 73 | if(Objects.isNull(root)){ 74 | sj.add("Configuration file parsed but no configs present"); 75 | } 76 | if(Objects.isNull(root.getGlobal())){ 77 | sj.add("global attribute not set"); 78 | }else { 79 | if(Objects.isNull(root.getGlobal().getRestartCronExpression())){ 80 | sj.add("global.restartCronExpression not set"); 81 | } 82 | if(Objects.isNull(root.getGlobal().getHostAddress())){ 83 | sj.add("global.hostAddress not set"); 84 | } 85 | } 86 | 87 | if(Objects.isNull(root.getMetricGroups())){ 88 | sj.add("metricGroups is not set"); 89 | } else if (root.getMetricGroups().isEmpty()){ 90 | sj.add("metricGroups is empty"); 91 | }else{ 92 | root.getMetricGroups().forEach((k,v)->{ 93 | if(Objects.isNull(v.getName())){ 94 | sj.add("name is unset for metricGroup %s".formatted(k)); 95 | }else if (!v.getName().matches("^[-a-zA-Z0-9_]+")){ 96 | sj.add("name doesn't match regex ^[-a-zA-Z0-9_]+"); 97 | } 98 | if(Objects.isNull(v.getApiKey())){ 99 | sj.add("apiKey is unset for metricGroup %s".formatted(k)); 100 | } 101 | if(Objects.isNull(v.getMaxTimeSeries())){ 102 | sj.add("maxTimeSeries is unset for metricGroup %s".formatted(k)); 103 | } 104 | }); 105 | } 106 | String errors = sj.toString(); 107 | if(!errors.isBlank()){ 108 | log.error(errors); 109 | throw new RuntimeException("Failed metric group configurations"); 110 | } 111 | 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/service/RegistryRepository.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.service; 2 | 3 | import io.bpoole6.accumulator.service.metricgroup.Group; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import lombok.Getter; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.stereotype.Component; 10 | 11 | @Component 12 | @Slf4j 13 | public class RegistryRepository { 14 | 15 | public static final String META_DATA_PREFIX = "_metrics_accumulator_"; 16 | public static final String META_DATA_LATEST = META_DATA_PREFIX + "latest"; 17 | 18 | @Getter 19 | private final Map registryMap = new HashMap<>(); 20 | private final MetricsAccumulatorConfiguration metricsAccumulatorConfiguration; 21 | 22 | public RegistryRepository(MetricsAccumulatorConfiguration metricsAccumulatorConfiguration) { 23 | this.metricsAccumulatorConfiguration = metricsAccumulatorConfiguration; 24 | reset(); 25 | } 26 | 27 | public void reset(){ 28 | registryMap.clear(); 29 | for (Group metricGroup : metricsAccumulatorConfiguration.getMetricGroups().values()) { 30 | registryMap.put(metricGroup, new MetricManager(metricGroup.getName())); 31 | } 32 | } 33 | public MetricManager getRegistry(Group metricGroup) { 34 | return this.registryMap.get(metricGroup); 35 | } 36 | public void incrementCounter(MetricKey metricKey, prometheus.types.Counter metric) { 37 | this.registryMap.get(metricKey.getMetricGroup()).incrementCounter(metricKey, metric); 38 | } 39 | public void setGauge(MetricKey metricKey, prometheus.types.Gauge metric) { 40 | this.registryMap.get(metricKey.getMetricGroup()).setGauge(metricKey, metric); 41 | } 42 | 43 | 44 | 45 | public static Map stripMetaData(Map labels) { 46 | Map map = new HashMap<>(); 47 | labels.forEach((k, v) -> { 48 | if (!k.startsWith(META_DATA_PREFIX)) { 49 | map.put(k, v); 50 | } 51 | }); 52 | return map; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/service/metricgroup/Global.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.service.metricgroup; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class Global { 7 | private String restartCronExpression; 8 | private String hostAddress; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/service/metricgroup/Group.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.service.metricgroup; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | @Data 9 | public class Group { 10 | private boolean displayMetrics; 11 | private String name; 12 | private Integer maxTimeSeries; 13 | private String apiKey; 14 | private String restartCronExpression; 15 | private final Map serviceDiscoveryLabels = new HashMap<>(); 16 | 17 | public void setServiceDiscoveryLabels(Map serviceDiscoveryLabels){ 18 | this.serviceDiscoveryLabels.clear(); 19 | this.serviceDiscoveryLabels.putAll(serviceDiscoveryLabels); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/service/metricgroup/Root.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.service.metricgroup; 2 | 3 | import java.util.Map; 4 | import lombok.Data; 5 | 6 | @Data 7 | public class Root { 8 | private Global global; 9 | private Map metricGroups; 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/util/RunnableThrowable.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.util; 2 | 3 | public interface RunnableThrowable { 4 | 5 | void run() throws Throwable; 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/io/bpoole6/accumulator/util/Utils.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator.util; 2 | 3 | import io.bpoole6.accumulator.service.metricgroup.Group; 4 | import io.micrometer.core.instrument.Counter; 5 | import io.micrometer.core.instrument.composite.CompositeMeterRegistry; 6 | import io.micrometer.core.instrument.simple.SimpleMeterRegistry; 7 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 8 | import java.io.ByteArrayInputStream; 9 | import java.io.IOException; 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | import io.prometheus.metrics.model.registry.PrometheusRegistry; 14 | import prometheus.text.TextPrometheusMetricDataParser; 15 | import prometheus.types.MetricFamily; 16 | import prometheus.types.MetricType; 17 | 18 | public class Utils { 19 | public static List readMetrics(String metrics) throws IOException { 20 | 21 | TextPrometheusMetricDataParser i = new TextPrometheusMetricDataParser( 22 | new ByteArrayInputStream(metrics.getBytes())); 23 | List metricFamilies = new ArrayList<>(); 24 | MetricFamily family; 25 | while ((family = i.parse()) != null) { 26 | if((family.getType() == MetricType.COUNTER || family.getType() == MetricType.GAUGE) && !family.getName().endsWith("_info")) { 27 | metricFamilies.add(family); 28 | } 29 | } 30 | return metricFamilies; 31 | } 32 | public static boolean exceedsMaxTimeSeriesLimit(Group group, PrometheusMeterRegistry registry){ 33 | synchronized (registry){ 34 | return registry.getPrometheusRegistry().scrape().size() >= group.getMaxTimeSeries(); 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | PrometheusRegistry r = new PrometheusRegistry(); 40 | io.prometheus.metrics.core.metrics.Counter c = io.prometheus.metrics.core.metrics.Counter.builder().name("test").labelNames("tag").register(r); 41 | io.prometheus.metrics.core.metrics.Counter d = io.prometheus.metrics.core.metrics.Counter.builder().name("test").labelNames("b").register(r); 42 | c.labelValues("a").inc(); 43 | d.labelValues("b").inc(); 44 | System.out.println(); 45 | CompositeMeterRegistry s = new CompositeMeterRegistry(); 46 | Counter.builder("test") 47 | .tag("tag", "tag").register(s).increment(3); 48 | Counter.builder("test") 49 | .tag("bag", "bag").register(s).increment(34); 50 | System.out.println(); 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: metrics-accumulator 4 | 5 | management: 6 | endpoint: 7 | prometheus: 8 | enabled: true 9 | endpoints: 10 | web: 11 | exposure: 12 | include: prometheus 13 | metrics: 14 | tags: 15 | application: ${spring.application.name} 16 | maxBatchedMetrics: 200000 17 | sleepTimeBtwMetrics: 200 # milliseconds -------------------------------------------------------------------------------- /src/main/resources/banner.txt: -------------------------------------------------------------------------------- 1 | 2 | . . . . 3 | ,8. ,8. 8 8888888888 8888888 8888888888 8 888888888o. 8 8888 ,o888888o. d888888o. .8. ,o888888o. ,o888888o. 8 8888 88 ,8. ,8. 8 8888 88 8 8888 .8. 8888888 8888888888 ,o888888o. 8 888888888o. 4 | ,888. ,888. 8 8888 8 8888 8 8888 `88. 8 8888 8888 `88. .`8888:' `88. .888. 8888 `88. 8888 `88. 8 8888 88 ,888. ,888. 8 8888 88 8 8888 .888. 8 8888 . 8888 `88. 8 8888 `88. 5 | .`8888. .`8888. 8 8888 8 8888 8 8888 `88 8 8888 ,8 8888 `8. 8.`8888. Y8 :88888. ,8 8888 `8. ,8 8888 `8. 8 8888 88 .`8888. .`8888. 8 8888 88 8 8888 :88888. 8 8888 ,8 8888 `8b 8 8888 `88 6 | ,8.`8888. ,8.`8888. 8 8888 8 8888 8 8888 ,88 8 8888 88 8888 `8.`8888. . `88888. 88 8888 88 8888 8 8888 88 ,8.`8888. ,8.`8888. 8 8888 88 8 8888 . `88888. 8 8888 88 8888 `8b 8 8888 ,88 7 | ,8'8.`8888,8^8.`8888. 8 888888888888 8 8888 8 8888. ,88' 8 8888 88 8888 `8.`8888. .8. `88888. 88 8888 88 8888 8 8888 88 ,8'8.`8888,8^8.`8888. 8 8888 88 8 8888 .8. `88888. 8 8888 88 8888 88 8 8888. ,88' 8 | ,8' `8.`8888' `8.`8888. 8 8888 8 8888 8 888888888P' 8 8888 88 8888 `8.`8888. .8`8. `88888. 88 8888 88 8888 8 8888 88 ,8' `8.`8888' `8.`8888. 8 8888 88 8 8888 .8`8. `88888. 8 8888 88 8888 88 8 888888888P' 9 | ,8' `8.`88' `8.`8888. 8 8888 8 8888 8 8888`8b 8 8888 88 8888 `8.`8888. .8' `8. `88888.88 8888 88 8888 8 8888 88 ,8' `8.`88' `8.`8888. 8 8888 88 8 8888 .8' `8. `88888. 8 8888 88 8888 ,8P 8 8888`8b 10 | ,8' `8.`' `8.`8888. 8 8888 8 8888 8 8888 `8b. 8 8888 `8 8888 .8' 8b `8.`8888. .8' `8. `88888`8 8888 .8' `8 8888 .8' ` 8888 ,8P ,8' `8.`' `8.`8888.` 8888 ,8P 8 8888 .8' `8. `88888. 8 8888 `8 8888 ,8P 8 8888 `8b. 11 | ,8' `8 `8.`8888. 8 8888 8 8888 8 8888 `8b. 8 8888 8888 ,88' `8b. ;8.`8888 .888888888. `88888. 8888 ,88' 8888 ,88' 8888 ,d8P ,8' `8 `8.`8888. 8888 ,d8P 8 8888 .888888888. `88888. 8 8888 ` 8888 ,88' 8 8888 `8b. 12 | ,8' ` `8.`8888. 8 888888888888 8 8888 8 8888 `88. 8 8888 `8888888P' `Y8888P ,88P' .8' `8. `88888. `8888888P' `8888888P' `Y88888P' ,8' ` `8.`8888. `Y88888P' 8 888888888888 .8' `8. `88888. 8 8888 `8888888P' 8 8888 `88. 13 | -------------------------------------------------------------------------------- /src/main/resources/static/blah.txt: -------------------------------------------------------------------------------- 1 | # TYPE mega_total counter 2 | # HELP mega_total 3 | mega_total {span_id="321",trace_id="124",a="df"} 5.0 4 | mega_total 5.0 -------------------------------------------------------------------------------- /src/main/resources/templates/configuration.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Hello 5 | 6 | 15 | 16 | 17 | 18 |

Configurations

19 |

Swagger Endpoint

20 |

Configuration file:

21 |

22 |

Configuration loaded

23 |
24 |         
25 |             
26 |         
27 |     
28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/test/java/io/bpoole6/accumulator/BasicTest.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator; 2 | 3 | import io.bpoole6.accumulator.service.MetricsAccumulatorConfiguration; 4 | import org.mockito.Mockito; 5 | import org.springframework.boot.ApplicationArguments; 6 | import org.springframework.boot.test.context.TestConfiguration; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.test.context.ContextConfiguration; 9 | 10 | import java.io.IOException; 11 | import java.nio.file.Path; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | @ContextConfiguration(classes = BasicTest.TestApplicationArguments.class) 16 | public class BasicTest { 17 | 18 | @TestConfiguration 19 | public static class TestApplicationArguments{ 20 | @Bean("springApplicationArguments") 21 | public ApplicationArguments getApplicationArguments() throws IOException { 22 | ApplicationArguments arguments = Mockito.mock(ApplicationArguments.class); 23 | Path path = TestUtils.createMetricsFile(); 24 | List configFiles = new ArrayList<>(); 25 | configFiles.add(path.toAbsolutePath().toString()); 26 | Mockito.when(arguments.containsOption(MetricsAccumulatorConfiguration.CONFIGURATION_OPTS)).thenReturn(true); 27 | Mockito.when(arguments.getOptionValues(MetricsAccumulatorConfiguration.CONFIGURATION_OPTS)).thenReturn(configFiles); 28 | 29 | return arguments; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/io/bpoole6/accumulator/MetricsConsumerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator; 2 | 3 | import io.bpoole6.accumulator.service.MetricService; 4 | import io.bpoole6.accumulator.service.RegistryRepository; 5 | import io.bpoole6.accumulator.service.metricgroup.Group; 6 | import io.bpoole6.accumulator.service.MetricsAccumulatorConfiguration; 7 | import io.bpoole6.accumulator.util.Utils; 8 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 9 | import java.io.IOException; 10 | import java.nio.charset.Charset; 11 | import java.util.List; 12 | import java.util.Optional; 13 | import org.junit.jupiter.api.Assertions; 14 | import org.junit.jupiter.api.BeforeEach; 15 | import org.junit.jupiter.api.Test; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.beans.factory.annotation.Value; 18 | import org.springframework.boot.test.context.SpringBootTest; 19 | import org.springframework.core.io.Resource; 20 | import org.springframework.test.annotation.DirtiesContext; 21 | import prometheus.types.Counter; 22 | import prometheus.types.Gauge; 23 | import prometheus.types.Metric; 24 | import prometheus.types.MetricFamily; 25 | import prometheus.types.MetricType; 26 | 27 | @SpringBootTest 28 | @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) //In the future we may want to just reset the registries and maps between tests. Reloading the context may become expensive 29 | class MetricsConsumerApplicationTests extends BasicTest{ 30 | 31 | 32 | @Value("classpath:data/default/metrics") 33 | private Resource metrics1; 34 | 35 | @Value("classpath:data/label_timestamp/metrics-future") 36 | private Resource metricsFuture; 37 | 38 | @Value("classpath:data/label_timestamp/metrics-old") 39 | private Resource metricsOld; 40 | 41 | @Autowired 42 | private RegistryRepository registryRepository; 43 | 44 | @Autowired 45 | private MetricService metricService; 46 | 47 | private Group defaultGroup; 48 | @Autowired 49 | private MetricsAccumulatorConfiguration metricsAccumulatorConfiguration; 50 | 51 | public MetricsConsumerApplicationTests() { 52 | 53 | } 54 | 55 | @BeforeEach 56 | void setup() { 57 | this.defaultGroup = registryRepository.getRegistryMap().keySet().stream().findFirst().get(); 58 | } 59 | 60 | @Test 61 | void testCounterAccumulator() throws IOException, InterruptedException { 62 | List originalMetrics = Utils.readMetrics( 63 | new String(metrics1.getContentAsByteArray())); 64 | metricService.modifyMetrics(new String(metrics1.getContentAsByteArray()), defaultGroup); 65 | metricService.modifyMetrics(new String(metrics1.getContentAsByteArray()), defaultGroup); 66 | Thread.sleep(metricService.sleepTimeBtwMetrics+500); 67 | PrometheusMeterRegistry prometheusRegistry =this.registryRepository.getRegistry(defaultGroup).getPrometheusRegistry(); 68 | String snapshot = prometheusRegistry.scrape(); 69 | List newMetrics =Utils.readMetrics(snapshot); 70 | 71 | evalMetricFamilies(originalMetrics, newMetrics); 72 | 73 | } 74 | 75 | @Test 76 | void testGaugeTimestamp() throws IOException, InterruptedException { 77 | String olderMetrics = metricsOld.getContentAsString(Charset.defaultCharset()); 78 | String newerMetrics = metricsFuture.getContentAsString(Charset.defaultCharset()); 79 | 80 | this.metricService.modifyMetrics(olderMetrics, defaultGroup); 81 | this.metricService.modifyMetrics(newerMetrics, defaultGroup); 82 | Thread.sleep(metricService.sleepTimeBtwMetrics+500); 83 | Gauge oldGauge = (Gauge) Utils.readMetrics(olderMetrics).get(0).getMetrics().get(0); 84 | Gauge newGauge = (Gauge) Utils.readMetrics(this.registryRepository.getRegistry(defaultGroup).getPrometheusRegistry().scrape()).get(0).getMetrics().get(0); 85 | Assertions.assertNotSame(oldGauge.getValue(), newGauge.getValue()); 86 | Assertions.assertEquals(4911.0, newGauge.getValue()); 87 | } 88 | 89 | @Test 90 | void testMaxMetrics() throws IOException, InterruptedException { 91 | String formatted = """ 92 | # HELP python%s_gc_objects_collected_seconds Objects collected during gc 93 | # TYPE python%s_gc_objects_collected_seconds gauge 94 | python%s_gc_objects_collected_seconds{generation="0",_metrics_accumulator_latest="3992623250"} 4911.0 95 | """; 96 | String strings = ""; 97 | for(int i = 0; i < 150; i++) { 98 | strings += formatted.formatted(i,i,i); 99 | } 100 | this.metricService.modifyMetrics(strings, defaultGroup); 101 | Thread.sleep(metricService.sleepTimeBtwMetrics+500); 102 | Assertions.assertEquals(defaultGroup.getMaxTimeSeries(), this.registryRepository.getRegistry(defaultGroup).getPrometheusRegistry().getPrometheusRegistry().scrape().size()); 103 | } 104 | 105 | 106 | 107 | public void evalMetricFamilies(List originalMetrics, List newMetrics) { 108 | for (MetricFamily metricFamily : originalMetrics) { 109 | Optional opt = newMetrics.stream() 110 | .filter(i -> i.getName().equals(metricFamily.getName())).findFirst(); 111 | if(opt.isEmpty()){ 112 | Assertions.fail("Missing MetricFamily "+ metricFamily.getName()); 113 | } 114 | MetricFamily foundMetricFamily = opt.get(); 115 | Assertions.assertEquals(metricFamily.getType(), foundMetricFamily.getType()); 116 | for(Metric metric : metricFamily.getMetrics()){ 117 | Metric foundMetric = foundMetricFamily.getMetrics().stream().filter(i-> i.getName().equals(metric.getName()) && i.getLabels().equals(metric.getLabels())).findFirst().get(); 118 | Assertions.assertEquals(metric.getLabels().keySet(), foundMetric.getLabels().keySet()); 119 | if(metricFamily.getType() == MetricType.COUNTER) { 120 | Counter c = ((prometheus.types.Counter)metric); 121 | Counter foundC = ((prometheus.types.Counter)foundMetric); 122 | Assertions.assertEquals(c.getValue()*2, foundC.getValue() ); 123 | }else if(metricFamily.getType() == MetricType.GAUGE){ 124 | Gauge g = ((prometheus.types.Gauge)metric); 125 | Gauge foundG = ((prometheus.types.Gauge)foundMetric); 126 | Assertions.assertEquals(g.getValue(), foundG.getValue() ); 127 | } 128 | 129 | } 130 | } 131 | 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/test/java/io/bpoole6/accumulator/ResetConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator; 2 | 3 | import io.bpoole6.accumulator.service.MetricsAccumulatorConfiguration; 4 | import io.bpoole6.accumulator.service.MetricManager; 5 | import io.bpoole6.accumulator.service.MetricService; 6 | import io.bpoole6.accumulator.service.RegistryRepository; 7 | import io.bpoole6.accumulator.service.metricgroup.Group; 8 | import org.junit.jupiter.api.Assertions; 9 | import org.junit.jupiter.api.Test; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.test.annotation.DirtiesContext; 13 | 14 | import java.io.IOException; 15 | import java.nio.file.Files; 16 | import java.nio.file.Path; 17 | import java.nio.file.Paths; 18 | import java.util.List; 19 | import java.util.Optional; 20 | 21 | @SpringBootTest 22 | @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) //In the future we may want to just reset the registries and maps between tests 23 | public class ResetConfigurationTest extends BasicTest{ 24 | 25 | @Autowired 26 | private RegistryRepository registryRepository; 27 | 28 | @Autowired 29 | private MetricService metricService; 30 | 31 | @Autowired 32 | private ScheduledTasks scheduledTasks; 33 | 34 | @Autowired 35 | private MetricsAccumulatorConfiguration metricsAccumulatorConfiguration; 36 | 37 | @Test 38 | void testMetricReset() throws IOException, InterruptedException { 39 | 40 | String oldName = "oldName"; 41 | String newName = "newName"; 42 | Path path = Paths.get(this.metricsAccumulatorConfiguration.getConfigurationFile()); 43 | Files.writeString(path, TestUtils.metricsFile(oldName)); 44 | this.metricService.resetConfigs(); 45 | 46 | Optional oldGroup = this.registryRepository.getRegistryMap().keySet().stream().findFirst(); 47 | Assertions.assertTrue(oldGroup.isPresent(), "Assert that registrymap has the current"); 48 | Assertions.assertEquals(oldName, oldGroup.get().getName(), "Assert that Group name is %s".formatted(oldName)); 49 | 50 | Files.writeString(path, TestUtils.metricsFile(newName)); 51 | this.metricService.resetConfigs(); 52 | 53 | Optional newGroup = this.registryRepository.getRegistryMap().keySet().stream().findFirst(); 54 | Assertions.assertTrue(newGroup.isPresent(), "Assert that registrymap has the current"); 55 | Assertions.assertEquals(newName, newGroup.get().getName(), "Assert that Group name is %s".formatted(newName)); 56 | } 57 | 58 | 59 | @Test 60 | public void resetMetricManager() throws InterruptedException, IOException { 61 | String metrics = """ 62 | # HELP python_gc_objects_collected_seconds Objects collected during gc 63 | # TYPE python_gc_objects_collected_seconds gauge 64 | python_gc_objects_collected_seconds{generation="0",_metrics_accumulator_latest="3992623250"} 4911.0 65 | """; 66 | Group group = this.registryRepository.getRegistryMap().keySet().stream().findFirst().get(); 67 | this.metricService.modifyMetrics(metrics, group); 68 | Thread.sleep(metricService.sleepTimeBtwMetrics+500); 69 | MetricManager oldManager = this.registryRepository.getRegistryMap().values().stream().findFirst().get(); 70 | Assertions.assertEquals(1, oldManager.getPrometheusRegistry().getPrometheusRegistry().scrape().size()); 71 | oldManager.resetRegistries(); 72 | Assertions.assertEquals(0, oldManager.getPrometheusRegistry().getPrometheusRegistry().scrape().size()); 73 | 74 | } 75 | @Test 76 | public void testSchedulingReload() throws InterruptedException { 77 | List oldTasks = this.scheduledTasks.getTasks(); 78 | this.metricService.resetConfigs(); 79 | List newTasks = this.scheduledTasks.getTasks(); 80 | 81 | oldTasks.forEach(t->{ 82 | Assertions.assertTrue(t.getFuture().isCancelled(), "Task is still running when it should be stopped"); 83 | }); 84 | 85 | newTasks.forEach(t->{ 86 | Assertions.assertFalse(t.getFuture().isCancelled(), "Task is still running when it should be stopped"); 87 | }); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/io/bpoole6/accumulator/TestControllers.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator; 2 | 3 | import io.bpoole6.accumulator.controller.MetricsController; 4 | import io.bpoole6.accumulator.controller.response.ServiceDiscovery; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.Test; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.test.annotation.DirtiesContext; 11 | import org.springframework.web.client.RestTemplate; 12 | 13 | import java.net.URI; 14 | import java.net.http.HttpRequest; 15 | import java.util.List; 16 | 17 | @SpringBootTest 18 | @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) 19 | public class TestControllers extends BasicTest { 20 | 21 | @Autowired 22 | private MetricsController controller; 23 | 24 | @Test 25 | public void testServiceDiscovery(){ 26 | ResponseEntity> entity = controller.serviceDiscovery(); 27 | List sds = entity.getBody(); 28 | Assertions.assertTrue(sds.size() == 1); 29 | Assertions.assertEquals(3, sds.get(0).getLabels().size()); 30 | Assertions.assertEquals("qa", sds.get(0).getLabels().get("env")); 31 | Assertions.assertEquals("v45", sds.get(0).getLabels().get("version")); 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/io/bpoole6/accumulator/TestUtils.java: -------------------------------------------------------------------------------- 1 | package io.bpoole6.accumulator; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | 7 | public class TestUtils { 8 | public static String DEFAULT_METRIC_NAME = "test-Metrics"; 9 | public static Path createMetricsFile() throws IOException { 10 | Path path = Files.createTempFile("config",".yml"); 11 | Files.writeString(path,metricsFile(DEFAULT_METRIC_NAME)); 12 | return path; 13 | } 14 | public static String metricsFile(String name){ 15 | return """ 16 | global: 17 | restartCronExpression: "0 0 0 ? * *" 18 | hostAddress: localhost:8080 19 | 20 | metricGroups: 21 | %s: 22 | displayMetrics: true 23 | name: %s 24 | maxTimeSeries: 100 25 | apiKey: 0d98f65f-074b-4d56-b834-576e15a3bfa5 26 | restartCronExpression: "0 0 0 ? * *" 27 | serviceDiscoveryLabels: 28 | env: qa 29 | version: v45 30 | """.formatted(name,name); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/test/resources/application.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: MetricsConsumer 4 | server: 5 | port: 8081 6 | 7 | metricGroup: 8 | file: "classpath:metric-groups.yml" 9 | host: 10 | address: "localhost:8081" 11 | 12 | maxBatchedMetrics: 100000 13 | sleepTimeBtwMetrics: 200 # milliseconds -------------------------------------------------------------------------------- /src/test/resources/data/created_total/metrics: -------------------------------------------------------------------------------- 1 | # HELP proxy_watch_total Total number of connection made 2 | # TYPE proxy_watch_total counter 3 | proxy_watch_total{application="proxy_watch",host="proxy.internal.q6cyber.com",ip="8003"} 1211.0 4 | # HELP proxy_watch_created Total number of connection made 5 | # TYPE proxy_watch_created gauge 6 | #proxy_watch_created{application="proxy_watch",host="proxy.internal.q6cyber.com",ip="8003"} 1.7225315143089755e+09 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/test/resources/data/default/metrics: -------------------------------------------------------------------------------- 1 | # HELP python_gc_objects_collected_total Objects collected during gc 2 | # TYPE python_gc_objects_collected_total counter 3 | python_gc_objects_collected_total{generation="0"} 4911.0 4 | python_gc_objects_collected_total{generation="1"} 324.0 5 | python_gc_objects_collected_total{generation="2"} 0.0 6 | # HELP python_gc_objects_uncollectable_total Uncollectable objects found during GC 7 | # TYPE python_gc_objects_uncollectable_total counter 8 | python_gc_objects_uncollectable_total{generation="0"} 0.0 9 | python_gc_objects_uncollectable_total{generation="1"} 0.0 10 | python_gc_objects_uncollectable_total{generation="2"} 0.0 11 | # HELP python_gc_collections_total Number of times this generation was collected 12 | # TYPE python_gc_collections_total counter 13 | python_gc_collections_total{generation="0"} 97.0 14 | python_gc_collections_total{generation="1"} 8.0 15 | python_gc_collections_total{generation="2"} 0.0 16 | # HELP python_info Python platform information 17 | # TYPE python_info gauge 18 | python_info{implementation="CPython",major="3",minor="10",patchlevel="12",version="3.10.12"} 1.0 19 | # HELP process_virtual_memory_bytes Virtual memory size in bytes. 20 | # TYPE process_virtual_memory_bytes gauge 21 | process_virtual_memory_bytes 3.43359488e+08 22 | # HELP process_resident_memory_bytes Resident memory size in bytes. 23 | # TYPE process_resident_memory_bytes gauge 24 | process_resident_memory_bytes 3.6716544e+07 25 | # HELP process_start_time_seconds Start time of the process since unix epoch in seconds. 26 | # TYPE process_start_time_seconds gauge 27 | process_start_time_seconds 1.72253151306e+09 28 | # HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. 29 | # TYPE process_cpu_seconds_total counter 30 | process_cpu_seconds_total 4.34 31 | # HELP process_open_fds Number of open file descriptors. 32 | # TYPE process_open_fds gauge 33 | process_open_fds 8.0 34 | # HELP process_max_fds Maximum number of open file descriptors. 35 | # TYPE process_max_fds gauge 36 | process_max_fds 1.048576e+06 37 | # HELP proxy_watch_total Total number of connection made 38 | # TYPE proxy_watch_total counter 39 | proxy_watch_total{application="proxy_watch",host="proxy.internal.q6cyber.com",ip="8003"} 1211.0 40 | -------------------------------------------------------------------------------- /src/test/resources/data/label_timestamp/metrics-future: -------------------------------------------------------------------------------- 1 | # HELP python_gc_objects_collected_seconds Objects collected during gc 2 | # TYPE python_gc_objects_collected_seconds gauge 3 | python_gc_objects_collected_seconds{generation="0",_metrics_accumulator_latest="3992623250"} 4911.0 4 | -------------------------------------------------------------------------------- /src/test/resources/data/label_timestamp/metrics-old: -------------------------------------------------------------------------------- 1 | # HELP python_gc_objects_collected_seconds Objects collected during gc 2 | # TYPE python_gc_objects_collected_seconds gauge 3 | python_gc_objects_collected_seconds{generation="0",_metrics_accumulator_latest="1722620529"} 5.0 4 | -------------------------------------------------------------------------------- /src/test/resources/metric-groups.yml: -------------------------------------------------------------------------------- 1 | --- 2 | defaults: 3 | restartCronExpression: "0 0 0 ? * *" 4 | metricGroups: 5 | default: 6 | displayMetrics: false 7 | name: default 8 | maxTimeSeries: 2500 9 | --------------------------------------------------------------------------------