├── .circleci └── config.yml ├── .gitignore ├── LICENSE ├── PrometheusSink.md ├── README.md ├── build.sbt ├── maven-repo └── releases │ └── com │ └── banzaicloud │ └── spark-metrics_2.11 │ └── 2.2.1-1.0.0 │ ├── spark-metrics_2.11-2.2.1-1.0.0-javadoc.jar │ ├── spark-metrics_2.11-2.2.1-1.0.0-javadoc.jar.md5 │ ├── spark-metrics_2.11-2.2.1-1.0.0-javadoc.jar.sha1 │ ├── spark-metrics_2.11-2.2.1-1.0.0-sources.jar │ ├── spark-metrics_2.11-2.2.1-1.0.0-sources.jar.md5 │ ├── spark-metrics_2.11-2.2.1-1.0.0-sources.jar.sha1 │ ├── spark-metrics_2.11-2.2.1-1.0.0.jar │ ├── spark-metrics_2.11-2.2.1-1.0.0.jar.md5 │ ├── spark-metrics_2.11-2.2.1-1.0.0.jar.sha1 │ ├── spark-metrics_2.11-2.2.1-1.0.0.pom │ ├── spark-metrics_2.11-2.2.1-1.0.0.pom.md5 │ └── spark-metrics_2.11-2.2.1-1.0.0.pom.sha1 ├── project ├── build.properties └── plugins.sbt └── src ├── main └── scala │ ├── com │ └── banzaicloud │ │ └── spark │ │ └── metrics │ │ ├── CollectorDecorator.scala │ │ ├── DeduplicatedCollectorRegistry.scala │ │ ├── SparkCollectorDecorators.scala │ │ └── sink │ │ └── PrometheusSink.scala │ └── org │ └── apache │ └── spark │ └── banzaicloud │ └── metrics │ └── sink │ └── PrometheusSink.scala └── test └── scala ├── com └── banzaicloud │ └── spark │ └── metrics │ ├── DeduplicatedCollectorRegistrySuite.scala │ ├── SparkCollectorDecoratorsSuite.scala │ └── sink │ └── PrometheusSinkSuite.scala └── org └── apache └── spark └── banzaicloud └── metrics └── sink └── PrometheusSinkSuite.scala /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Scala CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/sample-config/ for more details 4 | # 5 | version: 2 6 | jobs: 7 | build: 8 | docker: 9 | # specify the version you desire here 10 | - image: circleci/openjdk:8-jdk 11 | 12 | # Specify service dependencies here if necessary 13 | # CircleCI maintains a library of pre-built images 14 | # documented at https://circleci.com/docs/2.0/circleci-images/ 15 | # - image: circleci/postgres:9.4 16 | 17 | working_directory: ~/repo 18 | 19 | environment: 20 | # Customize the JVM maximum heap limit 21 | JVM_OPTS: -Xmx3200m 22 | TERM: dumb 23 | 24 | steps: 25 | - checkout 26 | 27 | # Download and cache dependencies 28 | - restore_cache: 29 | keys: 30 | - v1-dependencies-{{ checksum "build.sbt" }} 31 | # fallback to using the latest cache if no exact match is found 32 | - v1-dependencies- 33 | 34 | - run: cat /dev/null | sbt test:compile 35 | 36 | - save_cache: 37 | paths: 38 | - ~/.m2 39 | key: v1-dependencies--{{ checksum "build.sbt" }} 40 | 41 | # run tests! 42 | - run: cat /dev/null | sbt test:test -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | target/ 4 | .idea/ 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /PrometheusSink.md: -------------------------------------------------------------------------------- 1 | ### Monitor Apache Spark with Prometheus the `alternative` way 2 | 3 | We have externalized the sink into a separate library thus you can use this by either building for yourself or take it from our Maven repository. 4 | 5 | #### Prometheus sink 6 | 7 | PrometheusSink is a Spark metrics [sink](https://spark.apache.org/docs/2.2.0/monitoring.html#metrics) that publishes spark metrics into [Prometheus](https://prometheus.io). 8 | 9 | #### Prerequisites 10 | 11 | Prometheus uses a **pull** model over http to scrape data from the applications. For batch jobs it also supports a **push** model. We need to use this model as Spark pushes metrics to sinks. In order to enable this feature for Prometheus a special component called [pushgateway](https://github.com/prometheus/pushgateway) needs to be running. 12 | 13 | #### How to enable PrometheusSink in Spark 14 | 15 | Spark publishes metrics to Sinks listed in the metrics configuration file. The location of the metrics configuration file can be specified for `spark-submit` as follows: 16 | 17 | ```sh 18 | --conf spark.metrics.conf= 19 | ``` 20 | 21 | Add the following lines to metrics configuration file: 22 | 23 | ```sh 24 | # Enable Prometheus for all instances by class name 25 | *.sink.prometheus.class=org.apache.spark.banzaicloud.metrics.sink.PrometheusSink 26 | # Prometheus pushgateway address 27 | *.sink.prometheus.pushgateway-address-protocol= - defaults to http 28 | *.sink.prometheus.pushgateway-address= - defaults to 127.0.0.1:9091 29 | *.sink.prometheus.period= - defaults to 10 30 | *.sink.prometheus.unit=< unit> - defaults to seconds (TimeUnit.SECONDS) 31 | *.sink.prometheus.pushgateway-enable-timestamp= - defaults to false 32 | # Metrics name processing (version 2.3-1.1.0 +) 33 | *.sink.prometheus.metrics-name-capture-regex= 34 | *.sink.prometheus.metrics-name-replacement= 35 | *.sink.prometheus.labels= 36 | # Support for JMX Collector (version 2.3-2.0.0 +) 37 | *.sink.prometheus.enable-dropwizard-collector=false 38 | *.sink.prometheus.enable-jmx-collector=true 39 | *.sink.prometheus.jmx-collector-config=/opt/spark/conf/monitoring/jmxCollector.yaml 40 | 41 | # Enable HostName in Instance instead of Appid (Default value is false i.e. instance=${appid}) 42 | *.sink.prometheus.enable-hostname-in-instance=true 43 | 44 | # Enable JVM metrics source for all instances by class name 45 | *.sink.jmx.class=org.apache.spark.metrics.sink.JmxSink 46 | *.source.jvm.class=org.apache.spark.metrics.source.JvmSource 47 | 48 | # Use custom metric filter 49 | *.sink.prometheus.metrics-filter-class=com.example.RegexMetricFilter 50 | *.sink.prometheus.metrics-filter-regex=com.example\.(.*) 51 | ``` 52 | 53 | * **pushgateway-address-protocol** - the scheme of the URL where pushgateway service is available 54 | * **pushgateway-address** - the host and port the URL where pushgateway service is available 55 | * **period** - controls the periodicity of metrics being sent to pushgateway 56 | * **unit** - the time unit of the periodicity 57 | * **pushgateway-enable-timestamp** - controls whether to send the timestamp of the metrics sent to pushgateway. This is disabled by default as **not all** versions of pushgateway support timestamp for metrics. 58 | * **metrics-name-capture-regex** - if provided than this regexp is applied on each metric name prior sending to Prometheus. The metric name sections captured(regexp groups) will be replaced with the value passed in `metrics-name-replacement`. 59 | e.g. `(.*driver_)(.+)`. *Supported only in version **2.3-1.1.0 and above**.* 60 | * **metrics-name-replacement** - the replacement to replace captured sections(regexp groups) metric name. e.g. `${2}`. *Supported only in version **2.3-1.1.0 and above**.* 61 | * **labels** - the list of labels to be passed to Prometheus with each metrics in addition to the default ones. This must be specified in the format label=value sperated by comma. *Supported only in version **2.3-1.1.0 and above**.* 62 | * **group-key** - the list of labels to be passed to pushgateway as a group key. This must be specified in the label=value format separated by comma. `role`, `number` labels are always added even if custom group key is set. If `group-key` is not specified PrometheusSink will use `role`, `app_name`, `instance`, `number` and all metrics labels as a group key. 63 | Please note that `instance` name change between application executions, so pushgateway will create and keep metrics groups from the old runs. This may lead to memory issues after many runs. That's way setting `group-key` is strongly advised. *Supported only in version **2.4-1.0.0 and above**.* 64 | * **enable-dropwizard-collector** - from version 2.3-2.0.0 you can enable/disable dropwizard collector 65 | * **enable-jmx-collector** - from version 2.3-2.0.0 you can enable/disable JMX collector which collects configure metrics from JMX 66 | * **jmx-collector-config** - the location of jmx collector config file 67 | * **metrics-filter-class** - optional MetricFilter implementation to filter metrics to report. By default, all metrics are reported. 68 | * **metrics-filter-<key>** - configuration option passed to the metric filter's constructor. See more on this below. 69 | 70 | #### JMX configuration 71 | 72 | Example JMX collector configuration file: 73 | 74 | ```sh 75 | lowercaseOutputName: false 76 | lowercaseOutputLabelNames: false 77 | whitelistObjectNames: ["*:*"] 78 | ``` 79 | 80 | You can find more detailed description on this configuration file [here](https://github.com/prometheus/jmx_exporter). 81 | 82 | #### Metrics filtering 83 | 84 | It is possible to provide a custom class implementing [`com.codahale.metrics.MetricFilter`](https://metrics.dropwizard.io/3.1.0/apidocs/com/codahale/metrics/MetricFilter.html) 85 | for filtering metrics to report. The qualified class name should be specified with the **metrics-filter-class** configuration option. 86 | The class must have a public constructor taking either 87 | - `scala.collection.immutable.Map[String, String]` 88 | - `java.util.Map[String, String]` 89 | - `java.util.Properties`. 90 | 91 | Properties matching **metrics-filter-<key>** are passed as key-value pairs to an applicable constructor during 92 | instantiation. Additionally, if we can't find any of the above, the public no-arg constructor is tried, but in this case 93 | no configuration can be passed. 94 | 95 | #### Deploying 96 | 97 | `spark-submit` needs to know repository where to download the `jar` containing PrometheusSink from: 98 | 99 | ```sh 100 | --repositories https://raw.github.com/banzaicloud/spark-metrics/master/maven-repo/releases 101 | ``` 102 | 103 | _**Note**_: this is a maven repo hosted on GitHub. Starting from version 2.3-2.1.0 PrometheusSink is available through Maven Central Repo under group id `com.banzaicloud` thus passing `--repositories` to `spark-submit` 104 | is not needed. 105 | 106 | Also we have to specify the spark-metrics package that includes PrometheusSink and it's dependent packages for `spark-submit`: 107 | * Spark 2.2: 108 | 109 | ```sh 110 | --packages com.banzaicloud:spark-metrics_2.11:2.2.1-1.0.0,io.prometheus:simpleclient:0.0.23,io.prometheus:simpleclient_dropwizard:0.0.23,io.prometheus:simpleclient_pushgateway:0.0.23,io.dropwizard.metrics:metrics-core:3.1.2 111 | ``` 112 | 113 | * Spark 2.3: 114 | 115 | ```sh 116 | --packages com.banzaicloud:spark-metrics_2.11:2.3-2.1.0,io.prometheus:simpleclient:0.3.0,io.prometheus:simpleclient_dropwizard:0.3.0,io.prometheus:simpleclient_pushgateway:0.3.0,io.dropwizard.metrics:metrics-core:3.1.2 117 | ``` 118 | 119 | * Spark 3.1: 120 | 121 | ```sh 122 | --packages com.banzaicloud:spark-metrics_2.12:3.1-1.0.0,io.prometheus:simpleclient:0.11.0,io.prometheus:simpleclient_dropwizard:0.11.0,io.prometheus:simpleclient_pushgateway:0.11.0,io.prometheus:simpleclient_common:0.11.0,io.prometheus.jmx:collector:0.15.0 123 | ``` 124 | 125 | * Spark 3.2: 126 | 127 | ```sh 128 | --packages com.banzaicloud:spark-metrics_2.12:3.2-1.0.0,io.prometheus:simpleclient:0.15.0,io.prometheus:simpleclient_dropwizard:0.15.0,io.prometheus:simpleclient_pushgateway:0.15.0,io.prometheus:simpleclient_common:0.15.0,io.prometheus.jmx:collector:0.17.0 129 | ``` 130 | _**Note**_: the `--packages` option currently is not supported by _**Spark 2.3 when running on Kubernetes**_. The reason is that the `--packages` option behind the scenes downloads the files from maven repo to local machines than uploads these to the cluster using _Local File Dependency Management_ feature. This feature has not been backported from the _**Spark 2.2 on Kubernetes**_ fork to _**Spark 2.3**_. See details here: [Spark 2.3 Future work](https://spark.apache.org/docs/latest/running-on-kubernetes.html#future-work). This can be worked around by: 131 | 1. building ourselves [Spark 2.3 with Kubernetes support](https://spark.apache.org/docs/latest/building-spark.html#building-with-kubernetes-support) from source 132 | 1. downloading and adding the dependencies to `assembly/target/scala-2.11/jars` folder, by running the following commands: 133 | 134 | 1. export SPARK_METRICS_VERSION=2.3-2.1.0 135 | 1. mvn dependency:get -DgroupId=com.banzaicloud -DartifactId=spark-metrics_2.11 -Dversion=${SPARK_METRICS_VERSION} 136 | 1. mkdir temp 137 | 1. mvn dependency:copy-dependencies -f ~/.m2/repository/com/banzaicloud/spark-metrics_2.11/${SPARK_METRICS_VERSION}/spark-metrics_2.11-${SPARK_METRICS_VERSION}.pom -DoutputDirectory=$(pwd)/temp 138 | 1. cp temp/* assembly/target/scala-2.11/jars 139 | 140 | ### Build fat jar 141 | In the case when you want to add spark-metrics jar into your classpath you can build it locally to include all needed dependencies using the following command: 142 | ```sh 143 | sbt assembly 144 | ``` 145 | After assembling just add resulting ``spark-metrics-assembly-3.2-1.0.0.jar`` into your Spark classpath (e.g. `$SPARK_HOME/jars/`). 146 | 147 | #### Package version 148 | 149 | The version number of the package is formatted as: `com.banzaicloud:spark-metrics_:-` 150 | 151 | ### Conclusion 152 | 153 | This is not the ideal scenario but it perfectly does the job and it's independent of Spark core. At [Banzai Cloud](https://banzaicloud.com) we are **willing to contribute** this sink once the community decided that it actually needs it. Meanwhile you can open a new feature requests, use this existing PR or use any other means to ask for `native` Prometheus support and let us know through one of our social channels. As usual, we are happy to help. All we create is open source and at the same time all we consume is open source as well - so we are always eager to make open source projects better. 154 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apache Spark metrics extensions 2 | 3 | This is a repository for ApacheSpark metrics related custom classes (e.g. sources, sinks). We were trying to extend the Spark Metrics subsystem with a Prometheus sink but the [PR](https://github.com/apache/spark/pull/19775#issuecomment-371504349) was not merged upstream. In order to support others to use Prometheus we have externalized the sink and made available through this repository, thus there is no need to build an Apache Spark fork. 4 | 5 | * [Prometheus sink](https://github.com/banzaicloud/spark-metrics/blob/master/PrometheusSink.md) 6 | 7 | For further information how we use this extension and the Prometheus sink at [Banzai Cloud](https://banzaicloud.com/) please read these posts: 8 | 9 | * [Monitoring Apache Spark with Prometheus](https://banzaicloud.com/blog/spark-monitoring/)
10 | * [Monitoring multiple federated clusters with Prometheus - the secure way](https://banzaicloud.com/blog/prometheus-federation/)
11 | * [Application monitoring with Prometheus and Pipeline](https://banzaicloud.com/blog/prometheus-application-monitoring/)
12 | 13 | 14 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | lazy val scala212 = "2.12.12" 2 | lazy val supportedScalaVersions = List(scala212) 3 | lazy val ioPrometheusVersion = "0.15.0" 4 | 5 | lazy val root = (project in file(".")) 6 | .settings( 7 | name := "spark-metrics", 8 | organization := "com.banzaicloud", 9 | organizationHomepage := Some(url("https://banzaicloud.com")), 10 | homepage := Some(url("https://github.com/banzaicloud/spark-metrics")), 11 | developers := List( 12 | Developer("stoader", "Sebastian Toader", "st0ad3r@gmail.com", url("https://github.com/stoader")), 13 | Developer("sancyx", "Sandor Magyari", "sancyx@gmail.com", url("https://github.com/sancyx")), 14 | Developer("baluchicken", "Balint Molnar", "balintmolnar91@gmail.com", url("https://github.com/baluchicken")) 15 | ), 16 | scmInfo := Some(ScmInfo(url("https://github.com/banzaicloud/spark-metrics"), "git@github.com:banzaicloud/spark-metrics.git")), 17 | licenses += ("Apache-2.0", url("http://www.apache.org/licenses/LICENSE-2.0")), 18 | scalaVersion := scala212, 19 | crossScalaVersions := supportedScalaVersions, 20 | version := "3.2-1.0.0", 21 | libraryDependencies ++= Seq( 22 | "io.prometheus" % "simpleclient" % ioPrometheusVersion, 23 | "io.prometheus" % "simpleclient_dropwizard" % ioPrometheusVersion, 24 | "io.prometheus" % "simpleclient_common" % ioPrometheusVersion, 25 | "io.prometheus" % "simpleclient_pushgateway" % ioPrometheusVersion, 26 | "io.dropwizard.metrics" % "metrics-core" % "4.2.9" % Provided, 27 | "io.prometheus.jmx" % "collector" % "0.17.0", 28 | "org.apache.spark" %% "spark-core" % "3.2.1" % Provided, 29 | "com.novocode" % "junit-interface" % "0.11" % Test, 30 | // Spark shaded jetty is not resolved in scala 2.11 31 | // Described in https://issues.apache.org/jira/browse/SPARK-18162?focusedCommentId=15818123#comment-15818123 32 | // "org.eclipse.jetty" % "jetty-servlet" % "9.4.18.v20190429" % Test 33 | ), 34 | testOptions in Test := Seq(Tests.Argument(TestFrameworks.JUnit, "-a")) 35 | ) 36 | 37 | 38 | publishMavenStyle := true 39 | useGpg := true 40 | 41 | // Add sonatype repository settings 42 | publishTo := Some( 43 | if (isSnapshot.value) 44 | Opts.resolver.sonatypeSnapshots 45 | else 46 | Opts.resolver.sonatypeStaging 47 | ) 48 | 49 | -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0-javadoc.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/banzaicloud/spark-metrics/1f2147fac5103a34e68bbc74a9021a00d3b5ad37/maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0-javadoc.jar -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0-javadoc.jar.md5: -------------------------------------------------------------------------------- 1 | 083a00690a0dcc41a35f43d69b6455f0 -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0-javadoc.jar.sha1: -------------------------------------------------------------------------------- 1 | 5e7afda8d9788074c911fff3cc988a3210dcf51e -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/banzaicloud/spark-metrics/1f2147fac5103a34e68bbc74a9021a00d3b5ad37/maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0-sources.jar -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0-sources.jar.md5: -------------------------------------------------------------------------------- 1 | a6b089055ab4a5334bed85d2ad3a60c7 -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0-sources.jar.sha1: -------------------------------------------------------------------------------- 1 | 8c81fc582537e44fba0620e1dca0581dad5bc1c3 -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/banzaicloud/spark-metrics/1f2147fac5103a34e68bbc74a9021a00d3b5ad37/maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0.jar -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0.jar.md5: -------------------------------------------------------------------------------- 1 | ec106ed0bdeaa4f783222d6e0ccbe0ca -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0.jar.sha1: -------------------------------------------------------------------------------- 1 | 113bb9a2c669254570f5a858a1fa19b6f436beb5 -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0.pom: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.banzaicloud 5 | spark-metrics_2.11 6 | jar 7 | spark-metrics 8 | 2.2.1-1.0.0 9 | spark-metrics 10 | 11 | com.banzaicloud 12 | 13 | 14 | 15 | org.scala-lang 16 | scala-library 17 | 2.11.12 18 | 19 | 20 | io.prometheus 21 | simpleclient 22 | 0.0.23 23 | 24 | 25 | io.prometheus 26 | simpleclient_dropwizard 27 | 0.0.23 28 | 29 | 30 | io.prometheus 31 | simpleclient_pushgateway 32 | 0.0.23 33 | 34 | 35 | io.dropwizard.metrics 36 | metrics-core 37 | 3.1.2 38 | 39 | 40 | org.slf4j 41 | slf4j-api 42 | 1.7.25 43 | 44 | 45 | com.google.guava 46 | guava 47 | 24.0-jre 48 | 49 | 50 | com.novocode 51 | junit-interface 52 | 0.11 53 | test 54 | 55 | 56 | -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0.pom.md5: -------------------------------------------------------------------------------- 1 | 55c922509ad3149b74e555274b2b39d0 -------------------------------------------------------------------------------- /maven-repo/releases/com/banzaicloud/spark-metrics_2.11/2.2.1-1.0.0/spark-metrics_2.11-2.2.1-1.0.0.pom.sha1: -------------------------------------------------------------------------------- 1 | 8b3438f6f1cd735a5884268785469f2b1c426299 -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version = 1.3.8 -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | resolvers += "Maven2 repository" at "https://repo1.maven.org/maven2/" 2 | 3 | resolvers += "sonatype-releases" at "https://oss.sonatype.org/content/repositories/releases/" 4 | 5 | addSbtPlugin("com.jsuereth" % "sbt-pgp" % "2.0.0-M2") 6 | addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "2.3") 7 | addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "1.0.0") 8 | -------------------------------------------------------------------------------- /src/main/scala/com/banzaicloud/spark/metrics/CollectorDecorator.scala: -------------------------------------------------------------------------------- 1 | package com.banzaicloud.spark.metrics 2 | 3 | import java.util 4 | 5 | import com.banzaicloud.spark.metrics.CollectorDecorator.FamilyBuilder 6 | import io.prometheus.client.Collector 7 | import io.prometheus.client.Collector.MetricFamilySamples 8 | import io.prometheus.client.Collector.MetricFamilySamples.Sample 9 | 10 | import scala.collection.JavaConverters._ 11 | 12 | object CollectorDecorator { 13 | case class FamilyBuilder(familyName : MetricFamilySamples => String = _.name, 14 | helpMessage : MetricFamilySamples => String = _.help, 15 | sampleBuilder: SampleBuilder = SampleBuilder()) { 16 | def build(mfs: MetricFamilySamples): MetricFamilySamples = { 17 | new MetricFamilySamples( 18 | familyName(mfs), 19 | mfs.`type`, 20 | helpMessage(mfs), 21 | mfs.samples 22 | .asScala 23 | .map(sampleBuilder.build(_)) 24 | .asJava 25 | ) 26 | } 27 | } 28 | 29 | case class SampleBuilder(sampleName : Sample => String = _.name, 30 | sampleLabelNames : Sample => util.List[String] = _.labelNames, 31 | sampleLabelValues : Sample => util.List[String] = _.labelValues, 32 | sampleTimestamp : Sample => java.lang.Long = _.timestampMs) { 33 | def build(sample: Sample): Sample = { 34 | new Sample( 35 | sampleName(sample), 36 | sampleLabelNames(sample), 37 | sampleLabelValues(sample), 38 | sample.value, 39 | sampleTimestamp(sample) 40 | ) 41 | } 42 | } 43 | 44 | } 45 | 46 | abstract class CollectorDecorator(parent: Collector) 47 | extends io.prometheus.client.Collector { 48 | 49 | 50 | override def collect(): util.List[MetricFamilySamples] = { 51 | map(parent.collect(), familyBuilder) 52 | } 53 | 54 | protected def familyBuilder: FamilyBuilder = FamilyBuilder() 55 | 56 | protected def map(source: util.List[MetricFamilySamples], builder: FamilyBuilder) = { 57 | source.asScala.toList.map(builder.build(_)).asJava 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/scala/com/banzaicloud/spark/metrics/DeduplicatedCollectorRegistry.scala: -------------------------------------------------------------------------------- 1 | package com.banzaicloud.spark.metrics 2 | 3 | import java.{lang, util} 4 | import java.util.Collections 5 | 6 | import io.prometheus.client.{Collector, CollectorRegistry} 7 | 8 | import scala.collection.JavaConverters._ 9 | import org.apache.spark.internal.Logging 10 | 11 | import scala.util.{Failure, Try} 12 | 13 | class DeduplicatedCollectorRegistry(parent: CollectorRegistry = CollectorRegistry.defaultRegistry) 14 | extends CollectorRegistry with Logging { 15 | private type MetricsEnum = util.Enumeration[Collector.MetricFamilySamples] 16 | 17 | override def register(m: Collector): Unit = { 18 | 19 | // in case collectors with the same name are registered multiple times keep the first one 20 | Try(parent.register(m)) match { 21 | case Failure(ex) if ex.getMessage.startsWith("Collector already registered that provides name:") => 22 | // TODO: find a more robust solution for checking if there is already a collector registered for a specific metric 23 | case Failure(ex) => throw ex 24 | case _ => 25 | } 26 | } 27 | 28 | override def unregister(m: Collector): Unit = parent.unregister(m) 29 | 30 | override def clear(): Unit = parent.clear() 31 | 32 | override def getSampleValue(name: String, labelNames: Array[String], labelValues: Array[String]): lang.Double = { 33 | parent.getSampleValue(name, labelNames, labelValues) 34 | } 35 | 36 | override def getSampleValue(name: String): lang.Double = parent.getSampleValue(name) 37 | 38 | override def metricFamilySamples(): MetricsEnum = { 39 | deduplicate(parent.metricFamilySamples()) 40 | } 41 | 42 | override def filteredMetricFamilySamples(includedNames: util.Set[String]): MetricsEnum = { 43 | deduplicate(parent.filteredMetricFamilySamples(includedNames)) 44 | } 45 | 46 | private def deduplicate(source: MetricsEnum): MetricsEnum = { 47 | val metrics = source.asScala.toSeq 48 | val deduplicated = metrics 49 | .groupBy(f => (f.name, f.`type`)) 50 | .flatMap { 51 | case (_, single) if single.lengthCompare(2) < 0 => 52 | 53 | single 54 | case ((name, metricType), duplicates) => 55 | logDebug(s"Found ${duplicates.length} metrics with the same name '${name}' and type ${metricType}") 56 | duplicates.lastOption 57 | } 58 | .toList 59 | .asJava 60 | Collections.enumeration(deduplicated) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/scala/com/banzaicloud/spark/metrics/SparkCollectorDecorators.scala: -------------------------------------------------------------------------------- 1 | package com.banzaicloud.spark.metrics 2 | 3 | import java.util 4 | 5 | import com.banzaicloud.spark.metrics.CollectorDecorator.FamilyBuilder 6 | import com.banzaicloud.spark.metrics.PushTimestampDecorator.PushTimestampProvider 7 | import com.codahale.metrics.MetricRegistry 8 | import io.prometheus.client.Collector.MetricFamilySamples 9 | import io.prometheus.client.Collector.MetricFamilySamples.Sample 10 | import io.prometheus.client.dropwizard.DropwizardExports 11 | import io.prometheus.jmx.JmxCollector 12 | 13 | import scala.collection.JavaConverters._ 14 | import scala.util.matching.Regex 15 | 16 | object NameDecorator { 17 | case class Replace(Regex: Regex, replacement: String) 18 | } 19 | 20 | trait NameDecorator extends CollectorDecorator { 21 | val metricsNameReplace: Option[NameDecorator.Replace] 22 | 23 | protected override def familyBuilder = { 24 | super.familyBuilder.copy( 25 | familyName = mfs => replaceName(mfs.name), 26 | sampleBuilder = super.familyBuilder.sampleBuilder.copy( 27 | sampleName = s => replaceName(s.name) 28 | ) 29 | ) 30 | } 31 | 32 | private def replaceName(name: String) = { 33 | metricsNameReplace.map { 34 | case NameDecorator.Replace(regex, replacement) => regex.replaceAllIn(name, replacement) 35 | }.getOrElse(name) 36 | } 37 | } 38 | 39 | trait LabelsDecorator extends CollectorDecorator { 40 | val extraLabels: Map[String, String] 41 | 42 | private val labelNames = extraLabels.keys.toList.asJava 43 | private val labelValues = extraLabels.values.toList.asJava 44 | 45 | protected override def familyBuilder = { 46 | super.familyBuilder.copy( 47 | sampleBuilder = super.familyBuilder.sampleBuilder.copy( 48 | sampleLabelNames = s => mergeLists(s.labelNames, labelNames), 49 | sampleLabelValues = s => mergeLists(s.labelValues, labelValues) 50 | ) 51 | ) 52 | } 53 | 54 | private def mergeLists(list1: util.List[String], list2: util.List[String]): util.List[String] = { 55 | val newList = new util.ArrayList[String](list1) 56 | newList.addAll(list2) 57 | newList 58 | } 59 | } 60 | 61 | object PushTimestampDecorator { 62 | case class PushTimestampProvider(getTimestamp: () => Long = System.currentTimeMillis) extends AnyVal 63 | } 64 | trait PushTimestampDecorator extends CollectorDecorator { 65 | val maybeTimestampProvider: Option[PushTimestampProvider] 66 | 67 | protected override def map(source: util.List[MetricFamilySamples], builder: FamilyBuilder) = { 68 | val builderWithTimestamp = maybeTimestampProvider match { 69 | case Some(provider) => 70 | val timestamp: java.lang.Long = provider.getTimestamp() 71 | builder.copy( 72 | sampleBuilder = builder.sampleBuilder.copy( 73 | sampleTimestamp = _ => timestamp 74 | ) 75 | ) 76 | case None => builder 77 | } 78 | super.map(source, builderWithTimestamp) 79 | } 80 | } 81 | 82 | trait ConstantHelpDecorator extends CollectorDecorator { 83 | val constatntHelp: String 84 | 85 | protected override val familyBuilder = super.familyBuilder.copy( 86 | helpMessage = _ => constatntHelp 87 | ) 88 | } 89 | 90 | class SparkDropwizardExports(private val registry: MetricRegistry, 91 | override val metricsNameReplace: Option[NameDecorator.Replace], 92 | override val extraLabels: Map[String, String], 93 | override val maybeTimestampProvider: Option[PushTimestampProvider]) 94 | extends CollectorDecorator(new DropwizardExports(registry)) 95 | with NameDecorator 96 | with LabelsDecorator 97 | with PushTimestampDecorator 98 | with ConstantHelpDecorator { 99 | override val constatntHelp: String = "Generated from Dropwizard metric import" 100 | } 101 | 102 | class SparkJmxExports(private val jmxCollector: JmxCollector, 103 | override val extraLabels: Map[String, String], 104 | override val maybeTimestampProvider: Option[PushTimestampProvider]) 105 | extends CollectorDecorator(jmxCollector) 106 | with LabelsDecorator 107 | with PushTimestampDecorator -------------------------------------------------------------------------------- /src/main/scala/com/banzaicloud/spark/metrics/sink/PrometheusSink.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://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 | */ 17 | package com.banzaicloud.spark.metrics.sink 18 | 19 | import java.io.File 20 | import java.net.{InetAddress, URI, URL, UnknownHostException} 21 | import java.util 22 | import java.util.Properties 23 | import java.util.concurrent.TimeUnit 24 | 25 | import com.banzaicloud.spark.metrics.NameDecorator.Replace 26 | import com.banzaicloud.spark.metrics.PushTimestampDecorator.PushTimestampProvider 27 | import com.banzaicloud.spark.metrics.{DeduplicatedCollectorRegistry, SparkDropwizardExports, SparkJmxExports} 28 | import com.codahale.metrics._ 29 | import io.prometheus.client.{Collector, CollectorRegistry} 30 | import io.prometheus.client.exporter.PushGateway 31 | import io.prometheus.jmx.JmxCollector 32 | import org.apache.spark.internal.Logging 33 | 34 | import scala.collection.JavaConverters._ 35 | import scala.collection.immutable.ListMap 36 | import scala.collection.immutable 37 | import scala.util.Try 38 | import scala.util.matching.Regex 39 | 40 | object PrometheusSink { 41 | trait SinkConfig extends Serializable { 42 | def metricsNamespace: Option[String] 43 | def sparkAppId: Option[String] 44 | def sparkAppName: Option[String] 45 | def executorId: Option[String] 46 | } 47 | } 48 | abstract class PrometheusSink(property: Properties, 49 | registry: MetricRegistry, 50 | sinkConfig: PrometheusSink.SinkConfig, 51 | pushGatewayBuilder: URL => PushGateway 52 | ) extends Logging { 53 | import sinkConfig._ 54 | 55 | private val lbv = raw"(.+)\s*=\s*(.*)".r 56 | 57 | protected class Reporter(registry: MetricRegistry, metricFilter: MetricFilter) 58 | extends ScheduledReporter( 59 | registry, 60 | "prometheus-reporter", 61 | metricFilter, 62 | TimeUnit.SECONDS, 63 | TimeUnit.MILLISECONDS) { 64 | 65 | @throws(classOf[UnknownHostException]) 66 | override def report( 67 | gauges: util.SortedMap[String, Gauge[_]], 68 | counters: util.SortedMap[String, Counter], 69 | histograms: util.SortedMap[String, Histogram], 70 | meters: util.SortedMap[String, Meter], 71 | timers: util.SortedMap[String, Timer]): Unit = { 72 | 73 | logInfo(s"metricsNamespace=$metricsNamespace, sparkAppName=$sparkAppName, sparkAppId=$sparkAppId, " + 74 | s"executorId=$executorId") 75 | 76 | val role: String = (sparkAppId, executorId) match { 77 | case (Some(_), Some("driver")) | (Some(_), Some(""))=> "driver" 78 | case (Some(_), Some(_)) => "executor" 79 | case _ => "unknown" 80 | } 81 | 82 | val job: String = role match { 83 | case "driver" => metricsNamespace.getOrElse(sparkAppId.get) 84 | case "executor" => metricsNamespace.getOrElse(sparkAppId.get) 85 | case _ => metricsNamespace.getOrElse("unknown") 86 | } 87 | 88 | val instance: String = if (enableHostNameInInstance) InetAddress.getLocalHost.getHostName else sparkAppId.getOrElse("") 89 | 90 | val appName: String = sparkAppName.getOrElse("") 91 | 92 | logInfo(s"role=$role, job=$job") 93 | 94 | val groupingKey = groupKeyMap.map { groupKey => 95 | customGroupKey(role, executorId, groupKey) 96 | }.getOrElse(defaultGroupKey(role, executorId, appName, instance, labelsMap)) 97 | 98 | pushGateway.pushAdd(pushRegistry, job, groupingKey.asJava) 99 | } 100 | } 101 | 102 | val DEFAULT_PUSH_PERIOD: Int = 10 103 | val DEFAULT_PUSH_PERIOD_UNIT: TimeUnit = TimeUnit.SECONDS 104 | val DEFAULT_PUSHGATEWAY_ADDRESS: String = "127.0.0.1:9091" 105 | val DEFAULT_PUSHGATEWAY_ADDRESS_PROTOCOL: String = "http" 106 | val PUSHGATEWAY_ENABLE_TIMESTAMP: Boolean = false 107 | 108 | val KEY_PUSH_PERIOD = "period" 109 | val KEY_PUSH_PERIOD_UNIT = "unit" 110 | val KEY_PUSHGATEWAY_ADDRESS = "pushgateway-address" 111 | val KEY_PUSHGATEWAY_ADDRESS_PROTOCOL = "pushgateway-address-protocol" 112 | val KEY_PUSHGATEWAY_ENABLE_TIMESTAMP = "pushgateway-enable-timestamp" 113 | val DEFAULT_KEY_JMX_COLLECTOR_CONFIG = "/opt/spark/conf/jmx_collector.yaml" 114 | 115 | // metrics name replacement 116 | val KEY_METRICS_NAME_CAPTURE_REGEX = "metrics-name-capture-regex" 117 | val KEY_METRICS_NAME_REPLACEMENT = "metrics-name-replacement" 118 | 119 | val KEY_ENABLE_DROPWIZARD_COLLECTOR = "enable-dropwizard-collector" 120 | val KEY_ENABLE_JMX_COLLECTOR = "enable-jmx-collector" 121 | val KEY_ENABLE_HOSTNAME_IN_INSTANCE = "enable-hostname-in-instance" 122 | val KEY_JMX_COLLECTOR_CONFIG = "jmx-collector-config" 123 | 124 | val KEY_RE_METRICS_FILTER = "metrics-filter-([a-zA-Z][a-zA-Z0-9-]*)".r 125 | 126 | // labels 127 | val KEY_LABELS = "labels" 128 | val KEY_GROUP_KEY = "group-key" 129 | 130 | val pollPeriod: Int = 131 | Option(property.getProperty(KEY_PUSH_PERIOD)) 132 | .map(_.toInt) 133 | .getOrElse(DEFAULT_PUSH_PERIOD) 134 | 135 | val pollUnit: TimeUnit = 136 | Option(property.getProperty(KEY_PUSH_PERIOD_UNIT)) 137 | .map { s => TimeUnit.valueOf(s.toUpperCase) } 138 | .getOrElse(DEFAULT_PUSH_PERIOD_UNIT) 139 | 140 | val pushGatewayAddress = 141 | Option(property.getProperty(KEY_PUSHGATEWAY_ADDRESS)) 142 | .getOrElse(DEFAULT_PUSHGATEWAY_ADDRESS) 143 | 144 | val pushGatewayAddressProtocol = 145 | Option(property.getProperty(KEY_PUSHGATEWAY_ADDRESS_PROTOCOL)) 146 | .getOrElse(DEFAULT_PUSHGATEWAY_ADDRESS_PROTOCOL) 147 | 148 | val enableTimestamp: Boolean = 149 | Option(property.getProperty(KEY_PUSHGATEWAY_ENABLE_TIMESTAMP)) 150 | .map(_.toBoolean) 151 | .getOrElse(PUSHGATEWAY_ENABLE_TIMESTAMP) 152 | 153 | val metricsNameCaptureRegex: Option[Regex] = 154 | Option(property.getProperty(KEY_METRICS_NAME_CAPTURE_REGEX)) 155 | .map(new Regex(_)) 156 | 157 | val metricsNameReplacement: String = 158 | Option(property.getProperty(KEY_METRICS_NAME_REPLACEMENT)) 159 | .getOrElse("") 160 | 161 | // validate pushgateway host:port 162 | Try(new URI(s"$pushGatewayAddressProtocol://$pushGatewayAddress")).get 163 | 164 | // validate metrics name capture regex 165 | if (metricsNameCaptureRegex.isDefined && metricsNameReplacement == "") { 166 | throw new IllegalArgumentException("Metrics name replacement must be specified if metrics name capture regexp is set !") 167 | } 168 | 169 | val labelsMap = parseLabels(KEY_LABELS).getOrElse(Map.empty[String, String]) 170 | val groupKeyMap = parseLabels(KEY_GROUP_KEY) 171 | 172 | val enableDropwizardCollector: Boolean = 173 | Option(property.getProperty(KEY_ENABLE_DROPWIZARD_COLLECTOR)) 174 | .map(_.toBoolean) 175 | .getOrElse(true) 176 | val enableJmxCollector: Boolean = 177 | Option(property.getProperty(KEY_ENABLE_JMX_COLLECTOR)) 178 | .map(_.toBoolean) 179 | .getOrElse(false) 180 | val enableHostNameInInstance: Boolean = 181 | Option(property.getProperty(KEY_ENABLE_HOSTNAME_IN_INSTANCE)) 182 | .map(_.toBoolean) 183 | .getOrElse(false) 184 | val jmxCollectorConfig = 185 | Option(property.getProperty(KEY_JMX_COLLECTOR_CONFIG)) 186 | .getOrElse(DEFAULT_KEY_JMX_COLLECTOR_CONFIG) 187 | 188 | checkMinimalPollingPeriod(pollUnit, pollPeriod) 189 | 190 | logInfo("Initializing Prometheus Sink...") 191 | logInfo(s"Metrics polling period -> $pollPeriod $pollUnit") 192 | logInfo(s"Metrics timestamp enabled -> $enableTimestamp") 193 | logInfo(s"$KEY_PUSHGATEWAY_ADDRESS -> $pushGatewayAddress") 194 | logInfo(s"$KEY_PUSHGATEWAY_ADDRESS_PROTOCOL -> $pushGatewayAddressProtocol") 195 | logInfo(s"$KEY_METRICS_NAME_CAPTURE_REGEX -> ${metricsNameCaptureRegex.getOrElse("")}") 196 | logInfo(s"$KEY_METRICS_NAME_REPLACEMENT -> $metricsNameReplacement") 197 | logInfo(s"$KEY_LABELS -> ${labelsMap}") 198 | logInfo(s"$KEY_JMX_COLLECTOR_CONFIG -> $jmxCollectorConfig") 199 | 200 | val metricsFilterProps: Map[String, String] = property.stringPropertyNames().asScala 201 | .collect { case qualifiedKey @ KEY_RE_METRICS_FILTER(key) => 202 | val value = property.getProperty(qualifiedKey) 203 | logInfo(s"$qualifiedKey -> $value") 204 | key -> value 205 | }.toMap 206 | 207 | val pushRegistry: CollectorRegistry = new DeduplicatedCollectorRegistry() 208 | 209 | private val pushTimestamp = if (enableTimestamp) Some(PushTimestampProvider()) else None 210 | 211 | private val replace = metricsNameCaptureRegex.map(Replace(_, metricsNameReplacement)) 212 | 213 | lazy val sparkMetricExports = new SparkDropwizardExports(registry, replace, labelsMap, pushTimestamp) 214 | 215 | lazy val jmxMetrics = new SparkJmxExports(new JmxCollector(new File(jmxCollectorConfig)), labelsMap, pushTimestamp) 216 | 217 | val pushGateway: PushGateway = pushGatewayBuilder(new URL(s"$pushGatewayAddressProtocol://$pushGatewayAddress")) 218 | 219 | val metricsFilter: MetricFilter = metricsFilterProps.get("class") 220 | .map { className => 221 | try { 222 | instantiateMetricFilter(className, metricsFilterProps - "class") 223 | } catch { 224 | case ex: Exception => throw new RuntimeException(s"Exception occurred while creating MetricFilter instance: ${ex.getMessage}", ex) 225 | } 226 | } 227 | .getOrElse(MetricFilter.ALL) 228 | 229 | val reporter = new Reporter(registry, metricsFilter) 230 | 231 | def start(): Unit = { 232 | if (enableDropwizardCollector) { 233 | sparkMetricExports.register(pushRegistry) 234 | } 235 | if (enableJmxCollector) { 236 | jmxMetrics.register(pushRegistry) 237 | } 238 | reporter.start(pollPeriod, pollUnit) 239 | } 240 | 241 | def stop(): Unit = { 242 | reporter.stop() 243 | if (enableDropwizardCollector) { 244 | pushRegistry.unregister(sparkMetricExports) 245 | } 246 | if (enableJmxCollector) { 247 | pushRegistry.unregister(jmxMetrics) 248 | } 249 | } 250 | 251 | def report(): Unit = { 252 | reporter.report() 253 | } 254 | 255 | private def checkMinimalPollingPeriod(pollUnit: TimeUnit, pollPeriod: Int) { 256 | val period = TimeUnit.SECONDS.convert(pollPeriod, pollUnit) 257 | if (period < 1) { 258 | throw new IllegalArgumentException("Polling period " + pollPeriod + " " + pollUnit + 259 | " below than minimal polling period ") 260 | } 261 | } 262 | 263 | private def parseLabel(label: String): (String, String) = { 264 | label match { 265 | case lbv(label, value) => (Collector.sanitizeMetricName(label), value) 266 | case _ => 267 | throw new IllegalArgumentException("Can not parse labels ! Labels should be in label=value separated by commas format.") 268 | } 269 | } 270 | 271 | 272 | private def parseLabels(key: String): Option[Map[String, String]] = { 273 | Option(property.getProperty(key)).map { labelsString => 274 | val kvs = labelsString.split(',') 275 | val parsedLabels = kvs.map(parseLabel) 276 | ListMap(parsedLabels: _*) // List map to preserve labels order which might be important for group key 277 | } 278 | } 279 | 280 | /** 281 | * Default group key use instance name. So for every spark job instance it will create new metric group in the Push Gateway. 282 | * This may lead to OOM errors. 283 | * This method exists for backward compatibility. 284 | */ 285 | private def defaultGroupKey(role: String, 286 | executorId: Option[String], 287 | appName: String, 288 | instance: String, 289 | labels: Map[String, String]) = { 290 | (role, executorId) match { 291 | case ("driver", _) => 292 | ListMap("role" -> role, "app_name" -> appName, "instance" -> instance) ++ labels 293 | 294 | case ("executor", Some(id)) => 295 | ListMap("role" -> role, "app_name" -> appName, "instance" -> instance, "number" -> id) ++ labels 296 | case _ => 297 | ListMap("role" -> role) 298 | } 299 | } 300 | 301 | private def customGroupKey(role: String, 302 | executorId: Option[String], 303 | labels: Map[String, String]) = { 304 | (role, executorId) match { 305 | case ("driver", _) => 306 | ListMap("role" -> role) ++ labels 307 | 308 | case ("executor", Some(id)) => 309 | ListMap("role" -> role, "number" -> id) ++ labels 310 | case _ => 311 | ListMap("role" -> role) 312 | } 313 | } 314 | 315 | private def instantiateMetricFilter(className: String, props: Map[String, String]): MetricFilter = { 316 | val cls = Class.forName(className) 317 | 318 | if (!classOf[MetricFilter].isAssignableFrom(cls)) { 319 | throw new RuntimeException(s"${cls.getName} is not a subclass of ${classOf[MetricFilter].getName}") 320 | } 321 | 322 | val constructors = cls.getConstructors() 323 | 324 | if (constructors.isEmpty) { 325 | throw new RuntimeException(s"${cls.getName} has no public constructors.") 326 | } 327 | 328 | def maybeCallScalaMapConstructor = constructors.collectFirst { 329 | case c if c.getParameterCount == 1 && 330 | classOf[immutable.Map[_,_]].isAssignableFrom(c.getParameterTypes()(0)) => c.newInstance(props).asInstanceOf[MetricFilter] 331 | } 332 | 333 | def maybeCallJavaMapConstructor = constructors.collectFirst { 334 | case c if c.getParameterCount == 1 && 335 | classOf[util.Map[_,_]].isAssignableFrom(c.getParameterTypes()(0)) => c.newInstance(props.asJava).asInstanceOf[MetricFilter] 336 | } 337 | 338 | def maybeCallPropertiesConstructor = constructors.collectFirst { 339 | case c if c.getParameterCount == 1 && 340 | classOf[Properties].isAssignableFrom(c.getParameterTypes()(0)) => 341 | val javaProps = new Properties() 342 | javaProps.asScala ++= props 343 | c.newInstance(javaProps).asInstanceOf[MetricFilter] 344 | } 345 | 346 | def maybeCallNoArgConstructor = constructors.collectFirst { 347 | case c if c.getParameterCount == 0 => { 348 | if (props.nonEmpty) { 349 | logWarning(s"Instantiating ${cls.getName} with default constructor. All properties are discarded!") 350 | } 351 | c.newInstance().asInstanceOf[MetricFilter] 352 | } 353 | } 354 | 355 | maybeCallScalaMapConstructor 356 | .orElse(maybeCallJavaMapConstructor) 357 | .orElse(maybeCallPropertiesConstructor) 358 | .orElse(maybeCallNoArgConstructor) 359 | .getOrElse(throw new RuntimeException(s"No applicable constructor found in ${cls.getName}")) 360 | } 361 | } 362 | -------------------------------------------------------------------------------- /src/main/scala/org/apache/spark/banzaicloud/metrics/sink/PrometheusSink.scala: -------------------------------------------------------------------------------- 1 | package org.apache.spark.banzaicloud.metrics.sink 2 | 3 | import java.net.URL 4 | import java.util.Properties 5 | 6 | import com.banzaicloud.spark.metrics.sink.PrometheusSink.SinkConfig 7 | import com.codahale.metrics.{MetricRegistry} 8 | import io.prometheus.client.exporter.PushGateway 9 | import org.apache.spark.banzaicloud.metrics.sink.PrometheusSink.SinkConfigProxy 10 | import org.apache.spark.internal.config 11 | import org.apache.spark.metrics.sink.Sink 12 | import org.apache.spark.{SecurityManager, SparkConf, SparkEnv} 13 | 14 | object PrometheusSink { 15 | 16 | class SinkConfigProxy extends SinkConfig { 17 | // SparkEnv may become available only after metrics sink creation thus retrieving 18 | // SparkConf from spark env here and not during the creation/initialisation of PrometheusSink. 19 | @transient 20 | private lazy val sparkConfig = Option(SparkEnv.get).map(_.conf).getOrElse(new SparkConf(true)) 21 | 22 | // Don't use sparkConf.getOption("spark.metrics.namespace") as the underlying string won't be substituted. 23 | def metricsNamespace: Option[String] = sparkConfig.get(config.METRICS_NAMESPACE) 24 | def sparkAppId: Option[String] = sparkConfig.getOption("spark.app.id") 25 | def sparkAppName: Option[String] = sparkConfig.getOption("spark.app.name") 26 | def executorId: Option[String] = sparkConfig.getOption("spark.executor.id") 27 | } 28 | } 29 | 30 | class PrometheusSink(property: Properties, 31 | registry: MetricRegistry, 32 | sinkConfig: SinkConfig, 33 | pushGatewayBuilder: URL => PushGateway 34 | ) 35 | extends com.banzaicloud.spark.metrics.sink.PrometheusSink(property, registry, sinkConfig, pushGatewayBuilder) with Sink { 36 | 37 | // Constructor required by MetricsSystem::registerSinks() for spark >= 3.2 38 | def this(property: Properties, registry: MetricRegistry) = { 39 | this( 40 | property, 41 | registry, 42 | new SinkConfigProxy, 43 | new PushGateway(_) 44 | ) 45 | } 46 | 47 | // Legacy Constructor required by MetricsSystem::registerSinks() for spark < 3.2 48 | def this(property: Properties, registry: MetricRegistry, securityMgr: SecurityManager) = { 49 | this(property, registry) 50 | } 51 | } -------------------------------------------------------------------------------- /src/test/scala/com/banzaicloud/spark/metrics/DeduplicatedCollectorRegistrySuite.scala: -------------------------------------------------------------------------------- 1 | package com.banzaicloud.spark.metrics 2 | 3 | import com.codahale.metrics.MetricRegistry 4 | import io.prometheus.client.{Collector, CollectorRegistry} 5 | import io.prometheus.client.dropwizard.DropwizardExports 6 | import org.junit.{Assert, Test} 7 | 8 | import scala.collection.JavaConverters._ 9 | 10 | class DeduplicatedCollectorRegistrySuite { 11 | @Test def testDeduplication(): Unit = { 12 | // given 13 | val baseRegistry = new MetricRegistry 14 | val registryA = new MetricRegistry 15 | val counterA = registryA.counter("counter") 16 | counterA.inc(20) 17 | counterA.inc(30) 18 | 19 | val registryB = new MetricRegistry 20 | val counterB = registryB.counter("counter") 21 | counterB.inc(40) 22 | counterB.inc(50) 23 | baseRegistry.register("hive_", registryA) 24 | baseRegistry.register("hive.", registryB) 25 | 26 | val metricsExports = new DropwizardExports(baseRegistry) 27 | val deduplicatedCollectorRegistry = new DeduplicatedCollectorRegistry(new CollectorRegistry(true)) 28 | 29 | // when 30 | metricsExports.register(deduplicatedCollectorRegistry) 31 | val samples = deduplicatedCollectorRegistry.metricFamilySamples() 32 | 33 | // then 34 | val actual = samples 35 | .asScala 36 | .filter(mfs => mfs.`type`== Collector.Type.GAUGE && mfs.name == "hive__counter") 37 | Assert.assertEquals(1, actual.size) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/scala/com/banzaicloud/spark/metrics/SparkCollectorDecoratorsSuite.scala: -------------------------------------------------------------------------------- 1 | package com.banzaicloud.spark.metrics 2 | 3 | import java.util.concurrent.atomic.AtomicLong 4 | 5 | import com.codahale.metrics.MetricRegistry 6 | import io.prometheus.client.{Collector, CollectorRegistry} 7 | import io.prometheus.jmx.JmxCollector 8 | import org.junit.{Assert, Test} 9 | 10 | import scala.collection.JavaConverters._ 11 | 12 | 13 | class SparkCollectorDecoratorsSuite { 14 | trait Fixture { 15 | // Given 16 | val extraLabels = Map("label1" -> "val1", "label2" -> "val2") 17 | val registry = new MetricRegistry 18 | val jmxCollector = new JmxCollector("") 19 | val pushRegistry = new CollectorRegistry(true) 20 | val metric1 = registry.counter("test-metric-sample1") 21 | metric1.inc() 22 | val metric2 = registry.histogram("test-metric-sample2") 23 | metric2.update(2) 24 | 25 | // Then 26 | def getExportedMetrics = pushRegistry.metricFamilySamples().asScala.toList 27 | def getCounterFamily = getExportedMetrics.find(_.`type`== Collector.Type.GAUGE).get 28 | def getHistogramFamily = getExportedMetrics.find(_.`type`== Collector.Type.SUMMARY).get 29 | def getCounterSamples = getCounterFamily.samples.asScala 30 | def getHistogramSamples = getHistogramFamily.samples.asScala 31 | 32 | } 33 | 34 | @Test def testStaticTimestamp(): Unit = new Fixture { 35 | // given 36 | val ts = new AtomicLong(0) 37 | val pushTs = PushTimestampDecorator.PushTimestampProvider(() => ts.incrementAndGet()) 38 | 39 | val metricsExports = new SparkDropwizardExports(registry, None, Map.empty, Some(pushTs)) 40 | metricsExports.register(pushRegistry) 41 | 42 | def testTimestampEqual() = { 43 | val allTimestamps = getExportedMetrics.flatMap { family => 44 | family.samples.asScala.map(_.timestampMs) 45 | } 46 | Assert.assertSame("Samples were omitted.", 8, allTimestamps.size) 47 | Assert.assertSame("Timestamps are not the same.",1, allTimestamps.distinct.size) 48 | } 49 | 50 | // then 51 | testTimestampEqual() 52 | testTimestampEqual() 53 | testTimestampEqual() 54 | } 55 | 56 | @Test def testNoPushTimestamp(): Unit = new Fixture { 57 | // given 58 | val metricsExports = new SparkDropwizardExports(registry, None, Map.empty, None) 59 | val jmxMetricsExports = new SparkJmxExports(jmxCollector, Map.empty, None) 60 | metricsExports.register(pushRegistry) 61 | jmxMetricsExports.register(pushRegistry) 62 | 63 | // then 64 | getExportedMetrics.foreach { family => 65 | family.samples.asScala.foreach { sample => 66 | Assert.assertEquals(null, sample.timestampMs) 67 | } 68 | } 69 | } 70 | 71 | @Test def testNameReplace(): Unit = new Fixture { // given 72 | val metricsNameReplace = NameDecorator.Replace("(\\d+)".r, "__$1__") 73 | 74 | val metricsExports = new SparkDropwizardExports(registry, Some(metricsNameReplace), Map.empty, None) 75 | metricsExports.register(pushRegistry) 76 | 77 | // then 78 | Assert.assertTrue(getExportedMetrics.size == 2) 79 | 80 | val counterSamples = getCounterSamples 81 | Assert.assertTrue(counterSamples.size == 1) 82 | counterSamples.foreach { sample => 83 | Assert.assertTrue(s"[${sample.name}]", sample.name == "test_metric_sample__1__") 84 | } 85 | 86 | val histogramSamples = getHistogramSamples 87 | Assert.assertTrue(histogramSamples.size == 7) 88 | histogramSamples.foreach { sample => 89 | Assert.assertTrue(sample.name.startsWith("test_metric_sample__2__")) 90 | } 91 | 92 | } 93 | 94 | @Test def testStaticHelpMessage(): Unit = new Fixture { // given 95 | val staticTs = 1 96 | 97 | val metricsExports = new SparkDropwizardExports(registry, None, Map.empty, None) 98 | metricsExports.register(pushRegistry) 99 | 100 | // then 101 | val expectedHelp = "Generated from Dropwizard metric import" 102 | getExportedMetrics.foreach { family => 103 | Assert.assertEquals(expectedHelp, family.help) 104 | } 105 | } 106 | 107 | @Test def testExtraLabels(): Unit = new Fixture { // given 108 | val metricsExports = new SparkDropwizardExports(registry, None, extraLabels, None) 109 | val jmxMetricsExports = new SparkJmxExports(jmxCollector, extraLabels, None) 110 | metricsExports.register(pushRegistry) 111 | jmxMetricsExports.register(pushRegistry) 112 | 113 | // then 114 | val exportedMetrics = getExportedMetrics 115 | Assert.assertTrue(exportedMetrics.size > 2) 116 | 117 | exportedMetrics.foreach { family => 118 | family.samples.asScala.foreach { sample => 119 | Assert.assertTrue(sample.labelNames.asScala.toList.containsSlice(extraLabels.keys.toList)) 120 | Assert.assertTrue(sample.labelValues.asScala.toList.containsSlice(extraLabels.values.toList)) 121 | } 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/test/scala/com/banzaicloud/spark/metrics/sink/PrometheusSinkSuite.scala: -------------------------------------------------------------------------------- 1 | package com.banzaicloud.spark.metrics.sink 2 | 3 | import java.io.IOException 4 | import java.util 5 | import java.util.Properties 6 | import java.util.concurrent.CopyOnWriteArrayList 7 | 8 | import com.banzaicloud.spark.metrics.sink.PrometheusSink.SinkConfig 9 | import com.banzaicloud.spark.metrics.sink.PrometheusSinkSuite.{DefaultConstr, JavaMapConstr, PropertiesConstr, ScalaMapConstr} 10 | import com.codahale.metrics.{Metric, MetricFilter, MetricRegistry} 11 | import io.prometheus.client.CollectorRegistry 12 | import io.prometheus.client.exporter.PushGateway 13 | import org.apache.spark.banzaicloud.metrics.sink.{PrometheusSink => SparkPrometheusSink} 14 | import org.junit.{Assert, Test} 15 | 16 | import scala.collection.JavaConverters._ 17 | import scala.util.Try 18 | 19 | class PrometheusSinkSuite { 20 | case class TestSinkConfig(metricsNamespace: Option[String], 21 | sparkAppId: Option[String], 22 | sparkAppName: Option[String], 23 | executorId: Option[String]) extends SinkConfig 24 | 25 | 26 | val basicProperties = { 27 | val properties = new Properties 28 | properties.setProperty("enable-jmx-collector", "true") 29 | properties.setProperty("labels", "a=1,b=22") 30 | properties.setProperty("period", "1") 31 | properties.setProperty("group-key", "key1=AA,key2=BB") 32 | properties.setProperty("jmx-collector-config", "/dev/null") 33 | properties 34 | } 35 | 36 | 37 | trait Fixture { 38 | def sinkConfig = TestSinkConfig(Some("test-job-name"), Some("test-app-id"), Some("test-app-name"), None) 39 | lazy val pgMock = new PushGatewayMock 40 | lazy val registry = new MetricRegistry 41 | 42 | def withSink[T](properties: Properties = basicProperties)(fn: (SparkPrometheusSink) => T): Unit = { 43 | // Given 44 | val sink = new SparkPrometheusSink(properties, registry, sinkConfig, _ => pgMock) 45 | try { 46 | //When 47 | sink.start() 48 | sink.report() 49 | } finally { 50 | Try(sink.stop()) // We call stop to avoid duplicated metrics across different tests 51 | } 52 | } 53 | } 54 | 55 | @Test 56 | def testSinkForDriver(): Unit = new Fixture { 57 | //Given 58 | override val sinkConfig = super.sinkConfig.copy(executorId = Some("driver")) 59 | 60 | registry.counter("test-counter").inc(3) 61 | withSink() { sink => 62 | //Then 63 | Assert.assertTrue(pgMock.requests.size == 1) 64 | val request = pgMock.requests.head 65 | 66 | Assert.assertTrue(request.job == "test-job-name") 67 | Assert.assertTrue(request.groupingKey.asScala == Map("role" -> "driver", "key1" -> "AA", "key2" -> "BB")) 68 | Assert.assertTrue( 69 | request.registry.metricFamilySamples().asScala.exists(_.name == "jmx_config_reload_success_total") 70 | ) 71 | Assert.assertTrue( 72 | sink.metricsFilter == MetricFilter.ALL 73 | ) 74 | } 75 | } 76 | 77 | @Test 78 | def testSinkForExecutor(): Unit = new Fixture { 79 | //Given 80 | override val sinkConfig = super.sinkConfig.copy(executorId = Some("2")) 81 | 82 | registry.counter("test-counter").inc(3) 83 | 84 | withSink() { sink => 85 | //Then 86 | Assert.assertTrue(pgMock.requests.size == 1) 87 | val request = pgMock.requests.head 88 | 89 | Assert.assertTrue(request.job == "test-job-name") 90 | Assert.assertTrue(request.groupingKey.asScala == Map("role" -> "executor", "number" -> "2", "key1" -> "AA", "key2" -> "BB")) 91 | val families = request.registry.metricFamilySamples().asScala.toList 92 | 93 | Assert.assertTrue { 94 | val counterFamily = families.find(_.name == "test_counter").get 95 | val sample = counterFamily.samples.asScala.head 96 | val labels = sample.labelNames.asScala.zip(sample.labelValues.asScala) 97 | labels == List("a" -> "1", "b" -> "22") 98 | } 99 | Assert.assertTrue( 100 | families.exists(_.name == "jmx_config_reload_success_total") 101 | ) 102 | Assert.assertTrue( 103 | sink.metricsFilter == MetricFilter.ALL 104 | ) 105 | } 106 | } 107 | 108 | @Test 109 | def testMetricsFilterInstantiation(): Unit = new Fixture { 110 | 111 | def testMetricPropertySet(tests: (Class[_], MetricFilter => Any)*) = for {(cls, getter) <- tests} withSink({ 112 | val properties = new Properties() 113 | properties.put("metrics-filter-class", cls) 114 | properties.put("metrics-filter-key", "value") 115 | properties 116 | }) { sink => 117 | Assert.assertEquals(cls, sink.metricsFilter.getClass) 118 | Assert.assertEquals("value", getter(sink.metricsFilter)) 119 | } 120 | 121 | testMetricPropertySet( 122 | (classOf[PropertiesConstr], _.asInstanceOf[PropertiesConstr].props.get("key")), 123 | (classOf[JavaMapConstr], _.asInstanceOf[JavaMapConstr].props.get("key")), 124 | (classOf[ScalaMapConstr], _.asInstanceOf[ScalaMapConstr].props("key")), 125 | ) 126 | 127 | withSink({ 128 | val properties = new Properties() 129 | properties.put("metrics-filter-class", classOf[DefaultConstr]) 130 | properties 131 | }) { sink => 132 | Assert.assertEquals(classOf[DefaultConstr], sink.metricsFilter.getClass) 133 | } 134 | } 135 | 136 | class PushGatewayMock extends PushGateway("anything") { 137 | val requests = new CopyOnWriteArrayList[Request]().asScala 138 | case class Request(registry: CollectorRegistry, job: String, groupingKey: util.Map[String, String], method: String) 139 | 140 | @throws[IOException] 141 | override def push(registry: CollectorRegistry, job: String) { 142 | logRequest(registry, job, null, "PUT") 143 | } 144 | 145 | @throws[IOException] 146 | override def push(registry: CollectorRegistry, job: String, groupingKey: util.Map[String, String]): Unit = { 147 | logRequest(registry, job, groupingKey, "PUT") 148 | } 149 | 150 | @throws[IOException] 151 | override def pushAdd(registry: CollectorRegistry, job: String) { 152 | logRequest(registry, job, null, "POST") 153 | } 154 | 155 | @throws[IOException] 156 | override def pushAdd(registry: CollectorRegistry, job: String, groupingKey: util.Map[String, String]): Unit = { 157 | logRequest(registry, job, groupingKey, "POST") 158 | } 159 | 160 | @throws[IOException] 161 | override def delete(job: String) { 162 | logRequest(null, job, null, "DELETE") 163 | } 164 | 165 | @throws[IOException] 166 | override def delete(job: String, groupingKey: util.Map[String, String]) { 167 | logRequest(null, job, groupingKey, "DELETE") 168 | } 169 | 170 | private def logRequest(registry: CollectorRegistry, job: String, groupingKey: util.Map[String, String], method: String) { 171 | requests += Request(registry, job, groupingKey, method) 172 | } 173 | } 174 | } 175 | 176 | object PrometheusSinkSuite { 177 | trait NoOpMetricFilter extends MetricFilter { 178 | override def matches(name: String, metric: Metric): Boolean = false 179 | } 180 | 181 | class DefaultConstr extends NoOpMetricFilter 182 | 183 | class PropertiesConstr(val props: Properties) extends NoOpMetricFilter 184 | 185 | class JavaMapConstr(val props: util.Map[String, String]) extends NoOpMetricFilter 186 | 187 | class ScalaMapConstr(val props: Map[String, String]) extends NoOpMetricFilter 188 | } 189 | -------------------------------------------------------------------------------- /src/test/scala/org/apache/spark/banzaicloud/metrics/sink/PrometheusSinkSuite.scala: -------------------------------------------------------------------------------- 1 | package org.apache.spark.banzaicloud.metrics.sink 2 | 3 | import org.apache.spark.metrics.MetricsSystem 4 | import org.apache.spark.{SparkConf} 5 | import org.junit.{After, Before, Test} 6 | 7 | class PrometheusSinkSuite { 8 | private val sinkClassPropertyName = "spark.metrics.conf.*.sink.prometheus.class" 9 | private val sinkClassPropertyValue = "org.apache.spark.banzaicloud.metrics.sink.PrometheusSink" 10 | 11 | @Test 12 | def testThatPrometheusSinkCanBeLoaded() = { 13 | val instance = "driver" 14 | val conf = new SparkConf(true) 15 | val ms = MetricsSystem.createMetricsSystem(instance, conf) 16 | ms.start() 17 | ms.stop() 18 | } 19 | 20 | @Before 21 | def tearDown(): Unit = { 22 | System.setProperty(sinkClassPropertyName, sinkClassPropertyValue) 23 | } 24 | 25 | @After 26 | def setUp(): Unit = { 27 | System.clearProperty(sinkClassPropertyName) 28 | } 29 | } 30 | --------------------------------------------------------------------------------