├── .github └── dco.yml ├── doc └── proxy-grafana.png ├── scripts ├── proxy.sh ├── prometheus.sh ├── grafana-datasource.yml ├── grafana-dashboard.yml ├── kubernetes │ ├── prometheus │ │ ├── 02-prometheus-storage.yaml │ │ ├── prometheus-service.yaml │ │ ├── 00-namespace.yaml │ │ ├── prometheus-statefulset.yaml │ │ └── 01-prometheus-configmap.yaml │ ├── zipkin │ │ ├── zipkin-service.yaml │ │ ├── 00-namespace.yaml │ │ └── zipkin-statefulset.yaml │ ├── grafana │ │ ├── grafana-service.yaml │ │ ├── 00-namespace.yaml │ │ └── grafana-statefulset.yaml │ └── proxy │ │ ├── prometheus-proxy-service.yaml │ │ ├── 00-namespace.yaml │ │ └── prometheus-proxy-deployment.yaml ├── grafana.sh ├── prometheus.yml └── grafana-dashboard.json ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── licenseHeader.txt └── deploy.sh ├── .editorconfig ├── .gitignore ├── starter-spring ├── src │ ├── main │ │ ├── resources │ │ │ └── META-INF │ │ │ │ └── spring │ │ │ │ └── org.springframework.boot.autoconfigure.AutoConfiguration.imports │ │ └── java │ │ │ └── io │ │ │ └── micrometer │ │ │ └── prometheus │ │ │ └── rsocket │ │ │ └── autoconfigure │ │ │ ├── EnablePrometheusRSocketProxyServer.java │ │ │ ├── PrometheusRSocketProxyServerMarkerConfiguration.java │ │ │ ├── PrometheusRSocketProxyServerAutoConfiguration.java │ │ │ ├── PrometheusRSocketClientAutoConfiguration.java │ │ │ └── PrometheusRSocketClientProperties.java │ └── test │ │ ├── resources │ │ └── logback.xml │ │ └── java │ │ └── io │ │ └── micrometer │ │ └── prometheus │ │ └── rsocket │ │ └── autoconfigure │ │ └── PrometheusRSocketClientAutoConfigurationTest.java └── build.gradle ├── config └── checkstyle │ ├── suppressions.xml │ └── checkstyle.xml ├── NOTICE ├── proxy ├── src │ ├── main │ │ ├── resources │ │ │ └── application.yml │ │ └── java │ │ │ └── io │ │ │ └── micrometer │ │ │ └── prometheus │ │ │ └── rsocket │ │ │ └── PrometheusRSocketProxyMain.java │ └── test │ │ └── java │ │ └── io │ │ └── micrometer │ │ └── prometheus │ │ └── rsocket │ │ └── PrometheusRSocketProxyMainTest.java └── build.gradle ├── client ├── build.gradle └── src │ ├── test │ └── java │ │ └── io │ │ └── micrometer │ │ └── prometheus │ │ └── rsocket │ │ ├── SampleClient.java │ │ ├── SampleServerlessClient.java │ │ ├── SampleClientThatClosesManually.java │ │ ├── SampleManyClients.java │ │ └── PrometheusRSocketClientTests.java │ └── main │ └── java │ └── io │ └── micrometer │ └── prometheus │ └── rsocket │ └── PrometheusRSocketClient.java ├── proxy-server ├── build.gradle └── src │ └── main │ └── java │ └── io │ └── micrometer │ └── prometheus │ └── rsocket │ ├── PrometheusControllerProperties.java │ └── PrometheusController.java ├── settings.gradle ├── .circleci └── config.yml ├── CONTRIBUTING.md ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /.github/dco.yml: -------------------------------------------------------------------------------- 1 | require: 2 | members: false 3 | -------------------------------------------------------------------------------- /doc/proxy-grafana.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/micrometer-metrics/prometheus-rsocket-proxy/HEAD/doc/proxy-grafana.png -------------------------------------------------------------------------------- /scripts/proxy.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | docker run -p 8080:8080 -p 7001:7001 \ 3 | micrometermetrics/prometheus-rsocket-proxy:latest 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/micrometer-metrics/prometheus-rsocket-proxy/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /scripts/prometheus.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | docker run -p 9090:9090 \ 3 | -v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml \ 4 | prom/prometheus:v2.18.0 5 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | insert_final_newline = true 5 | 6 | [*.java] 7 | indent_style = space 8 | indent_size = 2 9 | continuation_indent_size = 4 10 | -------------------------------------------------------------------------------- /scripts/grafana-datasource.yml: -------------------------------------------------------------------------------- 1 | apiVersion: 1 2 | 3 | datasources: 4 | - name: prometheus 5 | type: prometheus 6 | access: direct 7 | url: http://10.200.10.1:9090 8 | isDefault: true 9 | -------------------------------------------------------------------------------- /scripts/grafana-dashboard.yml: -------------------------------------------------------------------------------- 1 | apiVersion: 1 2 | 3 | providers: 4 | - name: 'default' 5 | folder: 'Preconfigured' 6 | type: file 7 | options: 8 | path: /etc/grafana/dashboards 9 | 10 | -------------------------------------------------------------------------------- /scripts/kubernetes/prometheus/02-prometheus-storage.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: storage.k8s.io/v1 2 | kind: StorageClass 3 | metadata: 4 | name: faster 5 | namespace: monitoring-tools 6 | provisioner: kubernetes.io/gce-pd 7 | parameters: 8 | type: pd-ssd 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | **/build/ 3 | **/out/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | 6 | gradle.properties 7 | 8 | *.iml 9 | *.ipr 10 | *.iws 11 | .idea 12 | 13 | .classpath 14 | .project 15 | .settings/ 16 | .sts4-cache/ 17 | bin/ 18 | .factorypath 19 | 20 | -------------------------------------------------------------------------------- /starter-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports: -------------------------------------------------------------------------------- 1 | io.micrometer.prometheus.rsocket.autoconfigure.PrometheusRSocketClientAutoConfiguration 2 | io.micrometer.prometheus.rsocket.autoconfigure.PrometheusRSocketProxyServerAutoConfiguration 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /scripts/kubernetes/zipkin/zipkin-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: zipkin 5 | namespace: monitoring-tools 6 | labels: 7 | name: grafana 8 | spec: 9 | selector: 10 | app: zipkin 11 | ports: 12 | - name: zipkin 13 | port: 9411 14 | targetPort: 9411 15 | type: LoadBalancer 16 | -------------------------------------------------------------------------------- /scripts/kubernetes/grafana/grafana-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: grafana 5 | namespace: monitoring-tools 6 | labels: 7 | name: grafana 8 | spec: 9 | selector: 10 | app: grafana 11 | ports: 12 | - name: grafana 13 | port: 80 14 | targetPort: 3000 15 | type: LoadBalancer 16 | -------------------------------------------------------------------------------- /config/checkstyle/suppressions.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /scripts/grafana.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | docker run -i -p 3000:3000 \ 3 | -v $(pwd)/grafana-datasource.yml:/etc/grafana/provisioning/datasources/grafana-datasource.yml \ 4 | -v $(pwd)/grafana-dashboard.yml:/etc/grafana/provisioning/dashboards/grafana-dashboard.yml \ 5 | -v $(pwd)/grafana-dashboard.json:/etc/grafana/dashboards/grafana-dashboard.json \ 6 | grafana/grafana:6.7.3 7 | -------------------------------------------------------------------------------- /scripts/kubernetes/prometheus/prometheus-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: prometheus 5 | namespace: monitoring-tools 6 | labels: 7 | name: prometheus 8 | spec: 9 | selector: 10 | app: prometheus 11 | ports: 12 | - name: prometheus 13 | port: 9090 14 | targetPort: prometheus 15 | type: LoadBalancer 16 | -------------------------------------------------------------------------------- /scripts/kubernetes/proxy/prometheus-proxy-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: prometheus-proxy 5 | namespace: monitoring-tools 6 | labels: 7 | name: prometheus-proxy 8 | spec: 9 | selector: 10 | app: prometheus-proxy 11 | ports: 12 | - name: scrape 13 | port: 8080 14 | targetPort: 8080 15 | - name: rsocket 16 | port: 7001 17 | targetPort: 7001 18 | type: LoadBalancer 19 | -------------------------------------------------------------------------------- /scripts/kubernetes/proxy/00-namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: monitoring-tools 5 | --- 6 | apiVersion: v1 7 | kind: ServiceAccount 8 | metadata: 9 | name: monitoring-tools 10 | namespace: monitoring-tools 11 | --- 12 | apiVersion: rbac.authorization.k8s.io/v1beta1 13 | kind: ClusterRoleBinding 14 | metadata: 15 | name: monitoring-tools 16 | subjects: 17 | - kind: ServiceAccount 18 | name: monitoring-tools 19 | namespace: monitoring-tools 20 | roleRef: 21 | kind: ClusterRole 22 | name: cluster-admin 23 | apiGroup: rbac.authorization.k8s.io 24 | -------------------------------------------------------------------------------- /scripts/kubernetes/zipkin/00-namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: monitoring-tools 5 | --- 6 | apiVersion: v1 7 | kind: ServiceAccount 8 | metadata: 9 | name: monitoring-tools 10 | namespace: monitoring-tools 11 | --- 12 | apiVersion: rbac.authorization.k8s.io/v1beta1 13 | kind: ClusterRoleBinding 14 | metadata: 15 | name: monitoring-tools 16 | subjects: 17 | - kind: ServiceAccount 18 | name: monitoring-tools 19 | namespace: monitoring-tools 20 | roleRef: 21 | kind: ClusterRole 22 | name: cluster-admin 23 | apiGroup: rbac.authorization.k8s.io 24 | -------------------------------------------------------------------------------- /scripts/kubernetes/grafana/00-namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: monitoring-tools 5 | --- 6 | apiVersion: v1 7 | kind: ServiceAccount 8 | metadata: 9 | name: monitoring-tools 10 | namespace: monitoring-tools 11 | --- 12 | apiVersion: rbac.authorization.k8s.io/v1beta1 13 | kind: ClusterRoleBinding 14 | metadata: 15 | name: monitoring-tools 16 | subjects: 17 | - kind: ServiceAccount 18 | name: monitoring-tools 19 | namespace: monitoring-tools 20 | roleRef: 21 | kind: ClusterRole 22 | name: cluster-admin 23 | apiGroup: rbac.authorization.k8s.io 24 | -------------------------------------------------------------------------------- /scripts/kubernetes/prometheus/00-namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: monitoring-tools 5 | --- 6 | apiVersion: v1 7 | kind: ServiceAccount 8 | metadata: 9 | name: monitoring-tools 10 | namespace: monitoring-tools 11 | --- 12 | apiVersion: rbac.authorization.k8s.io/v1beta1 13 | kind: ClusterRoleBinding 14 | metadata: 15 | name: monitoring-tools 16 | subjects: 17 | - kind: ServiceAccount 18 | name: monitoring-tools 19 | namespace: monitoring-tools 20 | roleRef: 21 | kind: ClusterRole 22 | name: cluster-admin 23 | apiGroup: rbac.authorization.k8s.io 24 | -------------------------------------------------------------------------------- /gradle/licenseHeader.txt: -------------------------------------------------------------------------------- 1 | Copyright ${year} VMware, Inc. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Prometheus RSocket Proxy 2 | 3 | Copyright (c) 2017-Present VMware, Inc. All Rights Reserved. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | https://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | -------------------------------------------------------------------------------- /scripts/prometheus.yml: -------------------------------------------------------------------------------- 1 | global: 2 | scrape_interval: 5s 3 | 4 | scrape_configs: 5 | - job_name: 'prometheus' 6 | 7 | static_configs: 8 | - targets: ['localhost:9090'] 9 | 10 | - job_name: 'local-rsocket-proxy-connected' 11 | 12 | scrape_interval: 10s 13 | scrape_timeout: 9s 14 | metrics_path: '/metrics/connected' 15 | static_configs: 16 | - targets: ['10.200.10.1:8080'] 17 | 18 | - job_name: 'local-rsocket-proxy' 19 | 20 | scrape_interval: 10s 21 | scrape_timeout: 2s 22 | metrics_path: '/metrics/proxy' 23 | static_configs: 24 | - targets: ['10.200.10.1:8080'] 25 | 26 | rule_files: 27 | - prometheus_rules.yml 28 | -------------------------------------------------------------------------------- /proxy/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2019 Pivotal Software, Inc. 3 | #

4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | #

8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | #

10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | server.compression.enabled: true 18 | -------------------------------------------------------------------------------- /client/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java-library' 3 | } 4 | 5 | repositories { 6 | mavenCentral() 7 | } 8 | 9 | dependencies { 10 | 11 | 12 | api 'io.rsocket:rsocket-core:1.1.+' 13 | api 'io.micrometer:micrometer-registry-prometheus:1.13.+' 14 | implementation 'org.xerial.snappy:snappy-java:latest.release' 15 | 16 | testImplementation(platform('org.junit:junit-bom:5.12.1')) 17 | 18 | testImplementation 'ch.qos.logback:logback-classic:1.4.+' 19 | testImplementation 'org.junit.jupiter:junit-jupiter' 20 | testRuntimeOnly 'org.junit.platform:junit-platform-launcher' 21 | testImplementation 'io.rsocket:rsocket-transport-netty:1.1.+' 22 | testImplementation 'io.rsocket:rsocket-transport-local:1.1.+' 23 | testImplementation 'org.assertj:assertj-core:latest.release' 24 | } 25 | 26 | test { 27 | useJUnitPlatform() 28 | } 29 | -------------------------------------------------------------------------------- /scripts/kubernetes/proxy/prometheus-proxy-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: prometheus-proxy 5 | namespace: monitoring-tools 6 | spec: 7 | replicas: 3 8 | selector: 9 | matchLabels: 10 | app: prometheus-proxy 11 | template: 12 | metadata: 13 | labels: 14 | app: prometheus-proxy 15 | spec: 16 | serviceAccountName: monitoring-tools 17 | containers: 18 | - name: prometheus-proxy 19 | image: micrometermetrics/prometheus-rsocket-proxy:latest 20 | imagePullPolicy: Always 21 | ports: 22 | - name: scrape 23 | containerPort: 8080 24 | - name: rsocket 25 | containerPort: 7001 26 | resources: 27 | requests: 28 | cpu: "2" 29 | memory: "1000Mi" 30 | args: 31 | - -cpus 32 | - "2" 33 | securityContext: 34 | fsGroup: 2000 35 | runAsNonRoot: true 36 | runAsUser: 1000 37 | -------------------------------------------------------------------------------- /starter-spring/src/test/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | %d{yyyy-MM-dd HH:mm:ss.SSS} %5p --- [%15.15t] %-40.40logger{39} : %m%n 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /scripts/kubernetes/zipkin/zipkin-statefulset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: StatefulSet 3 | metadata: 4 | name: zipkin 5 | namespace: monitoring-tools 6 | spec: 7 | replicas: 1 8 | serviceName: zipkin 9 | selector: 10 | matchLabels: 11 | app: zipkin 12 | template: 13 | metadata: 14 | labels: 15 | app: zipkin 16 | spec: 17 | serviceAccountName: monitoring-tools 18 | securityContext: 19 | runAsUser: 472 20 | fsGroup: 472 21 | containers: 22 | - name: zipkin 23 | image: openzipkin/zipkin:latest 24 | ports: 25 | - containerPort: 9411 26 | protocol: TCP 27 | volumeMounts: 28 | - mountPath: /var/lib/zipkin 29 | name: zipkin-volume 30 | readOnly: false 31 | volumeClaimTemplates: 32 | - metadata: 33 | name: zipkin-volume 34 | spec: 35 | accessModes: 36 | - ReadWriteOnce 37 | resources: 38 | requests: 39 | storage: 128Gi 40 | storageClassName: standard 41 | -------------------------------------------------------------------------------- /scripts/kubernetes/grafana/grafana-statefulset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: StatefulSet 3 | metadata: 4 | name: grafana 5 | namespace: monitoring-tools 6 | spec: 7 | replicas: 1 8 | serviceName: grafana 9 | selector: 10 | matchLabels: 11 | app: grafana 12 | template: 13 | metadata: 14 | labels: 15 | app: grafana 16 | spec: 17 | serviceAccountName: monitoring-tools 18 | securityContext: 19 | runAsUser: 472 20 | fsGroup: 472 21 | containers: 22 | - name: grafana 23 | image: grafana/grafana:6.7.3 24 | ports: 25 | - containerPort: 3000 26 | protocol: TCP 27 | volumeMounts: 28 | - mountPath: /var/lib/grafana 29 | name: grafana-volume 30 | readOnly: false 31 | volumeClaimTemplates: 32 | - metadata: 33 | name: grafana-volume 34 | spec: 35 | accessModes: 36 | - ReadWriteOnce 37 | resources: 38 | requests: 39 | storage: 128Gi 40 | storageClassName: standard 41 | -------------------------------------------------------------------------------- /proxy-server/build.gradle: -------------------------------------------------------------------------------- 1 | import org.springframework.boot.gradle.plugin.SpringBootPlugin 2 | 3 | plugins { 4 | id 'java-library' 5 | id 'org.springframework.boot' version '3.4.0' apply false 6 | } 7 | 8 | apply plugin: 'io.spring.dependency-management' 9 | 10 | repositories { 11 | mavenCentral() 12 | } 13 | 14 | dependencyManagement { 15 | imports { 16 | mavenBom SpringBootPlugin.BOM_COORDINATES 17 | } 18 | } 19 | 20 | dependencies { 21 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 22 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 23 | implementation 'io.micrometer:micrometer-registry-prometheus' 24 | 25 | implementation 'io.rsocket:rsocket-micrometer' 26 | implementation 'io.rsocket:rsocket-transport-netty' 27 | 28 | implementation 'org.xerial.snappy:snappy-java:latest.release' 29 | annotationProcessor "org.springframework.boot:spring-boot-configuration-processor" 30 | 31 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 32 | testImplementation 'io.projectreactor:reactor-test' 33 | } 34 | -------------------------------------------------------------------------------- /proxy/src/test/java/io/micrometer/prometheus/rsocket/PrometheusRSocketProxyMainTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket; 17 | 18 | import org.junit.jupiter.api.Test; 19 | import org.junit.jupiter.api.extension.ExtendWith; 20 | import org.springframework.boot.test.context.SpringBootTest; 21 | import org.springframework.test.context.junit.jupiter.SpringExtension; 22 | 23 | @ExtendWith(SpringExtension.class) 24 | @SpringBootTest 25 | class PrometheusRSocketProxyMainTest { 26 | @Test 27 | public void contextLoads() { 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /starter-spring/build.gradle: -------------------------------------------------------------------------------- 1 | import org.springframework.boot.gradle.plugin.SpringBootPlugin 2 | 3 | plugins { 4 | id 'java-library' 5 | id 'org.springframework.boot' version '3.4.0' apply false 6 | } 7 | 8 | apply plugin: 'io.spring.dependency-management' 9 | 10 | repositories { 11 | mavenCentral() 12 | } 13 | 14 | dependencyManagement { 15 | imports { 16 | mavenBom SpringBootPlugin.BOM_COORDINATES 17 | } 18 | } 19 | 20 | dependencies { 21 | api 'io.micrometer:micrometer-registry-prometheus' 22 | 23 | implementation 'org.springframework.boot:spring-boot-actuator-autoconfigure' 24 | implementation 'org.springframework.boot:spring-boot-autoconfigure' 25 | implementation project(':prometheus-rsocket-client') 26 | implementation project(':prometheus-rsocket-proxy-server') 27 | 28 | implementation 'io.rsocket:rsocket-transport-netty' 29 | 30 | annotationProcessor 'org.springframework.boot:spring-boot-autoconfigure-processor' 31 | 32 | // to validate auto-completion on configuration properties 33 | annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' 34 | 35 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 36 | testImplementation 'io.projectreactor:reactor-test' 37 | testImplementation 'io.micrometer:micrometer-registry-prometheus' 38 | } 39 | 40 | test { 41 | useJUnitPlatform() 42 | } 43 | -------------------------------------------------------------------------------- /proxy/src/main/java/io/micrometer/prometheus/rsocket/PrometheusRSocketProxyMain.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket; 17 | 18 | import io.micrometer.prometheus.rsocket.autoconfigure.EnablePrometheusRSocketProxyServer; 19 | import io.micrometer.prometheus.rsocket.autoconfigure.PrometheusRSocketClientAutoConfiguration; 20 | import org.springframework.boot.SpringApplication; 21 | import org.springframework.boot.autoconfigure.SpringBootApplication; 22 | 23 | @SpringBootApplication(exclude = PrometheusRSocketClientAutoConfiguration.class) 24 | @EnablePrometheusRSocketProxyServer 25 | public class PrometheusRSocketProxyMain { 26 | public static void main(String[] args) { 27 | SpringApplication.run(PrometheusRSocketProxyMain.class, args); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /starter-spring/src/main/java/io/micrometer/prometheus/rsocket/autoconfigure/EnablePrometheusRSocketProxyServer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket.autoconfigure; 17 | 18 | import io.micrometer.prometheus.rsocket.PrometheusController; 19 | import org.springframework.context.annotation.Import; 20 | 21 | import java.lang.annotation.*; 22 | 23 | /** 24 | * Annotation to activate Prometheus RSocket Proxy Server related configuration. 25 | * {@link PrometheusController} 26 | * 27 | * @author Scott Steele 28 | * @author Doug Saus 29 | */ 30 | @Target(ElementType.TYPE) 31 | @Retention(RetentionPolicy.RUNTIME) 32 | @Documented 33 | @Import(PrometheusRSocketProxyServerMarkerConfiguration.class) 34 | public @interface EnablePrometheusRSocketProxyServer { 35 | 36 | } 37 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | } 5 | 6 | resolutionStrategy { 7 | eachPlugin { 8 | if (requested.id.id == 'org.springframework.boot') { 9 | useModule("org.springframework.boot:spring-boot-gradle-plugin:${requested.version}") 10 | } 11 | } 12 | } 13 | } 14 | 15 | plugins { 16 | id 'com.gradle.develocity' version '3.18' 17 | id 'io.spring.develocity.conventions' version '0.0.20' 18 | } 19 | 20 | rootProject.name = 'prometheus-rsocket-proxy' 21 | 22 | develocity { 23 | server = 'https://ge.micrometer.io' 24 | } 25 | 26 | // The build cache settings should be the following, but build cache is not enabled in gradle.properties at the moment 27 | buildCache { 28 | remote(develocity.buildCache) { 29 | server = 'https://ge.micrometer.io' 30 | } 31 | } 32 | 33 | include 'prometheus-rsocket-proxy' 34 | project(':prometheus-rsocket-proxy').projectDir = new File(rootProject.projectDir, 'proxy') 35 | 36 | include 'prometheus-rsocket-client' 37 | project(':prometheus-rsocket-client').projectDir = new File(rootProject.projectDir, 'client') 38 | 39 | include 'prometheus-rsocket-proxy-server' 40 | project(':prometheus-rsocket-proxy-server').projectDir = new File(rootProject.projectDir, 'proxy-server') 41 | 42 | include 'prometheus-rsocket-spring' 43 | project(':prometheus-rsocket-spring').projectDir = new File(rootProject.projectDir, 'starter-spring') 44 | -------------------------------------------------------------------------------- /starter-spring/src/main/java/io/micrometer/prometheus/rsocket/autoconfigure/PrometheusRSocketProxyServerMarkerConfiguration.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket.autoconfigure; 17 | 18 | import org.springframework.context.annotation.Bean; 19 | import org.springframework.context.annotation.Configuration; 20 | 21 | /** 22 | * A configuration class that supplies a marker bean used to trigger {@link PrometheusRSocketClientAutoConfiguration}. 23 | * 24 | * @author Scott Steele 25 | * @author Doug Saus 26 | */ 27 | @Configuration(proxyBeanMethods = false) 28 | class PrometheusRSocketProxyServerMarkerConfiguration { 29 | 30 | @Bean 31 | Marker prometheusRSocketProxyServerMarker() { 32 | return new Marker(); 33 | } 34 | 35 | static class Marker { 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /config/checkstyle/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /proxy-server/src/main/java/io/micrometer/prometheus/rsocket/PrometheusControllerProperties.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket; 17 | 18 | import org.springframework.boot.context.properties.ConfigurationProperties; 19 | 20 | /** 21 | * @author Christian Tzolov 22 | */ 23 | @ConfigurationProperties("micrometer.prometheus-proxy") 24 | public class PrometheusControllerProperties { 25 | 26 | /** 27 | * Proxy accept TCP port. 28 | */ 29 | private int tcpPort = 7001; 30 | 31 | /** 32 | * Proxy accept Websocket port. 33 | */ 34 | private int websocketPort = 8081; 35 | 36 | public int getTcpPort() { 37 | return tcpPort; 38 | } 39 | 40 | public void setTcpPort(int tcpPort) { 41 | this.tcpPort = tcpPort; 42 | } 43 | 44 | public int getWebsocketPort() { 45 | return websocketPort; 46 | } 47 | 48 | public void setWebsocketPort(int websocketPort) { 49 | this.websocketPort = websocketPort; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /scripts/kubernetes/prometheus/prometheus-statefulset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: StatefulSet 3 | metadata: 4 | name: prometheus 5 | namespace: monitoring-tools 6 | spec: 7 | replicas: 1 8 | serviceName: prometheus 9 | selector: 10 | matchLabels: 11 | app: prometheus 12 | template: 13 | metadata: 14 | labels: 15 | app: prometheus 16 | spec: 17 | serviceAccountName: monitoring-tools 18 | securityContext: 19 | fsGroup: 2000 20 | runAsNonRoot: true 21 | runAsUser: 1000 22 | containers: 23 | - name: prometheus 24 | image: prom/prometheus:v2.18.0 25 | args: 26 | - "--config.file=/etc/prometheus/prometheus.yml" 27 | - "--storage.tsdb.path=/prometheus/" 28 | - "--web.enable-lifecycle" 29 | - "--storage.tsdb.no-lockfile" 30 | ports: 31 | - name: prometheus 32 | containerPort: 9090 33 | volumeMounts: 34 | - mountPath: /etc/prometheus/ 35 | name: prometheus-config-volume 36 | - mountPath: /prometheus/ 37 | name: prometheus-data-volume 38 | volumes: 39 | - name: prometheus-config-volume 40 | configMap: 41 | defaultMode: 420 42 | name: prometheus-server-conf 43 | volumeClaimTemplates: 44 | - metadata: 45 | name: prometheus-data-volume 46 | spec: 47 | accessModes: 48 | - ReadWriteOnce 49 | resources: 50 | requests: 51 | storage: 250Gi 52 | storageClassName: faster 53 | 54 | -------------------------------------------------------------------------------- /scripts/kubernetes/prometheus/01-prometheus-configmap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: prometheus-server-conf 5 | labels: 6 | name: prometheus-server-conf 7 | namespace: monitoring-tools 8 | data: 9 | prometheus.yml: |- 10 | global: 11 | scrape_interval: 10s 12 | scrape_timeout: 9s 13 | evaluation_interval: 10s 14 | 15 | scrape_configs: 16 | - job_name: 'proxied-applications' 17 | metrics_path: '/metrics/connected' 18 | kubernetes_sd_configs: 19 | - role: pod 20 | namespaces: 21 | names: 22 | - monitoring-tools 23 | relabel_configs: 24 | - source_labels: [__meta_kubernetes_pod_label_app] 25 | action: keep 26 | regex: prometheus-proxy 27 | - source_labels: [__meta_kubernetes_pod_container_port_number] 28 | action: keep 29 | regex: 8080 30 | - job_name: 'proxies' 31 | metrics_path: '/metrics/proxy' 32 | kubernetes_sd_configs: 33 | - role: pod 34 | namespaces: 35 | names: 36 | - monitoring-tools 37 | relabel_configs: 38 | - source_labels: [__meta_kubernetes_pod_label_app] 39 | action: keep 40 | regex: prometheus-proxy 41 | - source_labels: [__meta_kubernetes_pod_container_port_number] 42 | action: keep 43 | regex: 8080 44 | - action: labelmap 45 | regex: __meta_kubernetes_pod_label_(.+) 46 | - source_labels: [__meta_kubernetes_pod_name] 47 | action: replace 48 | target_label: kubernetes_pod_name 49 | -------------------------------------------------------------------------------- /proxy/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '3.4.0' 3 | } 4 | 5 | apply plugin: 'io.spring.dependency-management' 6 | 7 | repositories { 8 | mavenCentral() 9 | } 10 | 11 | publishing { 12 | publications { 13 | nebula(MavenPublication) { 14 | artifacts { 15 | // ensure the Spring Boot jar gets published rather than the plain jar 16 | artifact bootJar 17 | artifact sourcesJar // because of bootJar, we need to put these back (sourcesJar and javadocJar) 18 | artifact javadocJar 19 | } 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 26 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 27 | implementation 'io.micrometer:micrometer-registry-prometheus' 28 | implementation project(':prometheus-rsocket-spring') 29 | 30 | implementation 'io.rsocket:rsocket-micrometer' 31 | implementation 'io.rsocket:rsocket-transport-netty' 32 | 33 | implementation 'org.xerial.snappy:snappy-java:latest.release' 34 | annotationProcessor "org.springframework.boot:spring-boot-configuration-processor" 35 | 36 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 37 | testImplementation 'io.projectreactor:reactor-test' 38 | } 39 | 40 | if (hasProperty('DOCKER_USER') && hasProperty('DOCKER_PASSWORD')) { 41 | bootBuildImage { 42 | imageName = "${findProperty('DOCKER_USER')}/prometheus-rsocket-proxy:${project.version}" 43 | environment = ["BP_JVM_VERSION" : "17.*"] 44 | docker { 45 | publishRegistry { 46 | username = findProperty('DOCKER_USER') 47 | password = findProperty('DOCKER_PASSWORD') 48 | email = 'tludwig@pivotal.io' 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /client/src/test/java/io/micrometer/prometheus/rsocket/SampleClient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket; 17 | 18 | import io.micrometer.core.instrument.Counter; 19 | import io.micrometer.prometheusmetrics.PrometheusConfig; 20 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 21 | import io.rsocket.transport.netty.client.WebsocketClientTransport; 22 | import reactor.core.publisher.Flux; 23 | import reactor.util.retry.Retry; 24 | 25 | import java.lang.management.ManagementFactory; 26 | import java.time.Duration; 27 | import java.util.Random; 28 | 29 | public class SampleClient { 30 | public static void main(String[] args) { 31 | PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); 32 | meterRegistry.config().commonTags("process.id", ManagementFactory.getRuntimeMXBean().getName()); 33 | 34 | PrometheusRSocketClient.build(meterRegistry, WebsocketClientTransport.create("localhost", 8081)) 35 | .retry(Retry.fixedDelay(3, Duration.ofSeconds(1))) 36 | .connect(); 37 | 38 | Random r = new Random(); 39 | 40 | Counter counter = meterRegistry.counter("my.counter", "instance", Integer.toString(r.nextInt(10))); 41 | Flux.interval(Duration.ofMillis(100)) 42 | .doOnEach(n -> counter.increment()) 43 | .blockLast(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /client/src/test/java/io/micrometer/prometheus/rsocket/SampleServerlessClient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket; 17 | 18 | import io.micrometer.core.instrument.Counter; 19 | import io.micrometer.prometheusmetrics.PrometheusConfig; 20 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 21 | import io.rsocket.transport.netty.client.TcpClientTransport; 22 | import reactor.core.Disposable; 23 | import reactor.core.publisher.Flux; 24 | 25 | import java.lang.management.ManagementFactory; 26 | import java.time.Duration; 27 | import java.util.Random; 28 | 29 | public class SampleServerlessClient { 30 | public static void main(String[] args) throws InterruptedException { 31 | PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); 32 | meterRegistry.config().commonTags("process.id", ManagementFactory.getRuntimeMXBean().getName()); 33 | 34 | PrometheusRSocketClient client = PrometheusRSocketClient 35 | .build(meterRegistry, TcpClientTransport.create("localhost", 7001)) 36 | .connect(); 37 | 38 | Random r = new Random(); 39 | 40 | Counter counter = meterRegistry.counter("my.counter", "instance", Integer.toString(r.nextInt(10))); 41 | 42 | Disposable counts = Flux.interval(Duration.ofMillis(100)) 43 | .doOnEach(n -> counter.increment()) 44 | .subscribe(); 45 | 46 | Thread.sleep(1000); 47 | 48 | client.pushAndClose(); 49 | counts.dispose(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /gradle/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | # This script will deploy the project artifacts. 3 | 4 | # Exit script if a statement returns a non-true return value. Fail fast. Fail the build. 5 | set -o errexit 6 | 7 | SWITCHES="-s --console=plain -x test" 8 | # circleci does not like multi-line values so they are base64 encoded 9 | ORG_GRADLE_PROJECT_SIGNING_KEY="$(echo "$ORG_GRADLE_PROJECT_SIGNING_KEY" | base64 -d)" 10 | 11 | if [ $CIRCLE_PR_NUMBER ]; then 12 | echo -e "WARN: Should not be here => Found Pull Request #$CIRCLE_PR_NUMBER => Branch [$CIRCLE_BRANCH]" 13 | echo -e "Not attempting to publish" 14 | elif [ -z $CIRCLE_TAG ]; then 15 | echo -e "Publishing Snapshot => Branch ['$CIRCLE_BRANCH']" 16 | ./gradlew -Prelease.stage=SNAPSHOT snapshot bootBuildImage --publishImage publishNebulaPublicationToSnapshotRepository $SWITCHES 17 | elif [ $CIRCLE_TAG ]; then 18 | echo -e "Publishing Release => Branch ['$CIRCLE_BRANCH'] Tag ['$CIRCLE_TAG']" 19 | case "$CIRCLE_TAG" in 20 | *-M*) 21 | ./gradlew -Prelease.disableGitChecks=true -Prelease.useLastTag=true -Prelease.stage=milestone candidate bootBuildImage --publishImage publishNebulaPublicationToMilestoneRepository $SWITCHES 22 | ;; 23 | *-RC*) 24 | # -Prelease.stage=milestone instead of rc (should be rc), probably related to this bug: https://github.com/nebula-plugins/nebula-release-plugin/issues/213 25 | ./gradlew -Prelease.disableGitChecks=true -Prelease.useLastTag=true -Prelease.stage=milestone candidate bootBuildImage --publishImage publishNebulaPublicationToMilestoneRepository $SWITCHES 26 | ;; 27 | *) 28 | ./gradlew -Prelease.disableGitChecks=true -Prelease.useLastTag=true -Prelease.stage=final final bootBuildImage --publishImage publishNebulaPublicationToMavenCentralRepository closeAndReleaseMavenCentralStagingRepository $SWITCHES 29 | ./gradlew -Prelease.disableGitChecks=true -Prelease.useLastTag=true -Prelease.stage=final final bootBuildImage --imageName=micrometermetrics/prometheus-rsocket-proxy:latest --publishImage $SWITCHES 30 | ;; 31 | esac 32 | else 33 | echo -e "WARN: Should not be here => Branch ['$CIRCLE_BRANCH'] Tag ['$CIRCLE_TAG'] Pull Request ['$CIRCLE_PR_NUMBER']" 34 | echo -e "Not attempting to publish" 35 | fi 36 | 37 | EXIT=$? 38 | 39 | exit $EXIT 40 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | executors: 4 | circle-jdk17-executor: 5 | working_directory: ~/prometheus-rsocket-proxy 6 | environment: 7 | GRADLE_OPTS: '-Dorg.gradle.jvmargs="-Xmx2048m -XX:+HeapDumpOnOutOfMemoryError"' 8 | docker: 9 | - image: cimg/openjdk:17.0.7 10 | 11 | jobs: 12 | build: 13 | executor: circle-jdk17-executor 14 | steps: 15 | - checkout 16 | 17 | - restore_cache: 18 | keys: 19 | - gradle-dependencies-{{ .Branch }}-{{ checksum "build.gradle" }} 20 | - gradle-dependencies-{{ .Branch }} 21 | 22 | - run: 23 | name: downloadDependencies 24 | command: ./gradlew downloadDependencies --console=plain 25 | 26 | - save_cache: 27 | key: gradle-dependencies-{{ .Branch }}-{{ checksum "build.gradle" }} 28 | paths: 29 | - ~/.gradle 30 | 31 | - run: 32 | name: run build 33 | command: ./gradlew build 34 | 35 | - run: 36 | name: collect test reports 37 | when: always 38 | command: | 39 | mkdir -p test-results/junit/ 40 | find . -type f -regex ".*/build/test-results/.*xml" -exec cp {} test-results/junit/ \; 41 | 42 | - store_test_results: 43 | path: test-results/ 44 | 45 | - store_artifacts: 46 | path: test-results/ 47 | 48 | deploy: 49 | executor: circle-jdk17-executor 50 | steps: 51 | - checkout 52 | - restore_cache: 53 | key: gradle-dependencies-{{ .Branch }}-{{ checksum "build.gradle" }} 54 | - setup_remote_docker 55 | - deploy: 56 | name: Deployment 57 | command: sh ./gradle/deploy.sh 58 | 59 | workflows: 60 | version: 2 61 | build_prs_deploy_snapshots: 62 | jobs: 63 | - build 64 | - deploy: 65 | context: 66 | - deploy 67 | requires: 68 | - build 69 | filters: 70 | branches: 71 | only: 72 | - main 73 | - /\d+\.\d+\.x/ 74 | build_deploy_releases: 75 | jobs: 76 | - build: 77 | filters: 78 | branches: 79 | ignore: /.*/ 80 | tags: 81 | only: /^v\d+\.\d+\.\d+(-(RC|M)\d+)?$/ 82 | - deploy: 83 | context: 84 | - deploy 85 | requires: 86 | - build 87 | filters: 88 | tags: 89 | only: /^v\d+\.\d+\.\d+(-(RC|M)\d+)?$/ 90 | -------------------------------------------------------------------------------- /client/src/test/java/io/micrometer/prometheus/rsocket/SampleClientThatClosesManually.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket; 17 | 18 | import io.micrometer.core.instrument.Counter; 19 | import io.micrometer.prometheusmetrics.PrometheusConfig; 20 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 21 | import io.rsocket.transport.netty.client.WebsocketClientTransport; 22 | import reactor.core.publisher.Flux; 23 | 24 | import java.lang.management.ManagementFactory; 25 | import java.time.Duration; 26 | import java.util.Random; 27 | import java.util.concurrent.CountDownLatch; 28 | import java.util.concurrent.TimeUnit; 29 | 30 | public class SampleClientThatClosesManually { 31 | public static void main(String[] args) throws InterruptedException { 32 | PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); 33 | meterRegistry.config().commonTags("process.id", ManagementFactory.getRuntimeMXBean().getName()); 34 | 35 | CountDownLatch keyLatch = new CountDownLatch(1); 36 | 37 | PrometheusRSocketClient client = PrometheusRSocketClient 38 | .build(meterRegistry, WebsocketClientTransport.create("localhost", 8081)) 39 | .doOnKeyReceived(keyLatch::countDown) 40 | .connect(); 41 | 42 | Random r = new Random(); 43 | 44 | Counter counter = meterRegistry.counter("my.counter", "instance", Integer.toString(r.nextInt(10))); 45 | counter.increment(); 46 | 47 | if (!keyLatch.await(10, TimeUnit.SECONDS)) { 48 | throw new IllegalStateException("Didn't receive a key within 10 seconds"); 49 | } 50 | 51 | client.pushAndClose(); 52 | 53 | if (!keyLatch.await(3, TimeUnit.SECONDS)) { 54 | throw new IllegalStateException("Not able to close within 3 seconds"); 55 | } 56 | 57 | // should no longer be able to respond to scrapes at this point 58 | Flux.interval(Duration.ofSeconds(1)).blockLast(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /starter-spring/src/main/java/io/micrometer/prometheus/rsocket/autoconfigure/PrometheusRSocketProxyServerAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket.autoconfigure; 17 | 18 | import io.micrometer.prometheus.rsocket.PrometheusController; 19 | import io.micrometer.prometheus.rsocket.PrometheusControllerProperties; 20 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 21 | import org.springframework.boot.autoconfigure.AutoConfiguration; 22 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 23 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 24 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 25 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 26 | import org.springframework.context.annotation.Bean; 27 | import org.springframework.context.annotation.Lazy; 28 | 29 | /** 30 | * Conditionally creates a {@link PrometheusController} bean if one does not already exist. 31 | * Creation is dependent on the presence of {@link PrometheusRSocketProxyServerMarkerConfiguration.Marker} 32 | * and {@link PrometheusMeterRegistry} beans. The marker can be created through the use of the 33 | * {@link EnablePrometheusRSocketProxyServer} annotation. 34 | * 35 | * @author Scott Steele 36 | * @author Doug Saus 37 | */ 38 | @AutoConfiguration 39 | @ConditionalOnClass(PrometheusMeterRegistry.class) 40 | @ConditionalOnBean(PrometheusRSocketProxyServerMarkerConfiguration.Marker.class) 41 | @EnableConfigurationProperties(PrometheusControllerProperties.class) 42 | @Lazy(value = false) 43 | class PrometheusRSocketProxyServerAutoConfiguration { 44 | 45 | @ConditionalOnMissingBean 46 | @Bean 47 | PrometheusController prometheusController(PrometheusMeterRegistry meterRegistry, PrometheusControllerProperties controllerProperties) { 48 | return new PrometheusController(meterRegistry, controllerProperties); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /starter-spring/src/main/java/io/micrometer/prometheus/rsocket/autoconfigure/PrometheusRSocketClientAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.micrometer.prometheus.rsocket.autoconfigure; 18 | 19 | import io.micrometer.prometheus.rsocket.PrometheusRSocketClient; 20 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 21 | import org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusMetricsExportAutoConfiguration; 22 | import org.springframework.boot.autoconfigure.AutoConfiguration; 23 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 24 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 25 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 26 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 27 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 28 | import org.springframework.context.annotation.Bean; 29 | import reactor.util.retry.Retry; 30 | 31 | @AutoConfiguration 32 | @AutoConfigureAfter(PrometheusMetricsExportAutoConfiguration.class) 33 | @ConditionalOnBean(PrometheusMeterRegistry.class) 34 | @ConditionalOnProperty(prefix = "micrometer.prometheus.rsocket", name = "enabled", havingValue = "true", matchIfMissing = true) 35 | @EnableConfigurationProperties(PrometheusRSocketClientProperties.class) 36 | public class PrometheusRSocketClientAutoConfiguration { 37 | 38 | @ConditionalOnMissingBean 39 | @Bean(destroyMethod = "pushAndCloseBlockingly") 40 | PrometheusRSocketClient prometheusRSocketClient(PrometheusMeterRegistry meterRegistry, PrometheusRSocketClientProperties properties) { 41 | return PrometheusRSocketClient.build(meterRegistry, properties.createClientTransport()) 42 | .retry(Retry.backoff(properties.getMaxRetries(), properties.getFirstBackoff()) 43 | .maxBackoff(properties.getMaxBackoff())) 44 | .timeout(properties.getTimeout()) 45 | .connectBlockingly(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /client/src/test/java/io/micrometer/prometheus/rsocket/SampleManyClients.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket; 17 | 18 | import ch.qos.logback.classic.Level; 19 | import ch.qos.logback.classic.Logger; 20 | import io.micrometer.core.instrument.Clock; 21 | import io.micrometer.prometheusmetrics.PrometheusConfig; 22 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 23 | import io.prometheus.metrics.model.registry.PrometheusRegistry; 24 | import io.rsocket.transport.netty.client.TcpClientTransport; 25 | import org.slf4j.LoggerFactory; 26 | import reactor.core.publisher.Flux; 27 | 28 | import java.time.Duration; 29 | import java.util.List; 30 | import java.util.stream.Collectors; 31 | import java.util.stream.IntStream; 32 | 33 | public class SampleManyClients { 34 | private static final int CLIENT_COUNT = 1000; 35 | private static final int ROW_COUNT = 1000; 36 | 37 | public static void main(String[] args) { 38 | ((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(Level.INFO); 39 | 40 | List registries = IntStream.range(0, CLIENT_COUNT) 41 | .mapToObj(n -> { 42 | PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT, new PrometheusRegistry(), Clock.SYSTEM); 43 | meterRegistry.config().commonTags("client.id", Integer.toString(n)); 44 | 45 | PrometheusRSocketClient.build(meterRegistry, TcpClientTransport.create("localhost", 7001)) 46 | .connect(); 47 | 48 | return meterRegistry; 49 | }) 50 | .collect(Collectors.toList()); 51 | 52 | Flux.interval(Duration.ofMillis(100)) 53 | .doOnEach(n -> { 54 | for (PrometheusMeterRegistry meterRegistry : registries) { 55 | for (int r = 0; r < ROW_COUNT; r++) { 56 | meterRegistry.counter("my.counter", "row", Integer.toString(r)).increment(); 57 | } 58 | } 59 | }) 60 | .blockLast(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guide 2 | 3 | This Contributing Guide is intended for those that would like to contribute to this repository. 4 | 5 | If you would like to use any of the published modules in your project, you can instead 6 | include the artifacts from the Maven Central repository using your build tool of choice or the published container images. 7 | 8 | ## Code of Conduct 9 | 10 | See [our Contributor Code of Conduct](https://github.com/micrometer-metrics/.github/blob/main/CODE_OF_CONDUCT.md). 11 | 12 | ## Contributions 13 | 14 | Contributions come in various forms and are not limited to code changes. The community benefits from 15 | contributions in all forms. 16 | 17 | For example, those with knowledge and experience can contribute by: 18 | 19 | * Answering [Stackoverflow questions](https://stackoverflow.com/tags/prometheus-rsocket-proxy) 20 | * Answering questions on the [Micrometer slack](https://slack.micrometer.io) 21 | * Share knowledge in other ways (e.g. presentations, blogs) 22 | 23 | The remainder of this document will focus on guidance for contributing code changes. It will help contributors to build, 24 | modify, or test the source code. 25 | 26 | ## Include a Signed Off By Trailer 27 | 28 | All commits must include a *Signed-off-by* trailer at the end of each commit message to indicate that the contributor agrees to the [Developer Certificate of Origin](https://developercertificate.org). 29 | For additional details, please refer to the blog post [Hello DCO, Goodbye CLA: Simplifying Contributions to Spring](https://spring.io/blog/2025/01/06/hello-dco-goodbye-cla-simplifying-contributions-to-spring). 30 | 31 | ## Getting the source 32 | 33 | The source code is hosted on GitHub at https://github.com/micrometer-metrics/prometheus-rsocket-proxy. You can use a 34 | Git client to clone the source code to your local machine. 35 | 36 | ## Building 37 | 38 | This project targets Java 17. 39 | 40 | The Gradle wrapper is provided and should be used for building with a consistent version of Gradle. 41 | 42 | The wrapper can be used with a command, for example, `./gradlew check` to build the project and check conventions. 43 | 44 | ## Importing into an IDE 45 | 46 | This repository should be imported as a Gradle project into your IDE of choice. 47 | 48 | ## Testing changes locally 49 | 50 | Specific modules or a test class can be run from your IDE for convenience. 51 | 52 | The Gradle `check` task depends on the `test` task, and so tests will be run as part of a build as described previously. 53 | 54 | ### Publishing local snapshots 55 | 56 | Run `./gradlew pTML` to publish a Maven-style snapshot to your Maven local repo. The build automatically calculates 57 | the "next" version for you when publishing snapshots. 58 | 59 | These local snapshots can be used in another project to test the changes. 60 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH= 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /starter-spring/src/test/java/io/micrometer/prometheus/rsocket/autoconfigure/PrometheusRSocketClientAutoConfigurationTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.micrometer.prometheus.rsocket.autoconfigure; 18 | 19 | import io.rsocket.Payload; 20 | import io.rsocket.RSocket; 21 | import io.rsocket.core.RSocketServer; 22 | import io.rsocket.frame.decoder.PayloadDecoder; 23 | import io.rsocket.transport.ServerTransport; 24 | import io.rsocket.transport.netty.server.CloseableChannel; 25 | import io.rsocket.transport.netty.server.TcpServerTransport; 26 | import io.rsocket.transport.netty.server.WebsocketServerTransport; 27 | import org.junit.jupiter.api.Test; 28 | import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration; 29 | import org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusMetricsExportAutoConfiguration; 30 | import org.springframework.boot.autoconfigure.AutoConfigurations; 31 | import org.springframework.boot.test.context.runner.ApplicationContextRunner; 32 | import org.springframework.test.util.TestSocketUtils; 33 | import reactor.core.publisher.Mono; 34 | 35 | import java.util.concurrent.CountDownLatch; 36 | import java.util.concurrent.TimeUnit; 37 | 38 | import static org.assertj.core.api.Assertions.assertThat; 39 | 40 | class PrometheusRSocketClientAutoConfigurationTest { 41 | private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() 42 | .withConfiguration(AutoConfigurations.of( 43 | MetricsAutoConfiguration.class, 44 | PrometheusMetricsExportAutoConfiguration.class, 45 | PrometheusRSocketClientAutoConfiguration.class 46 | )); 47 | 48 | private Mono startServer(ServerTransport serverTransport, CountDownLatch latch) { 49 | return RSocketServer.create() 50 | .payloadDecoder(PayloadDecoder.ZERO_COPY) 51 | .acceptor((setup, sendingSocket) -> { 52 | latch.countDown(); 53 | return Mono.just(new RSocket() { 54 | @Override 55 | public Mono fireAndForget(Payload payload) { 56 | return Mono.empty(); 57 | } 58 | }); 59 | }) 60 | .bind(serverTransport); 61 | } 62 | 63 | @Test 64 | void prometheusRSocketClientTcp() { 65 | int port = TestSocketUtils.findAvailableTcpPort(); 66 | CountDownLatch latch = new CountDownLatch(1); 67 | 68 | startServer(TcpServerTransport.create(port), latch).block(); 69 | 70 | contextRunner 71 | .withPropertyValues( 72 | "micrometer.prometheus.rsocket.port=" + port, 73 | "micrometer.prometheus.rsocket.transport=tcp" 74 | ) 75 | .run(context -> { 76 | latch.await(5, TimeUnit.SECONDS); 77 | assertThat(latch.getCount()).isEqualTo(0); 78 | }); 79 | } 80 | 81 | @Test 82 | void prometheusRSocketClientWebsocket() { 83 | int port = TestSocketUtils.findAvailableTcpPort(); 84 | CountDownLatch latch = new CountDownLatch(1); 85 | 86 | startServer(WebsocketServerTransport.create(port), latch).block(); 87 | 88 | contextRunner 89 | .withPropertyValues( 90 | "micrometer.prometheus.rsocket.port=" + port, 91 | "micrometer.prometheus.rsocket.transport=websocket" 92 | ) 93 | .run(context -> { 94 | latch.await(5, TimeUnit.SECONDS); 95 | assertThat(latch.getCount()).isEqualTo(0); 96 | }); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /starter-spring/src/main/java/io/micrometer/prometheus/rsocket/autoconfigure/PrometheusRSocketClientProperties.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.micrometer.prometheus.rsocket.autoconfigure; 18 | 19 | import io.rsocket.transport.ClientTransport; 20 | import io.rsocket.transport.netty.client.TcpClientTransport; 21 | import io.rsocket.transport.netty.client.WebsocketClientTransport; 22 | import org.springframework.boot.context.properties.ConfigurationProperties; 23 | import org.springframework.boot.convert.DurationUnit; 24 | import reactor.netty.http.client.HttpClient; 25 | import reactor.netty.tcp.TcpClient; 26 | 27 | import java.time.Duration; 28 | import java.time.temporal.ChronoUnit; 29 | 30 | @ConfigurationProperties("micrometer.prometheus.rsocket") 31 | public class PrometheusRSocketClientProperties { 32 | 33 | /** 34 | * The host name of the proxy to connect to. 35 | */ 36 | private String host = "localhost"; 37 | 38 | /** 39 | * The port to make a connection on. 40 | */ 41 | private int port = 7001; 42 | 43 | /** 44 | * The maximum number of connection attempts to make. 45 | */ 46 | private long maxRetries = Long.MAX_VALUE; 47 | 48 | /** 49 | * The first connection attempt backoff delay to apply, then grow exponentially. 50 | */ 51 | private Duration firstBackoff = Duration.ofSeconds(10); 52 | 53 | /** 54 | * The maximum connection attempt delay to apply despite exponential growth. 55 | */ 56 | private Duration maxBackoff = Duration.ofMinutes(10); 57 | 58 | /** 59 | * RSocket transport protocol. 60 | */ 61 | private Transport transport = Transport.TCP; 62 | 63 | /** 64 | * Whether to use a secured protocol. 65 | */ 66 | private boolean secure = false; 67 | 68 | /** 69 | * The timeout to be used for establishing the connection and pushing the data 70 | */ 71 | @DurationUnit(ChronoUnit.SECONDS) 72 | private Duration timeout = Duration.ofSeconds(5); 73 | 74 | public long getMaxRetries() { 75 | return maxRetries; 76 | } 77 | 78 | public void setMaxRetries(long maxRetries) { 79 | this.maxRetries = maxRetries; 80 | } 81 | 82 | public Duration getFirstBackoff() { 83 | return firstBackoff; 84 | } 85 | 86 | public void setFirstBackoff(Duration firstBackoff) { 87 | this.firstBackoff = firstBackoff; 88 | } 89 | 90 | public Duration getMaxBackoff() { 91 | return maxBackoff; 92 | } 93 | 94 | public void setMaxBackoff(Duration maxBackoff) { 95 | this.maxBackoff = maxBackoff; 96 | } 97 | 98 | public String getHost() { 99 | return host; 100 | } 101 | 102 | public void setHost(String host) { 103 | this.host = host; 104 | } 105 | 106 | public int getPort() { 107 | return port; 108 | } 109 | 110 | public void setPort(int port) { 111 | this.port = port; 112 | } 113 | 114 | public Transport getTransport() { 115 | return transport; 116 | } 117 | 118 | public void setTransport(Transport transport) { 119 | this.transport = transport; 120 | } 121 | 122 | public void setSecure(boolean secure) { 123 | this.secure = secure; 124 | } 125 | 126 | public boolean isSecure() { 127 | return secure; 128 | } 129 | 130 | public Duration getTimeout() { 131 | return timeout; 132 | } 133 | 134 | public void setTimeout(Duration timeout) { 135 | this.timeout = timeout; 136 | } 137 | 138 | ClientTransport createClientTransport() { 139 | final TcpClient tcpClient = TcpClient.create().host(this.host).port(this.port); 140 | return this.transport.create(this.secure ? tcpClient.secure() : tcpClient); 141 | } 142 | 143 | /** 144 | * Choice of transport protocol for the RSocket server. 145 | */ 146 | enum Transport { 147 | 148 | /** 149 | * TCP transport protocol. 150 | */ 151 | TCP { 152 | @Override 153 | ClientTransport create(TcpClient tcpClient) { 154 | return TcpClientTransport.create(tcpClient); 155 | } 156 | }, 157 | 158 | /** 159 | * WebSocket transport protocol. 160 | */ 161 | WEBSOCKET { 162 | @Override 163 | ClientTransport create(TcpClient tcpClient) { 164 | return WebsocketClientTransport.create(HttpClient.from(tcpClient), "/"); 165 | } 166 | }; 167 | 168 | abstract ClientTransport create(TcpClient tcpClient); 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![CircleCI](https://circleci.com/gh/micrometer-metrics/prometheus-rsocket-proxy.svg?style=svg)](https://circleci.com/gh/micrometer-metrics/prometheus-rsocket-proxy) 2 | [![Maven Central](https://img.shields.io/maven-central/v/io.micrometer.prometheus/prometheus-rsocket-proxy.svg)](https://mvnrepository.com/artifact/io.micrometer.prometheus/prometheus-rsocket-proxy) 3 | 4 | # Prometheus RSocket Proxy 5 | 6 | This is a collection of resources to help you get application metrics to Prometheus when you cannot open ingress into your application while still preserving the pull model, using [RSocket](https://rsocket.io) bidirectional persistent RPC. 7 | 8 | ## Basic operation 9 | 10 | The approach works like this: 11 | 12 | 1. An application makes a TCP RSocket connection to an RSocket proxy or cluster of proxies (the connection is effectively delegated by the load balancer to some instance/pod in the proxy cluster). Once the RSocket connection is established, the distinction between "server" and "client" disappears, so the proxy is able to act as the requester when pulling metrics from each application instance. 13 | 2. Prometheus is configured to scrape the `/metrics/connected` and `/metrics/proxy` endpoints of the proxy(ies) and not the application instances. 14 | 3. When the proxy receives a scrape request from Prometheus, it pulls metrics from each RSocket connection using a [request/response](https://rsocket.io/docs/Protocol#stream-sequences-request-response) sequence. The results of each connection are concatenated into one response for presentation to Prometheus. 15 | 16 | The proxy sends a public key to the application instance for it to encrypt the metrics payload on each scrape. 17 | 18 | Clients automatically reconnect, so the bidirectional connection doesn't have to be durable over a long period of time for metrics to still get out. Because clients reconnect, the proxy cluster itself can be configured to horizontally autoscale or rebalance connections without fear of disrupting connected applications. 19 | 20 | ## Use in application code 21 | 22 | Include the dependency: 23 | 24 | ``` 25 | implementation 'io.micrometer.prometheus:prometheus-rsocket-client:VERSION' 26 | ``` 27 | 28 | or 29 | 30 | ```xml 31 | io.micrometer.prometheus 32 | prometheus-rsocket-client 33 | VERSION 34 | ``` 35 | 36 | ### Manually configuring 37 | 38 | ```java 39 | PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); 40 | 41 | PrometheusRSocketClient client = PrometheusRSocketClient 42 | .build(meterRegistry, TcpClientTransport.create("proxyhost", 7001)) 43 | .connect(); 44 | 45 | // it isn't strictly necessary to close the client 46 | client.close(); 47 | ``` 48 | 49 | ### Spring Boot auto-configuration 50 | 51 | Include the following dependency: 52 | 53 | ```groovy 54 | implementation 'io.micrometer.prometheus:prometheus-rsocket-spring:VERSION' 55 | ``` 56 | 57 | or 58 | 59 | ```xml 60 | io.micrometer.prometheus 61 | prometheus-rsocket-spring 62 | VERSION 63 | ``` 64 | 65 | This will autoconfigure the Micrometer `PrometheusMeterRegistry`, a `PrometheusRSocketClient`, and a call to `pushAndClose` on application shutdown. The client will be configured to retry failing connections to the proxy. Retrying can be tuned with: 66 | 67 | ```yml 68 | micrometer.prometheus.rsocket: 69 | host: YOURPROXYHOSTHERE #required 70 | port: 7001 71 | max-retries: 10000 # default is Long.MAX_VALUE 72 | first-backoff: 10s 73 | max-backoff: 10m 74 | ``` 75 | 76 | ## Support for short-lived or serverless applications 77 | 78 | Use `pushAndClose()` on the `PrometheusRSocketClient` in a shutdown hook for short-lived and serverless applications. This performs a [fire-and-forget](https://rsocket.io/docs/Protocol#stream-sequences-fire-and-forget) push of metrics to the proxy, which will hold them until the next scrape by Prometheus. In this way, you do not need to set up [Pushgateway](https://github.com/prometheus/pushgateway). The same RSocket proxy serves the needs of both long-lived and short-lived applications. 79 | 80 | ```java 81 | PrometheusRSocketClient client = PrometheusRSocketClient 82 | .build(meterRegistry, TcpClientTransport.create("proxyhost", 7001)) 83 | .connect(); 84 | 85 | // in a shutdown hook 86 | client.pushAndClose(); 87 | ``` 88 | 89 | ## One client for multiple `PrometheusMeterRegistry` instances 90 | 91 | Use the alternate build method to concatenate results from multiple `PrometheusMeterRegistry` instances. You might have multiple instances when you create a different registry for different components of your application with different common tags, etc. 92 | 93 | ```java 94 | PrometheusMeterRegistry topLevelRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); 95 | new JvmGcMetrics().bind(topLevelRegistry); 96 | 97 | PrometheusMeterRegistry comp1Registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); 98 | comp1Registry.config().commonTags("component", "comp1"); 99 | 100 | PrometheusMeterRegistry comp2Registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); 101 | comp1Registry.config().commonTags("component", "comp2"); 102 | 103 | PrometheusRSocketClient client = PrometheusRSocketClient 104 | .build( 105 | topLevelRegistry, 106 | () -> topLevelRegistry.scrape() + "\n" + comp1Registry.scrape() + "\n" + comp2Registry.scrape(), 107 | TcpClientTransport.create("proxyhost", 7001) 108 | ) 109 | .connect(); 110 | ``` 111 | 112 | ## Installing on Kubernetes (GKE) 113 | 114 | This installation includes Prometheus and Grafana as well. 115 | 116 | 1. `kubectl apply -f scripts/kubernetes/proxy/` (`kubectl get svc -n monitoring-tools` to see external IP) 117 | 1. `kubectl apply -f scripts/kubernetes/prometheus/` 118 | 3. `kubectl apply -f scripts/kubernetes/grafana` 119 | 120 | ## Expected performance 121 | 122 | A 3-pod deployment easily handles 1,000 connected application instances each serving 1,000 distinct time series with <1vCPU and <3Gi RAM total on GKE. 123 | 124 | ![Proxy Grafana Dashboard](doc/proxy-grafana.png) 125 | 126 | The scrape performance for each pod is <3s per interval. 127 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH="\\\"\\\"" 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /client/src/test/java/io/micrometer/prometheus/rsocket/PrometheusRSocketClientTests.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket; 17 | 18 | import io.micrometer.prometheusmetrics.PrometheusConfig; 19 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 20 | import io.rsocket.Payload; 21 | import io.rsocket.RSocket; 22 | import io.rsocket.core.RSocketServer; 23 | import io.rsocket.frame.decoder.PayloadDecoder; 24 | import io.rsocket.transport.local.LocalClientTransport; 25 | import io.rsocket.transport.local.LocalServerTransport; 26 | import io.rsocket.util.DefaultPayload; 27 | import io.rsocket.util.EmptyPayload; 28 | import org.junit.jupiter.api.Test; 29 | import reactor.core.publisher.Mono; 30 | import reactor.core.scheduler.Schedulers; 31 | import reactor.util.retry.Retry; 32 | 33 | import java.lang.reflect.Field; 34 | import java.security.KeyPairGenerator; 35 | import java.security.NoSuchAlgorithmException; 36 | import java.time.Duration; 37 | import java.util.concurrent.CompletableFuture; 38 | import java.util.concurrent.CountDownLatch; 39 | import java.util.concurrent.ExecutionException; 40 | import java.util.concurrent.Executor; 41 | import java.util.concurrent.ScheduledThreadPoolExecutor; 42 | import java.util.concurrent.TimeUnit; 43 | import java.util.concurrent.atomic.AtomicBoolean; 44 | import java.util.concurrent.atomic.AtomicReference; 45 | 46 | import static java.util.concurrent.CompletableFuture.runAsync; 47 | import static java.util.concurrent.CompletableFuture.supplyAsync; 48 | import static java.util.concurrent.Executors.newSingleThreadExecutor; 49 | import static java.util.concurrent.TimeUnit.MILLISECONDS; 50 | import static java.util.concurrent.TimeUnit.SECONDS; 51 | import static org.assertj.core.api.Assertions.assertThat; 52 | 53 | class PrometheusRSocketClientTests { 54 | 55 | LocalServerTransport serverTransport = LocalServerTransport.createEphemeral(); 56 | 57 | PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); 58 | 59 | @Test 60 | void reconnection() throws InterruptedException { 61 | LocalServerTransport serverTransport = LocalServerTransport.createEphemeral(); 62 | serverTransport.start(connection -> { 63 | connection.dispose(); 64 | return Mono.empty(); 65 | }); 66 | 67 | LocalClientTransport local = LocalClientTransport.create("local"); 68 | 69 | CountDownLatch reconnectionAttemptLatch = new CountDownLatch(3); 70 | 71 | PrometheusRSocketClient.build(meterRegistry, local) 72 | .retry(Retry.fixedDelay(10, Duration.ofMillis(5)).doAfterRetry(retry -> reconnectionAttemptLatch.countDown())) 73 | .connect(); 74 | 75 | assertThat(reconnectionAttemptLatch.await(1, SECONDS)).isTrue(); 76 | assertThat(meterRegistry.get("prometheus.connection.retry").summary().count()).isGreaterThanOrEqualTo(3); 77 | } 78 | 79 | @Test 80 | void doesntAttemptReconnectWhenPushAndClose() throws InterruptedException { 81 | CountDownLatch connectionLatch = new CountDownLatch(3); 82 | 83 | RSocketServer.create() 84 | .payloadDecoder(PayloadDecoder.ZERO_COPY) 85 | .acceptor((setup, sendingSocket) -> { 86 | connectionLatch.countDown(); 87 | return Mono.empty(); 88 | }) 89 | .bind(serverTransport) 90 | .block(); 91 | 92 | PrometheusRSocketClient client = PrometheusRSocketClient.build(meterRegistry, serverTransport.clientTransport()) 93 | .retry(Retry.max(3)) 94 | .connect(); 95 | 96 | client.pushAndClose(); 97 | 98 | assertThat(connectionLatch.await(1, SECONDS)).isFalse(); 99 | assertThat(connectionLatch.getCount()).isEqualTo(2); 100 | } 101 | 102 | /** 103 | * See https://github.com/micrometer-metrics/prometheus-rsocket-proxy/issues/3 104 | */ 105 | @Test 106 | void dyingScrapeAfterNormalScrape() throws NoSuchAlgorithmException, InterruptedException { 107 | CountDownLatch dyingScrapeLatch = new CountDownLatch(1); 108 | Payload payload = DefaultPayload.create(KeyPairGenerator.getInstance("RSA").generateKeyPair().getPublic().getEncoded()); 109 | AtomicReference serverSocket = new AtomicReference<>(); 110 | 111 | RSocketServer.create() 112 | .payloadDecoder(PayloadDecoder.ZERO_COPY) 113 | .acceptor((setup, sendingSocket) -> { 114 | // normal scrape 115 | serverSocket.set(sendingSocket); 116 | sendingSocket.requestResponse(payload).subscribe(); 117 | 118 | return Mono.just(new RSocket() { 119 | 120 | @Override 121 | public Mono requestResponse(Payload payload) { 122 | dyingScrapeLatch.countDown(); 123 | return Mono.just(EmptyPayload.INSTANCE); 124 | } 125 | 126 | @Override 127 | public Mono fireAndForget(Payload payload) { 128 | dyingScrapeLatch.countDown(); 129 | return Mono.empty(); 130 | } 131 | }); 132 | }) 133 | .bind(serverTransport) 134 | .block(); 135 | 136 | CountDownLatch normalScrapeLatch = new CountDownLatch(1); 137 | 138 | PrometheusRSocketClient client = PrometheusRSocketClient 139 | .build( 140 | meterRegistry, 141 | () -> { 142 | normalScrapeLatch.countDown(); 143 | return meterRegistry.scrape(); 144 | }, 145 | serverTransport.clientTransport() 146 | ) 147 | .retry(Retry.max(0)) 148 | .connectBlockingly(); 149 | 150 | assertThat(normalScrapeLatch.await(1, SECONDS)).isTrue(); 151 | 152 | // trigger dying scrape 153 | client.pushAndCloseBlockingly(); 154 | assertThat(dyingScrapeLatch.await(1, TimeUnit.SECONDS)) 155 | .as("Dying scrape should be successfully called") 156 | .isTrue(); 157 | 158 | // after pushAndClose(), the client should no longer be scrapable 159 | Boolean failed = serverSocket.get() 160 | .requestResponse(payload) 161 | .map(response -> false) 162 | .onErrorReturn(true) 163 | .block(Duration.ofSeconds(10)); 164 | 165 | assertThat(failed).isTrue(); 166 | } 167 | 168 | @Test 169 | void blockingConnectAndPush() throws NoSuchAlgorithmException, InterruptedException, ExecutionException, NoSuchFieldException, IllegalAccessException { 170 | CountDownLatch pushLatch = new CountDownLatch(1); 171 | AtomicBoolean pushed = new AtomicBoolean(false); 172 | Payload payload = DefaultPayload.create(KeyPairGenerator.getInstance("RSA").generateKeyPair().getPublic().getEncoded()); 173 | RSocketServer.create() 174 | .payloadDecoder(PayloadDecoder.ZERO_COPY) 175 | .acceptor((setup, sendingSocket) -> { 176 | sendingSocket.requestResponse(payload) 177 | .subscribeOn(Schedulers.newSingle("server-polls")) 178 | .subscribe(); 179 | 180 | return Mono.just(new RSocket() { 181 | @Override 182 | public Mono requestResponse(Payload payload) { 183 | return Mono.defer(() -> { 184 | await(pushLatch); 185 | pushed.set(true); 186 | return Mono.just(EmptyPayload.INSTANCE); 187 | }) 188 | .map(p -> (Payload) p) 189 | .subscribeOn(Schedulers.newSingle("server-polls")); 190 | } 191 | }); 192 | }) 193 | .bind(serverTransport) 194 | .block(); 195 | 196 | CountDownLatch keyReceivedLatch = new CountDownLatch(1); 197 | AtomicBoolean keyReceived = new AtomicBoolean(false); 198 | PrometheusRSocketClient.Builder clientBuilder = PrometheusRSocketClient.build( 199 | meterRegistry, 200 | () -> "", 201 | serverTransport.clientTransport() 202 | ) 203 | .retry(Retry.max(0)) 204 | .timeout(Duration.ofSeconds(10)) 205 | .doOnKeyReceived(() -> { 206 | await(keyReceivedLatch); 207 | keyReceived.set(true); 208 | }); 209 | 210 | CompletableFuture clientFuture = supplyAsync(clientBuilder::connectBlockingly, newSingleThreadExecutor()); 211 | runAsync(keyReceivedLatch::countDown, newDelayedExecutor()); 212 | assertThat(keyReceived).as("Public key should not be received (not connected)").isFalse(); 213 | PrometheusRSocketClient client = clientFuture.get(); 214 | assertThat(keyReceived).as("Public key should be received(connected)").isTrue(); 215 | 216 | Field timeoutField = PrometheusRSocketClient.class.getDeclaredField("timeout"); 217 | timeoutField.setAccessible(true); 218 | Duration timeout = (Duration)timeoutField.get(client); 219 | assertThat(timeout.toSeconds()).isEqualTo(10L); 220 | 221 | CompletableFuture closeFuture = runAsync(client::pushAndCloseBlockingly, newSingleThreadExecutor()); 222 | runAsync(pushLatch::countDown, newDelayedExecutor()); 223 | assertThat(pushed).as("Data should not be pushed").isFalse(); 224 | closeFuture.get(); 225 | assertThat(pushed).as("Data should be pushed").isTrue(); 226 | } 227 | 228 | private Executor newDelayedExecutor() { 229 | return runnable -> new ScheduledThreadPoolExecutor(1).schedule(runnable, 200, MILLISECONDS); 230 | } 231 | 232 | private void await(CountDownLatch latch) { 233 | try { 234 | if (!latch.await(5, SECONDS)) { 235 | throw new RuntimeException("Latch timed out, there might be a problem with the test setup."); 236 | } 237 | } 238 | catch (InterruptedException e) { 239 | throw new RuntimeException(e); 240 | } 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /proxy-server/src/main/java/io/micrometer/prometheus/rsocket/PrometheusController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket; 17 | 18 | import io.micrometer.core.instrument.Counter; 19 | import io.micrometer.core.instrument.DistributionSummary; 20 | import io.micrometer.core.instrument.Tags; 21 | import io.micrometer.core.instrument.Timer; 22 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 23 | import io.netty.buffer.ByteBuf; 24 | import io.netty.buffer.ByteBufUtil; 25 | import io.rsocket.Payload; 26 | import io.rsocket.RSocket; 27 | import io.rsocket.core.RSocketServer; 28 | import io.rsocket.frame.decoder.PayloadDecoder; 29 | import io.rsocket.micrometer.MicrometerRSocketInterceptor; 30 | import io.rsocket.transport.netty.server.TcpServerTransport; 31 | import io.rsocket.transport.netty.server.WebsocketServerTransport; 32 | import io.rsocket.util.DefaultPayload; 33 | import org.springframework.stereotype.Controller; 34 | import org.springframework.web.bind.annotation.GetMapping; 35 | import org.springframework.web.bind.annotation.RestController; 36 | 37 | import io.rsocket.util.EmptyPayload; 38 | import org.xerial.snappy.Snappy; 39 | import reactor.core.publisher.Flux; 40 | import reactor.core.publisher.Mono; 41 | 42 | import jakarta.annotation.PostConstruct; 43 | import javax.crypto.Cipher; 44 | import javax.crypto.SecretKey; 45 | import javax.crypto.spec.SecretKeySpec; 46 | import java.io.IOException; 47 | import java.io.UncheckedIOException; 48 | import java.nio.channels.ClosedChannelException; 49 | import java.security.*; 50 | import java.security.spec.PKCS8EncodedKeySpec; 51 | import java.util.Map; 52 | import java.util.concurrent.ConcurrentHashMap; 53 | import java.util.stream.Collectors; 54 | 55 | /** 56 | * A {@link Controller} for endpoints to be scraped by Prometheus. 57 | * 58 | * @author Jon Schneider 59 | * @author Christian Tzolov 60 | */ 61 | @RestController 62 | public class PrometheusController { 63 | private final PrometheusMeterRegistry meterRegistry; 64 | private final Timer scrapeTimerSuccess; 65 | private final Timer scrapeTimerClosed; 66 | private final DistributionSummary scrapePayload; 67 | private final MicrometerRSocketInterceptor metricsInterceptor; 68 | private final PrometheusControllerProperties properties; 69 | private final Map scrapableApps = new ConcurrentHashMap<>(); 70 | 71 | public PrometheusController(PrometheusMeterRegistry meterRegistry, PrometheusControllerProperties properties) { 72 | this.meterRegistry = meterRegistry; 73 | this.metricsInterceptor = new MicrometerRSocketInterceptor(meterRegistry); 74 | this.properties = properties; 75 | meterRegistry.gaugeMapSize("prometheus.proxy.scrape.active.connections", Tags.empty(), scrapableApps); 76 | this.scrapeTimerSuccess = Timer.builder("prometheus.proxy.scrape") 77 | .tag("outcome", "success") 78 | .tag("exception", "none") 79 | .register(meterRegistry); 80 | this.scrapeTimerClosed = Timer.builder("prometheus.proxy.scrape") 81 | .tag("outcome", "closed") 82 | .tag("exception", "none") 83 | .register(meterRegistry); 84 | this.scrapePayload = DistributionSummary.builder("prometheus.proxy.scrape.payload") 85 | .baseUnit("bytes") 86 | .register(meterRegistry); 87 | } 88 | 89 | @PostConstruct 90 | public void connect() throws NoSuchAlgorithmException { 91 | KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); 92 | 93 | RSocketServer.create() 94 | .payloadDecoder(PayloadDecoder.ZERO_COPY) 95 | .acceptor((setup, sendingSocket) -> acceptRSocket(generator, sendingSocket)) 96 | .bind(TcpServerTransport.create(this.properties.getTcpPort())) 97 | .doOnError(t -> { 98 | Counter.builder("prometheus.proxy.connection.error") 99 | .tag("exception", t.getClass().getName()) 100 | .tag("transport", "TCP") 101 | .register(meterRegistry) 102 | .increment(); 103 | }) 104 | .subscribe(); 105 | 106 | RSocketServer.create() 107 | .payloadDecoder(PayloadDecoder.ZERO_COPY) 108 | .acceptor((setup, sendingSocket) -> acceptRSocket(generator, sendingSocket)) 109 | .bind(WebsocketServerTransport.create(this.properties.getWebsocketPort())) 110 | .doOnError(t -> { 111 | Counter.builder("prometheus.proxy.connection.error") 112 | .tag("exception", t.getClass().getName()) 113 | .tag("transport", "Websocket") 114 | .register(meterRegistry) 115 | .increment(); 116 | }) 117 | .subscribe(); 118 | } 119 | 120 | private Mono acceptRSocket(KeyPairGenerator generator, RSocket sendingSocket) { 121 | // respond with Mono.error(..) to 122 | RSocket metricsInterceptedSendingSocket = metricsInterceptor.apply(sendingSocket); 123 | 124 | ConnectionState connectionState = new ConnectionState(generator.generateKeyPair()); 125 | scrapableApps.put(metricsInterceptedSendingSocket, connectionState); 126 | 127 | // a key to be used by the client to push metrics as it's dying if this happens before the first scrape 128 | //noinspection CallingSubscribeInNonBlockingScope 129 | metricsInterceptedSendingSocket.fireAndForget(connectionState.createKeyPayload()).subscribe(); 130 | 131 | return Mono.just(new RSocket() { 132 | @Override 133 | public Mono requestResponse(Payload payload) { 134 | try { 135 | connectionState.setDyingPush(connectionState.receiveScrapePayload(payload, null)); 136 | } catch (Throwable t) { 137 | t.printStackTrace(); 138 | } 139 | return Mono.just(EmptyPayload.INSTANCE); 140 | } 141 | 142 | @Override 143 | public Mono fireAndForget(Payload payload) { 144 | try { 145 | connectionState.setDyingPush(connectionState.receiveScrapePayload(payload, null)); 146 | } catch (Throwable t) { 147 | t.printStackTrace(); 148 | } 149 | return Mono.empty(); 150 | } 151 | }); 152 | } 153 | 154 | @GetMapping(value = "/metrics/proxy", produces = "text/plain") 155 | public Mono proxyMetrics() { 156 | return Mono.just(meterRegistry.scrape()); 157 | } 158 | 159 | @GetMapping(value = "/metrics/connected", produces = "text/plain") 160 | public Mono prometheus() { 161 | return Flux 162 | .fromIterable(scrapableApps.entrySet()) 163 | .flatMap(socketAndState -> { 164 | ConnectionState connectionState = socketAndState.getValue(); 165 | RSocket rsocket = socketAndState.getKey(); 166 | Timer.Sample sample = Timer.start(); 167 | return rsocket 168 | .requestResponse(connectionState.createKeyPayload()) 169 | .map(payload -> connectionState.receiveScrapePayload(payload, sample)) 170 | .onErrorResume(throwable -> { 171 | scrapableApps.remove(rsocket); 172 | 173 | if (throwable instanceof ClosedChannelException) { 174 | sample.stop(scrapeTimerClosed); 175 | } else { 176 | sample.stop(meterRegistry.timer("prometheus.proxy.scrape", 177 | "outcome", "error", 178 | "exception", throwable.getMessage())); 179 | } 180 | 181 | return connectionState.getDyingPush(); 182 | }); 183 | }) 184 | .collect(Collectors.joining("\n")); 185 | } 186 | 187 | class ConnectionState { 188 | private final KeyPair keyPair; 189 | 190 | // the last metrics of a dying application instance 191 | private String dyingPush; 192 | 193 | ConnectionState(KeyPair keyPair) { 194 | this.keyPair = keyPair; 195 | } 196 | 197 | Mono getDyingPush() { 198 | return Mono.justOrEmpty(dyingPush); 199 | } 200 | 201 | void setDyingPush(String dyingPush) { 202 | this.dyingPush = dyingPush; 203 | } 204 | 205 | String receiveScrapePayload(Payload payload, Timer.Sample timing) { 206 | try { 207 | ByteBuf sliceMetadata = payload.sliceMetadata(); 208 | ByteBuf sliceData = payload.sliceData(); 209 | byte[] decrypted = decrypt(keyPair, 210 | ByteBufUtil.getBytes(sliceMetadata, sliceMetadata.readerIndex(), sliceMetadata.readableBytes(), false), 211 | ByteBufUtil.getBytes(sliceData, sliceData.readerIndex(), sliceData.readableBytes(), false)); 212 | 213 | String uncompressed = Snappy.uncompressString(decrypted); 214 | scrapePayload.record(uncompressed.length()); 215 | return uncompressed; 216 | } catch (IOException e) { 217 | throw new UncheckedIOException(e); 218 | } finally { 219 | payload.release(); 220 | if (timing != null) { 221 | timing.stop(scrapeTimerSuccess); 222 | } 223 | } 224 | } 225 | 226 | private byte[] decrypt(KeyPair keyPair, byte[] encryptedKey, byte[] data) { 227 | try { 228 | PrivateKey privateKey = KeyFactory.getInstance("RSA") 229 | .generatePrivate(new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded())); 230 | 231 | Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); 232 | cipher.init(Cipher.PRIVATE_KEY, privateKey); 233 | byte[] decryptedKey = cipher.doFinal(encryptedKey); 234 | 235 | SecretKey originalKey = new SecretKeySpec(decryptedKey, 0, decryptedKey.length, "AES"); 236 | Cipher aesCipher = Cipher.getInstance("AES"); 237 | aesCipher.init(Cipher.DECRYPT_MODE, originalKey); 238 | 239 | return aesCipher.doFinal(data); 240 | } catch (Throwable e) { 241 | throw new IllegalStateException(e); 242 | } 243 | } 244 | 245 | Payload createKeyPayload() { 246 | return DefaultPayload.create(keyPair.getPublic().getEncoded()); 247 | } 248 | } 249 | } 250 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | https://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 | https://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 | -------------------------------------------------------------------------------- /scripts/grafana-dashboard.json: -------------------------------------------------------------------------------- 1 | { 2 | "annotations": { 3 | "list": [ 4 | { 5 | "$$hashKey": "object:35", 6 | "builtIn": 1, 7 | "datasource": "-- Grafana --", 8 | "enable": true, 9 | "hide": true, 10 | "iconColor": "rgba(0, 211, 255, 1)", 11 | "name": "Annotations & Alerts", 12 | "type": "dashboard" 13 | } 14 | ] 15 | }, 16 | "editable": true, 17 | "gnetId": null, 18 | "graphTooltip": 0, 19 | "links": [], 20 | "panels": [ 21 | { 22 | "aliasColors": {}, 23 | "bars": false, 24 | "dashLength": 10, 25 | "dashes": false, 26 | "datasource": null, 27 | "fill": 0, 28 | "fillGradient": 0, 29 | "gridPos": { 30 | "h": 8, 31 | "w": 11, 32 | "x": 0, 33 | "y": 0 34 | }, 35 | "hiddenSeries": false, 36 | "id": 10, 37 | "legend": { 38 | "avg": false, 39 | "current": false, 40 | "max": false, 41 | "min": false, 42 | "show": true, 43 | "total": false, 44 | "values": false 45 | }, 46 | "lines": true, 47 | "linewidth": 2, 48 | "nullPointMode": "null", 49 | "options": { 50 | "dataLinks": [] 51 | }, 52 | "percentage": false, 53 | "pointradius": 2, 54 | "points": false, 55 | "renderer": "flot", 56 | "seriesOverrides": [], 57 | "spaceLength": 10, 58 | "stack": false, 59 | "steppedLine": true, 60 | "targets": [ 61 | { 62 | "expr": "prometheus_proxy_unrecognized_rsocket_total", 63 | "legendFormat": "{{kubernetes_pod_name}}", 64 | "refId": "A" 65 | } 66 | ], 67 | "thresholds": [], 68 | "timeFrom": null, 69 | "timeRegions": [], 70 | "timeShift": null, 71 | "title": "Unrecognized RSockets", 72 | "tooltip": { 73 | "shared": true, 74 | "sort": 0, 75 | "value_type": "individual" 76 | }, 77 | "type": "graph", 78 | "xaxis": { 79 | "buckets": null, 80 | "mode": "time", 81 | "name": null, 82 | "show": true, 83 | "values": [] 84 | }, 85 | "yaxes": [ 86 | { 87 | "format": "short", 88 | "label": null, 89 | "logBase": 1, 90 | "max": null, 91 | "min": null, 92 | "show": true 93 | }, 94 | { 95 | "format": "short", 96 | "label": null, 97 | "logBase": 1, 98 | "max": null, 99 | "min": null, 100 | "show": true 101 | } 102 | ], 103 | "yaxis": { 104 | "align": false, 105 | "alignLevel": null 106 | } 107 | }, 108 | { 109 | "aliasColors": {}, 110 | "bars": false, 111 | "dashLength": 10, 112 | "dashes": false, 113 | "datasource": null, 114 | "fill": 7, 115 | "fillGradient": 0, 116 | "gridPos": { 117 | "h": 8, 118 | "w": 12, 119 | "x": 11, 120 | "y": 0 121 | }, 122 | "hiddenSeries": false, 123 | "id": 6, 124 | "interval": "", 125 | "legend": { 126 | "alignAsTable": true, 127 | "avg": false, 128 | "current": true, 129 | "max": true, 130 | "min": false, 131 | "show": true, 132 | "total": false, 133 | "values": true 134 | }, 135 | "lines": true, 136 | "linewidth": 2, 137 | "nullPointMode": "null", 138 | "options": { 139 | "dataLinks": [] 140 | }, 141 | "percentage": false, 142 | "pointradius": 2, 143 | "points": false, 144 | "renderer": "flot", 145 | "seriesOverrides": [ 146 | { 147 | "alias": "complete", 148 | "color": "#73BF69" 149 | }, 150 | { 151 | "alias": "cancel", 152 | "color": "#FADE2A" 153 | }, 154 | { 155 | "alias": "error", 156 | "color": "#F2495C", 157 | "fill": 0, 158 | "lines": false, 159 | "points": true 160 | } 161 | ], 162 | "spaceLength": 10, 163 | "stack": true, 164 | "steppedLine": true, 165 | "targets": [ 166 | { 167 | "expr": "sum(rate(rsocket_request_response_seconds_count{signal_type=\"ON_COMPLETE\"}[1m]))", 168 | "legendFormat": "complete", 169 | "refId": "B" 170 | }, 171 | { 172 | "expr": "sum(rate(rsocket_request_response_seconds_count{signal_type=\"CANCEL\"}[1m]))", 173 | "legendFormat": "cancel", 174 | "refId": "C" 175 | }, 176 | { 177 | "expr": "sum(rate(rsocket_request_response_seconds_count{signal_type=\"ON_ERROR\"}[1m]))", 178 | "legendFormat": "error", 179 | "refId": "A" 180 | } 181 | ], 182 | "thresholds": [], 183 | "timeFrom": null, 184 | "timeRegions": [], 185 | "timeShift": null, 186 | "title": "RSocket Request/Responses", 187 | "tooltip": { 188 | "shared": true, 189 | "sort": 0, 190 | "value_type": "individual" 191 | }, 192 | "type": "graph", 193 | "xaxis": { 194 | "buckets": null, 195 | "mode": "time", 196 | "name": null, 197 | "show": true, 198 | "values": [] 199 | }, 200 | "yaxes": [ 201 | { 202 | "format": "ops", 203 | "label": "requests", 204 | "logBase": 1, 205 | "max": null, 206 | "min": null, 207 | "show": true 208 | }, 209 | { 210 | "format": "short", 211 | "label": null, 212 | "logBase": 1, 213 | "max": null, 214 | "min": null, 215 | "show": true 216 | } 217 | ], 218 | "yaxis": { 219 | "align": false, 220 | "alignLevel": null 221 | } 222 | }, 223 | { 224 | "aliasColors": {}, 225 | "bars": false, 226 | "dashLength": 10, 227 | "dashes": false, 228 | "datasource": null, 229 | "fill": 7, 230 | "fillGradient": 0, 231 | "gridPos": { 232 | "h": 8, 233 | "w": 11, 234 | "x": 0, 235 | "y": 8 236 | }, 237 | "hiddenSeries": false, 238 | "id": 8, 239 | "legend": { 240 | "alignAsTable": true, 241 | "avg": false, 242 | "current": true, 243 | "max": true, 244 | "min": false, 245 | "show": true, 246 | "total": false, 247 | "values": true 248 | }, 249 | "lines": true, 250 | "linewidth": 2, 251 | "nullPointMode": "null", 252 | "options": { 253 | "dataLinks": [] 254 | }, 255 | "percentage": false, 256 | "pointradius": 2, 257 | "points": false, 258 | "renderer": "flot", 259 | "seriesOverrides": [ 260 | { 261 | "alias": "success", 262 | "color": "#73BF69" 263 | }, 264 | { 265 | "alias": "closed", 266 | "color": "#FADE2A" 267 | }, 268 | { 269 | "alias": "error", 270 | "color": "#F2495C", 271 | "fill": 0, 272 | "lines": false, 273 | "points": true 274 | } 275 | ], 276 | "spaceLength": 10, 277 | "stack": true, 278 | "steppedLine": true, 279 | "targets": [ 280 | { 281 | "expr": "sum(rate(prometheus_proxy_scrape_seconds_count{outcome=\"success\"}[1m]))", 282 | "legendFormat": "success", 283 | "refId": "A" 284 | }, 285 | { 286 | "expr": "sum(rate(prometheus_proxy_scrape_seconds_count{outcome=\"closed\"}[1m]))", 287 | "legendFormat": "closed", 288 | "refId": "B" 289 | }, 290 | { 291 | "expr": "sum(rate(prometheus_proxy_scrape_seconds_count{outcome=\"error\"}[1m]))", 292 | "legendFormat": "error", 293 | "refId": "C" 294 | } 295 | ], 296 | "thresholds": [], 297 | "timeFrom": null, 298 | "timeRegions": [], 299 | "timeShift": null, 300 | "title": "Prometheus Scrapes of Individual Processes by Outcome", 301 | "tooltip": { 302 | "shared": true, 303 | "sort": 0, 304 | "value_type": "individual" 305 | }, 306 | "type": "graph", 307 | "xaxis": { 308 | "buckets": null, 309 | "mode": "time", 310 | "name": null, 311 | "show": true, 312 | "values": [] 313 | }, 314 | "yaxes": [ 315 | { 316 | "format": "ops", 317 | "label": "scrapes", 318 | "logBase": 1, 319 | "max": null, 320 | "min": null, 321 | "show": true 322 | }, 323 | { 324 | "format": "short", 325 | "label": null, 326 | "logBase": 1, 327 | "max": null, 328 | "min": null, 329 | "show": true 330 | } 331 | ], 332 | "yaxis": { 333 | "align": false, 334 | "alignLevel": null 335 | } 336 | }, 337 | { 338 | "aliasColors": {}, 339 | "bars": false, 340 | "dashLength": 10, 341 | "dashes": false, 342 | "datasource": null, 343 | "fill": 0, 344 | "fillGradient": 0, 345 | "gridPos": { 346 | "h": 8, 347 | "w": 12, 348 | "x": 11, 349 | "y": 8 350 | }, 351 | "hiddenSeries": false, 352 | "id": 2, 353 | "legend": { 354 | "avg": false, 355 | "current": false, 356 | "max": false, 357 | "min": false, 358 | "show": true, 359 | "total": false, 360 | "values": false 361 | }, 362 | "lines": true, 363 | "linewidth": 2, 364 | "nullPointMode": "null", 365 | "options": { 366 | "dataLinks": [] 367 | }, 368 | "percentage": false, 369 | "pointradius": 2, 370 | "points": false, 371 | "renderer": "flot", 372 | "seriesOverrides": [], 373 | "spaceLength": 10, 374 | "stack": false, 375 | "steppedLine": true, 376 | "targets": [ 377 | { 378 | "expr": "prometheus_proxy_scrape_active_connections", 379 | "legendFormat": "{{kubernetes_pod_name}}", 380 | "refId": "A" 381 | } 382 | ], 383 | "thresholds": [], 384 | "timeFrom": null, 385 | "timeRegions": [], 386 | "timeShift": null, 387 | "title": "Active Connections", 388 | "tooltip": { 389 | "shared": true, 390 | "sort": 0, 391 | "value_type": "individual" 392 | }, 393 | "type": "graph", 394 | "xaxis": { 395 | "buckets": null, 396 | "mode": "time", 397 | "name": null, 398 | "show": true, 399 | "values": [] 400 | }, 401 | "yaxes": [ 402 | { 403 | "format": "short", 404 | "label": "connections", 405 | "logBase": 1, 406 | "max": null, 407 | "min": null, 408 | "show": true 409 | }, 410 | { 411 | "format": "short", 412 | "label": null, 413 | "logBase": 1, 414 | "max": null, 415 | "min": null, 416 | "show": true 417 | } 418 | ], 419 | "yaxis": { 420 | "align": false, 421 | "alignLevel": null 422 | } 423 | }, 424 | { 425 | "aliasColors": {}, 426 | "bars": false, 427 | "dashLength": 10, 428 | "dashes": false, 429 | "datasource": null, 430 | "fill": 0, 431 | "fillGradient": 0, 432 | "gridPos": { 433 | "h": 8, 434 | "w": 11, 435 | "x": 0, 436 | "y": 16 437 | }, 438 | "hiddenSeries": false, 439 | "id": 4, 440 | "legend": { 441 | "alignAsTable": true, 442 | "avg": false, 443 | "current": false, 444 | "max": true, 445 | "min": false, 446 | "rightSide": false, 447 | "show": true, 448 | "total": false, 449 | "values": true 450 | }, 451 | "lines": true, 452 | "linewidth": 2, 453 | "nullPointMode": "null", 454 | "options": { 455 | "dataLinks": [] 456 | }, 457 | "percentage": false, 458 | "pointradius": 2, 459 | "points": false, 460 | "renderer": "flot", 461 | "seriesOverrides": [ 462 | { 463 | "alias": "count", 464 | "fill": 4, 465 | "linewidth": 0, 466 | "yaxis": 2 467 | } 468 | ], 469 | "spaceLength": 10, 470 | "stack": false, 471 | "steppedLine": true, 472 | "targets": [ 473 | { 474 | "expr": "prometheus_proxy_scrape_payload_bytes_max", 475 | "legendFormat": "{{kubernetes_pod_name}}", 476 | "refId": "A" 477 | }, 478 | { 479 | "expr": "sum(rate(prometheus_proxy_scrape_payload_bytes_count[1m]))", 480 | "legendFormat": "count", 481 | "refId": "B" 482 | } 483 | ], 484 | "thresholds": [], 485 | "timeFrom": null, 486 | "timeRegions": [], 487 | "timeShift": null, 488 | "title": "Maximum Scrape Payload", 489 | "tooltip": { 490 | "shared": true, 491 | "sort": 0, 492 | "value_type": "individual" 493 | }, 494 | "type": "graph", 495 | "xaxis": { 496 | "buckets": null, 497 | "mode": "time", 498 | "name": null, 499 | "show": true, 500 | "values": [] 501 | }, 502 | "yaxes": [ 503 | { 504 | "format": "decbytes", 505 | "label": "scrape payload size", 506 | "logBase": 1, 507 | "max": null, 508 | "min": "0", 509 | "show": true 510 | }, 511 | { 512 | "format": "ops", 513 | "label": "scrape throughput", 514 | "logBase": 1, 515 | "max": null, 516 | "min": null, 517 | "show": true 518 | } 519 | ], 520 | "yaxis": { 521 | "align": false, 522 | "alignLevel": null 523 | } 524 | } 525 | ], 526 | "refresh": "10s", 527 | "schemaVersion": 22, 528 | "style": "dark", 529 | "tags": [], 530 | "templating": { 531 | "list": [] 532 | }, 533 | "time": { 534 | "from": "now-15m", 535 | "to": "now" 536 | }, 537 | "timepicker": { 538 | "refresh_intervals": [ 539 | "5s", 540 | "10s", 541 | "30s", 542 | "1m", 543 | "5m", 544 | "15m", 545 | "30m", 546 | "1h", 547 | "2h", 548 | "1d" 549 | ] 550 | }, 551 | "timezone": "", 552 | "title": "Prometheus Proxy", 553 | "uid": "5sancpjZk", 554 | "variables": { 555 | "list": [] 556 | }, 557 | "version": 1 558 | } -------------------------------------------------------------------------------- /client/src/main/java/io/micrometer/prometheus/rsocket/PrometheusRSocketClient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2019 Pivotal Software, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.micrometer.prometheus.rsocket; 17 | 18 | import io.micrometer.core.instrument.Counter; 19 | import io.micrometer.core.instrument.DistributionSummary; 20 | import io.micrometer.core.instrument.MeterRegistry; 21 | import io.micrometer.core.lang.Nullable; 22 | import io.micrometer.core.util.internal.logging.InternalLogger; 23 | import io.micrometer.core.util.internal.logging.InternalLoggerFactory; 24 | import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; 25 | import io.rsocket.Payload; 26 | import io.rsocket.RSocket; 27 | import io.rsocket.core.RSocketConnector; 28 | import io.rsocket.transport.ClientTransport; 29 | import io.rsocket.util.DefaultPayload; 30 | import org.reactivestreams.Publisher; 31 | import org.xerial.snappy.Snappy; 32 | import reactor.core.publisher.Flux; 33 | import reactor.core.publisher.Mono; 34 | import reactor.util.retry.Retry; 35 | 36 | import javax.crypto.Cipher; 37 | import javax.crypto.KeyGenerator; 38 | import javax.crypto.SecretKey; 39 | import java.nio.ByteBuffer; 40 | import java.nio.charset.StandardCharsets; 41 | import java.security.KeyFactory; 42 | import java.security.NoSuchAlgorithmException; 43 | import java.security.PublicKey; 44 | import java.security.spec.InvalidKeySpecException; 45 | import java.security.spec.X509EncodedKeySpec; 46 | import java.time.Duration; 47 | import java.util.concurrent.CountDownLatch; 48 | import java.util.concurrent.atomic.AtomicReference; 49 | import java.util.function.Supplier; 50 | 51 | import static java.util.concurrent.TimeUnit.MILLISECONDS; 52 | 53 | /** 54 | * Establishes a persistent bidirectional RSocket connection to a Prometheus RSocket proxy. 55 | * Prometheus scrapes each proxy instance. Proxies in turn use the connection to pull metrics 56 | * from each client. 57 | */ 58 | public class PrometheusRSocketClient { 59 | private static final InternalLogger LOGGER = InternalLoggerFactory.getInstance(PrometheusRSocketClient.class); 60 | private final MeterRegistryAndScrape registryAndScrape; 61 | 62 | private volatile RSocket connection; 63 | private AtomicReference latestKey = new AtomicReference<>(); 64 | 65 | private volatile boolean requestedDisconnect = false; 66 | private RSocket sendingSocket; 67 | 68 | private Duration timeout; 69 | 70 | /** 71 | * Creates a {@link PrometheusRSocketClient}. 72 | * 73 | * @param registryAndScrape the registry and scrape meter 74 | * @param transport the client transport 75 | * @param retry the retry configuration 76 | * @param onKeyReceived the callback if a key has been received 77 | */ 78 | private PrometheusRSocketClient(MeterRegistryAndScrape registryAndScrape, 79 | ClientTransport transport, 80 | Retry retry, 81 | Runnable onKeyReceived) { 82 | this(registryAndScrape, transport, retry, Duration.ofSeconds(5), onKeyReceived); 83 | } 84 | 85 | /** 86 | * Creates a {@link PrometheusRSocketClient}. 87 | * 88 | * @param registryAndScrape the registry and scrape meter 89 | * @param transport the client transport 90 | * @param retry the retry configuration 91 | * @param timeout the timeout to connect and push the data 92 | * @param onKeyReceived the callback if a key has been received 93 | */ 94 | private PrometheusRSocketClient(MeterRegistryAndScrape registryAndScrape, 95 | ClientTransport transport, 96 | Retry retry, 97 | Duration timeout, 98 | Runnable onKeyReceived) { 99 | this.registryAndScrape = registryAndScrape; 100 | this.timeout = timeout; 101 | 102 | RSocketConnector.create() 103 | .reconnect(new Retry() { 104 | @Override 105 | public Publisher generateCompanion(Flux retrySignals) { 106 | return retry.generateCompanion(retrySignals 107 | .doOnNext(retrySignal -> { 108 | Throwable failure = retrySignal.failure(); 109 | DistributionSummary.builder("prometheus.connection.retry") 110 | .description("Attempts at retrying an RSocket connection to the Prometheus proxy") 111 | .baseUnit("retries") 112 | .tag("exception", failure.getCause() != null ? failure.getCause().getMessage() : failure.getMessage()) 113 | .register(registryAndScrape.registry) 114 | .record(retrySignal.totalRetries()); 115 | } 116 | ) 117 | ); 118 | } 119 | }) 120 | .acceptor((payload, r) -> { 121 | this.sendingSocket = r; 122 | return Mono.just(new RSocket() { 123 | @Override 124 | public Mono requestResponse(Payload payload) { 125 | PublicKey key = decodePublicKey(payload.getData()); 126 | latestKey.set(key); 127 | onKeyReceived.run(); 128 | return Mono.fromCallable(() -> scrapePayload(key)); 129 | } 130 | 131 | @Override 132 | public Mono fireAndForget(Payload payload) { 133 | latestKey.set(decodePublicKey(payload.getData())); 134 | onKeyReceived.run(); 135 | return Mono.empty(); 136 | } 137 | }); 138 | }) 139 | .connect(transport) 140 | .doOnError(t -> Counter.builder("prometheus.connection.error") 141 | .baseUnit("errors") 142 | .tag("exception", t.getClass().getSimpleName() == null ? t.getClass().getName() : t.getClass().getSimpleName()) 143 | .register(registryAndScrape.registry) 144 | .increment()) 145 | .doOnNext(connection -> this.connection = connection) 146 | .flatMap(socket -> socket.onClose() 147 | .map(v -> 1) // https://github.com/rsocket/rsocket-java/issues/819 148 | .onErrorReturn(1)) 149 | .repeat(() -> !requestedDisconnect) 150 | .subscribe(); 151 | } 152 | 153 | /** 154 | * The most common case is that you want to both register proxy client metrics to a {@link PrometheusMeterRegistry} and 155 | * also scrape from that registry. 156 | * 157 | * @param prometheusMeterRegistry The registry to scrape metrics from and also publish client metrics to. 158 | * @param clientTransport The transport to connect to the proxy server with. 159 | * @return The client, connecting asynchronously at the point of return. 160 | */ 161 | public static Builder build(PrometheusMeterRegistry prometheusMeterRegistry, ClientTransport clientTransport) { 162 | return new Builder(prometheusMeterRegistry, prometheusMeterRegistry::scrape, clientTransport); 163 | } 164 | 165 | /** 166 | * A generalization of {@link #build(PrometheusMeterRegistry, ClientTransport)} where you define the scrape function yourself. 167 | * This is useful when, for example, you want to concatenate scrapes from several {@link PrometheusMeterRegistry} instances, 168 | * perhaps each with different common tags for different parts of the application, and present these together as the scrape. 169 | * 170 | * @param meterRegistry The registry to publish client metrics to. 171 | * @param scrape A scrape in the Prometheus format used. 172 | * @param clientTransport The transport to connect to the proxy server with. 173 | * @param The type of registry to publish client metrics to. 174 | * @return The client, connecting asynchronously at the point of return. 175 | */ 176 | public static Builder build(M meterRegistry, Supplier scrape, ClientTransport clientTransport) { 177 | return new Builder(meterRegistry, scrape, clientTransport); 178 | } 179 | 180 | /** 181 | * Closes the {@link PrometheusRSocketClient} 182 | */ 183 | public void close() { 184 | this.requestedDisconnect = true; 185 | if (this.connection != null) { 186 | this.connection.dispose(); 187 | } 188 | } 189 | 190 | /** 191 | * Pushes the data in a blocking way and closes the connection. 192 | */ 193 | public void pushAndCloseBlockingly() { 194 | pushAndCloseBlockingly(timeout); 195 | } 196 | 197 | /** 198 | * Pushes the data in a blocking way and closes the connection. 199 | * 200 | * @param timeout the amount of time to wait for the data to be sent 201 | */ 202 | public void pushAndCloseBlockingly(Duration timeout) { 203 | LOGGER.debug("Pushing data to RSocket Proxy before closing the connection..."); 204 | CountDownLatch latch = new CountDownLatch(1); 205 | PublicKey key = latestKey.get(); 206 | if (key != null) { 207 | try { 208 | sendingSocket 209 | // This should be requestResponse instead of fireAndForget 210 | // since the latter will almost immediately emit the complete signal (before anything happens on the wire) 211 | // so waiting for it to terminate does not make too much sense; more details: https://github.com/micrometer-metrics/prometheus-rsocket-proxy/pull/54 212 | .requestResponse(scrapePayload(key)) 213 | .doOnSuccess(payload -> LOGGER.info("Pushing data to RSocket Proxy before closing the connection was successful!")) 214 | .doOnError(throwable -> LOGGER.warn("Pushing data to RSocket Proxy before closing the connection failed!", throwable)) 215 | .doOnCancel(() -> LOGGER.warn("Pushing data to RSocket Proxy before closing the connection was cancelled!")) 216 | .doFinally(signalType -> latch.countDown()) 217 | .subscribe(); 218 | } catch (Exception exception) { 219 | latch.countDown(); 220 | LOGGER.warn("Sending the payload failed!", exception); 221 | } 222 | 223 | try { 224 | if (!latch.await(timeout.toMillis(), MILLISECONDS)) { 225 | LOGGER.warn("Sending the payload timed out!"); 226 | } 227 | } catch (InterruptedException exception) { 228 | LOGGER.warn("Waiting for sending the payload was interrupted!", exception); 229 | } 230 | } 231 | close(); 232 | } 233 | 234 | /** 235 | * Pushes the data asynchronously (non-blocking) and closes the connection. 236 | */ 237 | public void pushAndClose() { 238 | LOGGER.debug("Pushing data to RSocket Proxy before closing the connection..."); 239 | PublicKey key = latestKey.get(); 240 | if (key != null) { 241 | try { 242 | sendingSocket 243 | .fireAndForget(scrapePayload(key)) 244 | .doOnSuccess(payload -> LOGGER.info("Pushing data to RSocket Proxy before closing the connection was successful!")) 245 | .doOnError(throwable -> LOGGER.warn("Pushing data to RSocket Proxy before closing the connection failed!", throwable)) 246 | .doOnCancel(() -> LOGGER.warn("Pushing data to RSocket Proxy before closing the connection was cancelled!")) 247 | .subscribe(); 248 | } catch (Exception exception) { 249 | LOGGER.warn("Sending the payload failed!", exception); 250 | } 251 | } 252 | close(); 253 | } 254 | 255 | private Payload scrapePayload(@Nullable PublicKey publicKey) throws Exception { 256 | String scrape = registryAndScrape.scrape(); 257 | 258 | if (publicKey == null) { 259 | return DefaultPayload.create(scrape, "plaintext"); 260 | } 261 | 262 | KeyGenerator generator = KeyGenerator.getInstance("AES"); 263 | generator.init(128); 264 | SecretKey secKey = generator.generateKey(); 265 | 266 | Cipher aesCipher = Cipher.getInstance("AES"); 267 | aesCipher.init(Cipher.ENCRYPT_MODE, secKey); 268 | byte[] encryptedMetrics = aesCipher.doFinal(Snappy.compress(scrape)); 269 | 270 | Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); 271 | cipher.init(Cipher.PUBLIC_KEY, publicKey); 272 | byte[] encryptedPublicKey = cipher.doFinal(secKey.getEncoded()); 273 | 274 | return DefaultPayload.create(encryptedMetrics, encryptedPublicKey); 275 | } 276 | 277 | @Nullable 278 | private PublicKey decodePublicKey(ByteBuffer encodedKeyBuffer) { 279 | byte[] encodedKey = new byte[encodedKeyBuffer.capacity()]; 280 | encodedKeyBuffer.get(encodedKey); 281 | 282 | if ("plaintext".equals(new String(encodedKey, StandardCharsets.UTF_8))) { 283 | return null; 284 | } 285 | 286 | X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey); 287 | try { 288 | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 289 | return keyFactory.generatePublic(keySpec); 290 | } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { 291 | throw new IllegalStateException(e); 292 | } 293 | } 294 | 295 | /** 296 | * Builder class to create a {@link PrometheusRSocketClient}. 297 | */ 298 | public static class Builder { 299 | private MeterRegistryAndScrape registryAndScrape; 300 | private final ClientTransport clientTransport; 301 | 302 | private Retry retry = Retry.backoff(Long.MAX_VALUE, Duration.ofSeconds(10)) 303 | .maxBackoff(Duration.ofMinutes(10)); 304 | 305 | private Duration timeout = Duration.ofSeconds(5); 306 | 307 | private Runnable onKeyReceived = () -> { 308 | }; 309 | 310 | Builder(M registry, Supplier scrape, ClientTransport clientTransport) { 311 | this.registryAndScrape = new MeterRegistryAndScrape<>(registry, scrape); 312 | this.clientTransport = clientTransport; 313 | } 314 | 315 | /** 316 | * Configures the retry for {@link PrometheusRSocketClient}. 317 | * 318 | * @param retry the retry configuration 319 | * @return the {@link Builder} 320 | */ 321 | public Builder retry(Retry retry) { 322 | this.retry = retry; 323 | return this; 324 | } 325 | 326 | /** 327 | * Timeout for the {@link PrometheusRSocketClient}. 328 | * 329 | * @param timeout the timeout in seconds 330 | * @return the {@link Builder} 331 | */ 332 | public Builder timeout(Duration timeout) { 333 | this.timeout = timeout; 334 | return this; 335 | } 336 | 337 | /** 338 | * Callback of {@link PrometheusRSocketClient} if a key is received. 339 | * 340 | * @param onKeyReceived callback which is executed if a key is received 341 | * @return the {@link Builder} 342 | */ 343 | public Builder doOnKeyReceived(Runnable onKeyReceived) { 344 | this.onKeyReceived = onKeyReceived; 345 | return this; 346 | } 347 | 348 | /** 349 | * Connects the {@link PrometheusRSocketClient}. 350 | * 351 | * @return the {@link PrometheusRSocketClient} 352 | */ 353 | public PrometheusRSocketClient connect() { 354 | return connect(timeout); 355 | } 356 | 357 | /** 358 | * Connects the {@link PrometheusRSocketClient}. 359 | * 360 | * @param timeout the timeout for the client to connect 361 | * 362 | * @return the {@link PrometheusRSocketClient} 363 | */ 364 | public PrometheusRSocketClient connect(Duration timeout) { 365 | LOGGER.debug("Connecting to RSocket Proxy..."); 366 | return new PrometheusRSocketClient( 367 | registryAndScrape, 368 | clientTransport, 369 | retry, 370 | timeout, 371 | () -> { 372 | LOGGER.info("Connected to RSocket Proxy!"); 373 | onKeyReceived.run(); 374 | } 375 | ); 376 | } 377 | 378 | /** 379 | * Connects the {@link PrometheusRSocketClient} blockingly. 380 | * 381 | * @return the {@link PrometheusRSocketClient} 382 | */ 383 | public PrometheusRSocketClient connectBlockingly() { 384 | return connectBlockingly(timeout); 385 | } 386 | 387 | /** 388 | * Connects the {@link PrometheusRSocketClient} blockingly with the given timeout. 389 | * 390 | * @return the {@link PrometheusRSocketClient} 391 | */ 392 | public PrometheusRSocketClient connectBlockingly(Duration timeout) { 393 | LOGGER.debug("Connecting to RSocket Proxy..."); 394 | CountDownLatch latch = new CountDownLatch(1); 395 | PrometheusRSocketClient client = new PrometheusRSocketClient( 396 | registryAndScrape, 397 | clientTransport, 398 | retry, 399 | timeout, 400 | () -> { 401 | LOGGER.info("Connected to RSocket Proxy!"); 402 | onKeyReceived.run(); 403 | latch.countDown(); 404 | } 405 | ); 406 | 407 | try { 408 | if (!latch.await(timeout.toMillis(), MILLISECONDS)) { 409 | LOGGER.warn("Creating the connection and receiving the key timed out!"); 410 | } 411 | } catch (InterruptedException exception) { 412 | LOGGER.warn("Waiting for receiving the key was interrupted!", exception); 413 | } 414 | 415 | return client; 416 | } 417 | } 418 | 419 | private static class MeterRegistryAndScrape { 420 | final M registry; 421 | final Supplier scrape; 422 | 423 | private MeterRegistryAndScrape(M registry, Supplier scrape) { 424 | this.registry = registry; 425 | this.scrape = scrape; 426 | } 427 | 428 | String scrape() { 429 | return scrape.get(); 430 | } 431 | } 432 | } 433 | --------------------------------------------------------------------------------