├── .buildscript └── settings.xml ├── .editorconfig ├── .github ├── dependabot.yml └── workflows │ └── java.yml ├── .gitignore ├── .java-version ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.txt ├── README.md ├── RELEASING.md ├── metrics-okhttp ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── raskasa │ │ └── metrics │ │ └── okhttp │ │ ├── InstrumentedEventListener.java │ │ ├── InstrumentedInterceptor.java │ │ ├── InstrumentedOkHttpClient.java │ │ └── InstrumentedOkHttpClients.java │ └── test │ └── java │ ├── com │ └── raskasa │ │ └── metrics │ │ └── okhttp │ │ ├── InstrumentedOkHttpClientTest.java │ │ └── InstrumentedOkHttpClientsTest.java │ └── okhttp3 │ └── RecordingEventListener.java ├── pom.xml └── sample ├── pom.xml └── src └── main └── java └── com └── raskasa └── metrics └── okhttp └── sample └── App.java /.buildscript/settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | sonatype-nexus-snapshots 5 | ${env.CI_DEPLOY_USERNAME} 6 | ${env.CI_DEPLOY_PASSWORD} 7 | 8 | 9 | sonatype-nexus-staging 10 | ${env.CI_DEPLOY_USERNAME} 11 | ${env.CI_DEPLOY_PASSWORD} 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | insert_final_newline = true 5 | 6 | [*{.java,xml}] 7 | indent_style = space 8 | indent_size = 2 9 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "maven" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | - package-ecosystem: "github-actions" 8 | directory: "/" 9 | schedule: 10 | interval: "daily" 11 | -------------------------------------------------------------------------------- /.github/workflows/java.yml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | on: [push] 3 | jobs: 4 | Build-Project: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Checkout 8 | uses: actions/checkout@v2 9 | - name: Configure JDK 10 | uses: actions/setup-java@v2 11 | with: 12 | distribution: 'adopt' 13 | java-version: 11 14 | - name: Run Maven Build 15 | run: mvn package 16 | - name: Publish Snapshots and JavaDocs 17 | env: 18 | CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} 19 | CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} 20 | run: mvn clean source:jar javadoc:jar deploy --settings=".buildscript/settings.xml" -Dmaven.test.skip=true 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | eclipsebin 5 | 6 | bin 7 | gen 8 | build 9 | out 10 | lib 11 | 12 | target 13 | pom.xml.* 14 | release.properties 15 | .okhttp-cache 16 | 17 | .idea 18 | *.iml 19 | *.ipr 20 | *.iws 21 | classes 22 | 23 | obj 24 | 25 | .DS_Store 26 | -------------------------------------------------------------------------------- /.java-version: -------------------------------------------------------------------------------- 1 | 1.8 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | 4 | ## Version 0.5.0 5 | 6 | _2021-10-08_ 7 | 8 | * __`EventListener`-based metrics.__ Users now have access to metrics recorded 9 | through OkHttp's new API for tracking metrics and monitoring HTTP requests’ 10 | size and duration. 11 | * Updated OkHttp dependency to 3.14.9. 12 | * Updated Dropwizard Metrics dependency to 4.2.3. 13 | 14 | ## Version 0.4.0 15 | 16 | _2017-11-10_ 17 | 18 | * __Support OkHttp 3.x__ 19 | * Fix: Rewrite network request instrumentation with interceptors. The 20 | instrumented executor service is only used when executing asynchronous 21 | requests - it is not used when executing synchronous requests. By using 22 | interceptors, we can record metrics all requests regardless of whether they are 23 | synchronous or asynchronous. 24 | * Other minor changes. 25 | 26 | ## Version 0.2.0 27 | 28 | _2015-12-14_ 29 | 30 | * __Custom instrumented client names.__ Users now have the ability to provide 31 | an identifier for each instrumented client. This is useful when using multiple 32 | instances of `OkHttpClient` in your application. 33 | * Updated OkHttp dependency to 2.7. 34 | * Other minor changes. 35 | 36 | ## Version 0.1.0 37 | 38 | _2015-07-22_ 39 | 40 | Initial release. 41 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing 2 | ============ 3 | 4 | If you would like to contribute code to Metrics Integration for OkHttp you can 5 | do so through GitHub by forking the repository and sending a pull request. 6 | 7 | When submitting code, please make every effort to follow existing conventions 8 | and style in order to keep the code as readable as possible. A concrete step 9 | you can take is to ensure you're running the following before submitting a PR: 10 | 11 | ```bash 12 | $ cd metrics-okhttp 13 | $ mvn clean package 14 | ``` 15 | 16 | This should run successfully. Additionally, this runs an automated source code 17 | formatter. So, ensure any formatting changes that occur after running the above 18 | commands are added to the changes in the PR. 19 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Metrics Integration for OkHttp 2 | ============================== 3 | 4 | > :warning: As of September 2021, this project's maintainer, @raskasa, has not 5 | > been able to use this project in production for a number of years. As a 6 | > result, active development has stalled; it will likely remain stalled moving 7 | > forward unless the opportunity arises again for the maintainer to use it in 8 | > production. 9 | 10 | An [OkHttp][okhttp] HTTP client wrapper providing [Metrics][metrics] 11 | instrumentation of connection pools, request durations and rates, and other 12 | useful information. 13 | 14 | Usage 15 | ----- 16 | 17 | Metrics Integration for OkHttp provides `InstrumentedOkHttpClients`, a static 18 | factory class for instrumenting OkHttp HTTP clients. 19 | 20 | You can create an instrumented `OkHttpClient` by doing the following: 21 | 22 | ```java 23 | MetricRegistry registry = ...; 24 | OkHttpClient client = InstrumentedOkHttpClients.create(registry); 25 | ``` 26 | 27 | If you wish to provide your own `OkHttpClient` instance, you can do that as well: 28 | 29 | ```java 30 | MetricRegistry registry = ...; 31 | OkHttpClient rawClient = ...; 32 | OkHttpClient client = InstrumentedOkHttpClients.create(registry, rawClient); 33 | ``` 34 | 35 | If you use more than one OkHttpClient instance in your application, you may 36 | want to provide a custom name when instrumenting the clients in order to 37 | properly distinguish them: 38 | 39 | ```java 40 | MetricRegistry registry = ...; 41 | OkHttpClient client = InstrumentedOkHttpClients.create(registry, "custom-name"); 42 | 43 | MetricRegistry registry = ...; 44 | OkHttpClient rawClient = ...; 45 | OkHttpClient client = InstrumentedOkHttpClients.create(registry, rawClient, "custom-name"); 46 | ``` 47 | 48 | An instrumented OkHttp HTTP client provides the following metrics: 49 | 50 | ``` 51 | okhttp3.EventListener.calls-duration 52 | okhttp3.EventListener.calls-end 53 | okhttp3.EventListener.calls-failed 54 | okhttp3.EventListener.calls-start 55 | okhttp3.EventListener.connections-acquired 56 | okhttp3.EventListener.connections-duration 57 | okhttp3.EventListener.connections-end 58 | okhttp3.EventListener.connections-failed 59 | okhttp3.EventListener.connections-released 60 | okhttp3.EventListener.connections-start 61 | okhttp3.EventListener.dns-duration 62 | okhttp3.EventListener.dns-end 63 | okhttp3.EventListener.dns-start 64 | okhttp3.OkHttpClient.cache-request-count 65 | okhttp3.OkHttpClient.cache-hit-count 66 | okhttp3.OkHttpClient.cache-network-count 67 | okhttp3.OkHttpClient.cache-current-size 68 | okhttp3.OkHttpClient.cache-max-size 69 | okhttp3.OkHttpClient.cache-size 70 | okhttp3.OkHttpClient.cache-write-success-count 71 | okhttp3.OkHttpClient.cache-write-abort-count 72 | okhttp3.OkHttpClient.connection-pool-count 73 | okhttp3.OkHttpClient.connection-pool-count-http 74 | okhttp3.OkHttpClient.connection-pool-count-multiplexed 75 | okhttp3.OkHttpClient.connection-pool-idle-count 76 | okhttp3.OkHttpClient.connection-pool-total-count 77 | okhttp3.OkHttpClient.network-requests-completed 78 | okhttp3.OkHttpClient.network-requests-duration 79 | okhttp3.OkHttpClient.network-requests-running 80 | okhttp3.OkHttpClient.network-requests-submitted 81 | ``` 82 | 83 | If you provide a custom name for the instrumented client (i.e. `custom-name`), 84 | the metrics will have the following format: 85 | 86 | ``` 87 | ... 88 | okhttp3.OkHttpClient.custom-name.cache-write-success-count 89 | okhttp3.OkHttpClient.custom-name.cache-write-abort-count 90 | okhttp3.OkHttpClient.custom-name.connection-pool-count 91 | ... 92 | ``` 93 | 94 | Download 95 | -------- 96 | 97 | **Metrics Integration for OkHttp is currently under development.** The API is 98 | not stable and neither is the feature set. 99 | 100 | Download [the latest jar][metrics-okhttp] or depend on Maven: 101 | 102 | ```xml 103 | 104 | com.raskasa.metrics 105 | metrics-okhttp 106 | 0.5.0 107 | 108 | ``` 109 | 110 | or Gradle: 111 | 112 | ```groovy 113 | compile 'com.raskasa.metrics:metrics-okhttp:0.5.0' 114 | ``` 115 | 116 | Snapshots of the development version are available in 117 | [Sonatype's `snapshots` repository][sonatype]. 118 | 119 | License 120 | ------- 121 | 122 | Copyright 2015 Ras Kasa Williams 123 | 124 | Licensed under the Apache License, Version 2.0 (the "License"); 125 | you may not use this file except in compliance with the License. 126 | You may obtain a copy of the License at 127 | 128 | http://www.apache.org/licenses/LICENSE-2.0 129 | 130 | Unless required by applicable law or agreed to in writing, software 131 | distributed under the License is distributed on an "AS IS" BASIS, 132 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 133 | See the License for the specific language governing permissions and 134 | limitations under the License. 135 | 136 | [metrics]: https://dropwizard.github.io/metrics/3.2.3/ 137 | [metrics-okhttp]: https://search.maven.org/remote_content?g=com.raskasa.metrics&a=metrics-okhttp&v=LATEST 138 | [okhttp]: http://square.github.io/okhttp/ 139 | [sonatype]: https://oss.sonatype.org/content/repositories/snapshots/com/raskasa/metrics/ 140 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | Release Process 2 | =============== 3 | 4 | 1. Update `CHANGELOG.md` with release date, new features, fixes, and next 5 | release number. 6 | 7 | 2. Update `README.md` with new usage and download info. 8 | 9 | 3. Commit: `git commit -am "Update project documentation for X.Y.Z."` 10 | 11 | 4. Prepare: `mvn release:prepare release:perform`. If you encounter the 12 | following issue: 13 | 14 | ``` 15 | gpg: signing failed: Inappropriate ioctl for device 16 | ``` 17 | 18 | ... execute the following before Step 4: 19 | 20 | ``` 21 | $ export GPG_TTY=$(tty) 22 | ``` 23 | 24 | 5. Verify and release the new artifacts in the Nexus Repository Manager. 25 | -------------------------------------------------------------------------------- /metrics-okhttp/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | metrics-okhttp-parent 6 | com.raskasa.metrics 7 | 0.5.0-SNAPSHOT 8 | 9 | 10 | metrics-okhttp 11 | Metrics Integration for OkHttp 12 | 13 | 14 | 15 | 16 | io.dropwizard.metrics 17 | metrics-core 18 | 19 | 20 | com.squareup.okhttp3 21 | okhttp 22 | ${okhttp.version} 23 | 24 | 25 | 26 | 27 | com.google.guava 28 | guava 29 | test 30 | 31 | 32 | junit 33 | junit 34 | test 35 | 36 | 37 | org.assertj 38 | assertj-core 39 | test 40 | 41 | 42 | org.mockito 43 | mockito-core 44 | test 45 | 46 | 47 | com.squareup.okhttp3 48 | mockwebserver 49 | test 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /metrics-okhttp/src/main/java/com/raskasa/metrics/okhttp/InstrumentedEventListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Ras Kasa Williams 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 | * http://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 com.raskasa.metrics.okhttp; 17 | 18 | import com.codahale.metrics.Meter; 19 | import com.codahale.metrics.MetricRegistry; 20 | import com.codahale.metrics.Timer; 21 | import java.io.IOException; 22 | import java.net.InetAddress; 23 | import java.net.InetSocketAddress; 24 | import java.net.Proxy; 25 | import java.util.List; 26 | import javax.annotation.Nonnull; 27 | import javax.annotation.Nullable; 28 | import okhttp3.Call; 29 | import okhttp3.Connection; 30 | import okhttp3.EventListener; 31 | import okhttp3.Handshake; 32 | import okhttp3.Protocol; 33 | import okhttp3.Request; 34 | import okhttp3.Response; 35 | 36 | /** 37 | * A client-scoped {@link EventListener} that records metrics around quantity, size, and duration of 38 | * HTTP calls using Dropwizard Metrics. 39 | * 40 | *

This listener will receive ALL analytics events for {@link okhttp3.OkHttpClient the given 41 | * instrumented client}. 42 | * 43 | *

This listener WILL NOT override a user-provided listener. It will ensure the user-provided 44 | * listener receives ALL analytics events as expected. Users usually configure a {@link 45 | * EventListener listener} via {@link okhttp3.OkHttpClient.Builder#eventListener(EventListener)} or 46 | * {@link okhttp3.OkHttpClient.Builder#eventListenerFactory(EventListener.Factory)}). 47 | * 48 | * @see EventListener for semantics and restrictions on listener implementations. 49 | */ 50 | final class InstrumentedEventListener extends EventListener { 51 | static final class Factory implements EventListener.Factory { 52 | private final MetricRegistry registry; 53 | private final EventListener.Factory delegate; 54 | private final String name; 55 | 56 | Factory( 57 | @Nonnull MetricRegistry registry, 58 | @Nonnull EventListener.Factory delegate, 59 | @Nullable String name) { 60 | this.registry = registry; 61 | this.delegate = delegate; 62 | this.name = name; 63 | } 64 | 65 | @Nonnull 66 | @Override 67 | public EventListener create(@Nonnull Call call) { 68 | return new InstrumentedEventListener(this.registry, this.delegate.create(call), this.name); 69 | } 70 | } 71 | 72 | /** 73 | * The user-provided {@link EventListener listener}. 74 | * 75 | *

If a user doesn't configure a listener, this will be {@link EventListener#NONE the default 76 | * listener}. 77 | */ 78 | private final EventListener delegate; 79 | 80 | private final Meter callStart; 81 | private final Meter callEnd; 82 | private final Meter callFailed; 83 | private final Timer callDuration; 84 | private Timer.Context callDurationContext; 85 | 86 | private final Meter dnsStart; 87 | private final Meter dnsEnd; 88 | private final Timer dnsDuration; 89 | private Timer.Context dnsDurationContext; 90 | 91 | private final Meter connectionStart; 92 | private final Meter connectionEnd; 93 | private final Meter connectionFailed; 94 | private final Timer connectionDuration; 95 | private Timer.Context connectionDurationContext; 96 | private final Meter connectionAcquired; 97 | private final Meter connectionReleased; 98 | 99 | InstrumentedEventListener( 100 | @Nonnull MetricRegistry registry, @Nonnull EventListener delegate, @Nullable String name) { 101 | this.delegate = delegate; 102 | 103 | this.callStart = registry.meter(MetricRegistry.name(name, "calls-start")); 104 | this.callEnd = registry.meter(MetricRegistry.name(name, "calls-end")); 105 | this.callFailed = registry.meter(MetricRegistry.name(name, "calls-failed")); 106 | this.callDuration = registry.timer(MetricRegistry.name(name, "calls-duration")); 107 | 108 | this.dnsStart = registry.meter(MetricRegistry.name(name, "dns-start")); 109 | this.dnsEnd = registry.meter(MetricRegistry.name(name, "dns-end")); 110 | this.dnsDuration = registry.timer(MetricRegistry.name(name, "dns-duration")); 111 | 112 | this.connectionStart = registry.meter(MetricRegistry.name(name, "connections-start")); 113 | this.connectionEnd = registry.meter(MetricRegistry.name(name, "connections-end")); 114 | this.connectionFailed = registry.meter(MetricRegistry.name(name, "connections-failed")); 115 | this.connectionDuration = registry.timer(MetricRegistry.name(name, "connections-duration")); 116 | this.connectionAcquired = registry.meter(MetricRegistry.name(name, "connections-acquired")); 117 | this.connectionReleased = registry.meter(MetricRegistry.name(name, "connections-released")); 118 | } 119 | 120 | @Override 121 | public void callStart(@Nonnull Call call) { 122 | this.callStart.mark(); 123 | this.callDurationContext = this.callDuration.time(); 124 | this.delegate.callStart(call); 125 | } 126 | 127 | @Override 128 | public void dnsStart(@Nonnull Call call, @Nonnull String domainName) { 129 | this.dnsStart.mark(); 130 | this.dnsDurationContext = this.dnsDuration.time(); 131 | this.delegate.dnsStart(call, domainName); 132 | } 133 | 134 | @Override 135 | public void dnsEnd( 136 | @Nonnull Call call, @Nonnull String domainName, @Nonnull List inetAddressList) { 137 | this.dnsDurationContext.stop(); 138 | this.dnsEnd.mark(); 139 | this.delegate.dnsEnd(call, domainName, inetAddressList); 140 | } 141 | 142 | @Override 143 | public void connectStart( 144 | @Nonnull Call call, @Nonnull InetSocketAddress inetSocketAddress, @Nonnull Proxy proxy) { 145 | this.connectionStart.mark(); 146 | this.connectionDurationContext = this.connectionDuration.time(); 147 | this.delegate.connectStart(call, inetSocketAddress, proxy); 148 | } 149 | 150 | @Override 151 | public void secureConnectStart(@Nonnull Call call) { 152 | this.delegate.secureConnectStart(call); 153 | } 154 | 155 | @Override 156 | public void secureConnectEnd(@Nonnull Call call, @Nullable Handshake handshake) { 157 | this.delegate.secureConnectEnd(call, handshake); 158 | } 159 | 160 | @Override 161 | public void connectEnd( 162 | @Nonnull Call call, 163 | @Nonnull InetSocketAddress inetSocketAddress, 164 | @Nonnull Proxy proxy, 165 | @Nullable Protocol protocol) { 166 | this.connectionDurationContext.stop(); 167 | this.connectionEnd.mark(); 168 | this.delegate.connectEnd(call, inetSocketAddress, proxy, protocol); 169 | } 170 | 171 | @Override 172 | public void connectFailed( 173 | @Nonnull Call call, 174 | @Nonnull InetSocketAddress inetSocketAddress, 175 | @Nonnull Proxy proxy, 176 | @Nullable Protocol protocol, 177 | @Nonnull IOException ioe) { 178 | this.connectionDurationContext.stop(); 179 | this.connectionFailed.mark(); 180 | this.delegate.connectFailed(call, inetSocketAddress, proxy, protocol, ioe); 181 | } 182 | 183 | @Override 184 | public void connectionAcquired(@Nonnull Call call, @Nonnull Connection connection) { 185 | this.connectionAcquired.mark(); 186 | this.delegate.connectionAcquired(call, connection); 187 | } 188 | 189 | @Override 190 | public void connectionReleased(@Nonnull Call call, @Nonnull Connection connection) { 191 | this.connectionReleased.mark(); 192 | this.delegate.connectionReleased(call, connection); 193 | } 194 | 195 | @Override 196 | public void requestHeadersStart(@Nonnull Call call) { 197 | this.delegate.requestHeadersStart(call); 198 | } 199 | 200 | @Override 201 | public void requestHeadersEnd(@Nonnull Call call, @Nonnull Request request) { 202 | this.delegate.requestHeadersEnd(call, request); 203 | } 204 | 205 | @Override 206 | public void requestBodyStart(@Nonnull Call call) { 207 | this.delegate.requestBodyStart(call); 208 | } 209 | 210 | @Override 211 | public void requestBodyEnd(@Nonnull Call call, long byteCount) { 212 | this.delegate.requestBodyEnd(call, byteCount); 213 | } 214 | 215 | @Override 216 | public void requestFailed(@Nonnull Call call, @Nonnull IOException ioe) { 217 | this.delegate.requestFailed(call, ioe); 218 | } 219 | 220 | @Override 221 | public void responseHeadersStart(@Nonnull Call call) { 222 | this.delegate.responseHeadersStart(call); 223 | } 224 | 225 | @Override 226 | public void responseHeadersEnd(@Nonnull Call call, @Nonnull Response response) { 227 | this.delegate.responseHeadersEnd(call, response); 228 | } 229 | 230 | @Override 231 | public void responseBodyStart(@Nonnull Call call) { 232 | this.delegate.responseBodyStart(call); 233 | } 234 | 235 | @Override 236 | public void responseBodyEnd(@Nonnull Call call, long byteCount) { 237 | this.delegate.responseBodyEnd(call, byteCount); 238 | } 239 | 240 | @Override 241 | public void responseFailed(@Nonnull Call call, @Nonnull IOException ioe) { 242 | this.delegate.responseFailed(call, ioe); 243 | } 244 | 245 | @Override 246 | public void callEnd(@Nonnull Call call) { 247 | this.callDurationContext.stop(); 248 | this.callEnd.mark(); 249 | this.delegate.callEnd(call); 250 | } 251 | 252 | @Override 253 | public void callFailed(@Nonnull Call call, @Nonnull IOException ioe) { 254 | this.callDurationContext.stop(); 255 | this.callFailed.mark(); 256 | this.delegate.callFailed(call, ioe); 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /metrics-okhttp/src/main/java/com/raskasa/metrics/okhttp/InstrumentedInterceptor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Ras Kasa Williams 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 | * http://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 com.raskasa.metrics.okhttp; 17 | 18 | import com.codahale.metrics.Counter; 19 | import com.codahale.metrics.Meter; 20 | import com.codahale.metrics.MetricRegistry; 21 | import com.codahale.metrics.Timer; 22 | import java.io.IOException; 23 | import okhttp3.Interceptor; 24 | import okhttp3.Response; 25 | 26 | /** 27 | * An {@link Interceptor} that monitors the number of submitted, running, and completed network 28 | * requests. Also, keeps a {@link Timer} for the request duration. 29 | */ 30 | final class InstrumentedInterceptor implements Interceptor { 31 | private final Meter submitted; 32 | private final Counter running; 33 | private final Meter completed; 34 | private final Timer duration; 35 | 36 | InstrumentedInterceptor(MetricRegistry registry, String name) { 37 | this.submitted = registry.meter(MetricRegistry.name(name, "network-requests-submitted")); 38 | this.running = registry.counter(MetricRegistry.name(name, "network-requests-running")); 39 | this.completed = registry.meter(MetricRegistry.name(name, "network-requests-completed")); 40 | this.duration = registry.timer(MetricRegistry.name(name, "network-requests-duration")); 41 | } 42 | 43 | @Override 44 | public Response intercept(Chain chain) throws IOException { 45 | submitted.mark(); 46 | running.inc(); 47 | final Timer.Context context = duration.time(); 48 | try { 49 | return chain.proceed(chain.request()); 50 | } finally { 51 | context.stop(); 52 | running.dec(); 53 | completed.mark(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /metrics-okhttp/src/main/java/com/raskasa/metrics/okhttp/InstrumentedOkHttpClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Ras Kasa Williams 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 | * http://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 com.raskasa.metrics.okhttp; 17 | 18 | import static com.codahale.metrics.MetricRegistry.name; 19 | 20 | import com.codahale.metrics.Gauge; 21 | import com.codahale.metrics.MetricRegistry; 22 | import com.codahale.metrics.RatioGauge; 23 | import java.io.IOException; 24 | import java.net.Proxy; 25 | import java.net.ProxySelector; 26 | import java.util.List; 27 | import javax.net.SocketFactory; 28 | import javax.net.ssl.HostnameVerifier; 29 | import javax.net.ssl.SSLSocketFactory; 30 | import okhttp3.Authenticator; 31 | import okhttp3.Cache; 32 | import okhttp3.Call; 33 | import okhttp3.CertificatePinner; 34 | import okhttp3.ConnectionPool; 35 | import okhttp3.ConnectionSpec; 36 | import okhttp3.CookieJar; 37 | import okhttp3.Dispatcher; 38 | import okhttp3.Dns; 39 | import okhttp3.EventListener; 40 | import okhttp3.Interceptor; 41 | import okhttp3.OkHttpClient; 42 | import okhttp3.Protocol; 43 | import okhttp3.Request; 44 | import okhttp3.WebSocket; 45 | import okhttp3.WebSocketListener; 46 | import org.slf4j.Logger; 47 | import org.slf4j.LoggerFactory; 48 | 49 | /** Wraps an {@link OkHttpClient} in order to provide data about its internals. */ 50 | final class InstrumentedOkHttpClient extends OkHttpClient { 51 | private static final Logger LOG = LoggerFactory.getLogger(InstrumentedOkHttpClient.class); 52 | private final MetricRegistry registry; 53 | private OkHttpClient rawClient; 54 | private final String name; 55 | 56 | InstrumentedOkHttpClient(MetricRegistry registry, OkHttpClient rawClient, String name) { 57 | this.rawClient = rawClient; 58 | this.registry = registry; 59 | this.name = name; 60 | instrumentHttpCache(); 61 | instrumentConnectionPool(); 62 | instrumentNetworkRequests(); 63 | instrumentEventListener(); 64 | } 65 | 66 | /** 67 | * Generates an identifier, with a common prefix, in order to uniquely identify the {@code metric} 68 | * in the registry. 69 | * 70 | *

The generated identifier includes: 71 | * 72 | *

77 | */ 78 | String metricId(String metric) { 79 | return name(OkHttpClient.class, name, metric); 80 | } 81 | 82 | private void instrumentHttpCache() { 83 | if (cache() == null) return; 84 | 85 | registry.register( 86 | metricId("cache-request-count"), 87 | new Gauge() { 88 | @Override 89 | public Integer getValue() { 90 | // The number of HTTP requests issued since this cache was created. 91 | return rawClient.cache().requestCount(); 92 | } 93 | }); 94 | registry.register( 95 | metricId("cache-hit-count"), 96 | new Gauge() { 97 | @Override 98 | public Integer getValue() { 99 | // ... the number of those requests that required network use. 100 | return rawClient.cache().hitCount(); 101 | } 102 | }); 103 | registry.register( 104 | metricId("cache-network-count"), 105 | new Gauge() { 106 | @Override 107 | public Integer getValue() { 108 | // ... the number of those requests whose responses were served by the cache. 109 | return rawClient.cache().networkCount(); 110 | } 111 | }); 112 | registry.register( 113 | metricId("cache-write-success-count"), 114 | new Gauge() { 115 | @Override 116 | public Integer getValue() { 117 | return rawClient.cache().writeSuccessCount(); 118 | } 119 | }); 120 | registry.register( 121 | metricId("cache-write-abort-count"), 122 | new Gauge() { 123 | @Override 124 | public Integer getValue() { 125 | return rawClient.cache().writeAbortCount(); 126 | } 127 | }); 128 | final Gauge currentCacheSize = 129 | new Gauge() { 130 | @Override 131 | public Long getValue() { 132 | try { 133 | return rawClient.cache().size(); 134 | } catch (IOException ex) { 135 | LOG.error(ex.getMessage(), ex); 136 | return -1L; 137 | } 138 | } 139 | }; 140 | final Gauge maxCacheSize = 141 | new Gauge() { 142 | @Override 143 | public Long getValue() { 144 | return rawClient.cache().maxSize(); 145 | } 146 | }; 147 | registry.register(metricId("cache-current-size"), currentCacheSize); 148 | registry.register(metricId("cache-max-size"), maxCacheSize); 149 | registry.register( 150 | metricId("cache-size"), 151 | new RatioGauge() { 152 | @Override 153 | protected Ratio getRatio() { 154 | return Ratio.of(currentCacheSize.getValue(), maxCacheSize.getValue()); 155 | } 156 | }); 157 | } 158 | 159 | private void instrumentConnectionPool() { 160 | if (connectionPool() == null) { 161 | rawClient = rawClient.newBuilder().connectionPool(new ConnectionPool()).build(); 162 | } 163 | 164 | registry.register( 165 | metricId("connection-pool-total-count"), 166 | new Gauge() { 167 | @Override 168 | public Integer getValue() { 169 | return rawClient.connectionPool().connectionCount(); 170 | } 171 | }); 172 | registry.register( 173 | metricId("connection-pool-idle-count"), 174 | new Gauge() { 175 | @Override 176 | public Integer getValue() { 177 | return rawClient.connectionPool().idleConnectionCount(); 178 | } 179 | }); 180 | } 181 | 182 | private void instrumentNetworkRequests() { 183 | rawClient = 184 | rawClient 185 | .newBuilder() 186 | .addNetworkInterceptor( 187 | new InstrumentedInterceptor(registry, name(OkHttpClient.class, this.name))) 188 | .build(); 189 | } 190 | 191 | private void instrumentEventListener() { 192 | final EventListener.Factory delegate = this.rawClient.eventListenerFactory(); 193 | this.rawClient = 194 | this.rawClient 195 | .newBuilder() 196 | .eventListenerFactory( 197 | new InstrumentedEventListener.Factory( 198 | this.registry, delegate, name(EventListener.class, this.name))) 199 | .build(); 200 | } 201 | 202 | @Override 203 | public Authenticator authenticator() { 204 | return rawClient.authenticator(); 205 | } 206 | 207 | @Override 208 | public Cache cache() { 209 | return rawClient.cache(); 210 | } 211 | 212 | @Override 213 | public CertificatePinner certificatePinner() { 214 | return rawClient.certificatePinner(); 215 | } 216 | 217 | @Override 218 | public ConnectionPool connectionPool() { 219 | return rawClient.connectionPool(); 220 | } 221 | 222 | @Override 223 | public List connectionSpecs() { 224 | return rawClient.connectionSpecs(); 225 | } 226 | 227 | @Override 228 | public int connectTimeoutMillis() { 229 | return rawClient.connectTimeoutMillis(); 230 | } 231 | 232 | @Override 233 | public CookieJar cookieJar() { 234 | return rawClient.cookieJar(); 235 | } 236 | 237 | @Override 238 | public Dispatcher dispatcher() { 239 | return rawClient.dispatcher(); 240 | } 241 | 242 | @Override 243 | public Dns dns() { 244 | return rawClient.dns(); 245 | } 246 | 247 | @Override 248 | public boolean followRedirects() { 249 | return rawClient.followRedirects(); 250 | } 251 | 252 | @Override 253 | public boolean followSslRedirects() { 254 | return rawClient.followSslRedirects(); 255 | } 256 | 257 | @Override 258 | public HostnameVerifier hostnameVerifier() { 259 | return rawClient.hostnameVerifier(); 260 | } 261 | 262 | @Override 263 | public List interceptors() { 264 | return rawClient.interceptors(); 265 | } 266 | 267 | @Override 268 | public List networkInterceptors() { 269 | return rawClient.networkInterceptors(); 270 | } 271 | 272 | @Override 273 | public OkHttpClient.Builder newBuilder() { 274 | return rawClient.newBuilder(); 275 | } 276 | 277 | @Override 278 | public Call newCall(Request request) { 279 | return rawClient.newCall(request); 280 | } 281 | 282 | @Override 283 | public WebSocket newWebSocket(Request request, WebSocketListener listener) { 284 | return rawClient.newWebSocket(request, listener); 285 | } 286 | 287 | @Override 288 | public int pingIntervalMillis() { 289 | return rawClient.pingIntervalMillis(); 290 | } 291 | 292 | @Override 293 | public List protocols() { 294 | return rawClient.protocols(); 295 | } 296 | 297 | @Override 298 | public Proxy proxy() { 299 | return rawClient.proxy(); 300 | } 301 | 302 | @Override 303 | public Authenticator proxyAuthenticator() { 304 | return rawClient.proxyAuthenticator(); 305 | } 306 | 307 | @Override 308 | public ProxySelector proxySelector() { 309 | return rawClient.proxySelector(); 310 | } 311 | 312 | @Override 313 | public int readTimeoutMillis() { 314 | return rawClient.readTimeoutMillis(); 315 | } 316 | 317 | @Override 318 | public boolean retryOnConnectionFailure() { 319 | return rawClient.retryOnConnectionFailure(); 320 | } 321 | 322 | @Override 323 | public SocketFactory socketFactory() { 324 | return rawClient.socketFactory(); 325 | } 326 | 327 | @Override 328 | public SSLSocketFactory sslSocketFactory() { 329 | return rawClient.sslSocketFactory(); 330 | } 331 | 332 | @Override 333 | public int writeTimeoutMillis() { 334 | return rawClient.writeTimeoutMillis(); 335 | } 336 | 337 | @Override 338 | public boolean equals(Object obj) { 339 | return (obj instanceof InstrumentedOkHttpClient 340 | && rawClient.equals(((InstrumentedOkHttpClient) obj).rawClient)) 341 | || rawClient.equals(obj); 342 | } 343 | 344 | @Override 345 | public String toString() { 346 | return rawClient.toString(); 347 | } 348 | } 349 | -------------------------------------------------------------------------------- /metrics-okhttp/src/main/java/com/raskasa/metrics/okhttp/InstrumentedOkHttpClients.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Ras Kasa Williams 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 | * http://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 com.raskasa.metrics.okhttp; 17 | 18 | import com.codahale.metrics.MetricRegistry; 19 | import okhttp3.OkHttpClient; 20 | 21 | /** Static factory methods for instrumenting an {@link OkHttpClient}. */ 22 | public final class InstrumentedOkHttpClients { 23 | 24 | /** Create and instrument an {@link OkHttpClient}. */ 25 | public static OkHttpClient create(MetricRegistry registry) { 26 | return new InstrumentedOkHttpClient(registry, new OkHttpClient(), null); 27 | } 28 | 29 | /** Instrument the given {@link OkHttpClient}. */ 30 | public static OkHttpClient create(MetricRegistry registry, OkHttpClient client) { 31 | return new InstrumentedOkHttpClient(registry, client, null); 32 | } 33 | 34 | /** 35 | * Create and instrument an {@link OkHttpClient} and give it the provided {@code name}. 36 | * 37 | *

{@code name} provides an identifier for the instrumented client. This is useful in 38 | * situations where you have more than one instrumented client in your application. 39 | */ 40 | public static OkHttpClient create(MetricRegistry registry, String name) { 41 | return new InstrumentedOkHttpClient(registry, new OkHttpClient(), name); 42 | } 43 | 44 | /** 45 | * Instrument the given {@link OkHttpClient} and give it the provided name. 46 | * 47 | *

{@code name} provides an identifier for the instrumented client. This is useful in 48 | * situations where you have more than one instrumented client in your application. 49 | */ 50 | public static OkHttpClient create(MetricRegistry registry, OkHttpClient client, String name) { 51 | return new InstrumentedOkHttpClient(registry, client, name); 52 | } 53 | 54 | private InstrumentedOkHttpClients() { 55 | // No instances. 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /metrics-okhttp/src/test/java/com/raskasa/metrics/okhttp/InstrumentedOkHttpClientTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Ras Kasa Williams 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 | * http://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 com.raskasa.metrics.okhttp; 17 | 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | import static org.junit.Assert.fail; 20 | 21 | import com.codahale.metrics.MetricRegistry; 22 | import com.google.common.util.concurrent.MoreExecutors; 23 | import java.io.IOException; 24 | import java.text.DateFormat; 25 | import java.text.SimpleDateFormat; 26 | import java.util.Arrays; 27 | import java.util.Date; 28 | import java.util.List; 29 | import java.util.Locale; 30 | import java.util.TimeZone; 31 | import java.util.concurrent.TimeUnit; 32 | import okhttp3.Cache; 33 | import okhttp3.Call; 34 | import okhttp3.Callback; 35 | import okhttp3.Dispatcher; 36 | import okhttp3.EventListener; 37 | import okhttp3.HttpUrl; 38 | import okhttp3.OkHttpClient; 39 | import okhttp3.RecordingEventListener; 40 | import okhttp3.Request; 41 | import okhttp3.Response; 42 | import okhttp3.mockwebserver.MockResponse; 43 | import okhttp3.mockwebserver.MockWebServer; 44 | import org.assertj.core.api.Assertions; 45 | import org.junit.Before; 46 | import org.junit.Rule; 47 | import org.junit.Test; 48 | import org.junit.rules.TemporaryFolder; 49 | 50 | public final class InstrumentedOkHttpClientTest { 51 | private MetricRegistry registry; 52 | private OkHttpClient rawClient; 53 | 54 | @Before 55 | public void setUp() throws Exception { 56 | registry = new MetricRegistry(); 57 | rawClient = new OkHttpClient(); 58 | } 59 | 60 | @Rule public MockWebServer server = new MockWebServer(); 61 | @Rule public TemporaryFolder cacheRule = new TemporaryFolder(); 62 | 63 | @Test 64 | public void syncNetworkRequestsAreInstrumented() throws IOException { 65 | MockResponse mockResponse = 66 | new MockResponse() 67 | .addHeader("Cache-Control:public, max-age=31536000") 68 | .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) 69 | .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) 70 | .setBody("one"); 71 | server.enqueue(mockResponse); 72 | HttpUrl baseUrl = server.url("/"); 73 | 74 | InstrumentedOkHttpClient client = new InstrumentedOkHttpClient(registry, rawClient, null); 75 | 76 | assertThat(registry.getMeters().get(client.metricId("network-requests-submitted")).getCount()) 77 | .isEqualTo(0); 78 | assertThat(registry.getCounters().get(client.metricId("network-requests-running")).getCount()) 79 | .isEqualTo(0); 80 | assertThat(registry.getMeters().get(client.metricId("network-requests-completed")).getCount()) 81 | .isEqualTo(0); 82 | assertThat(registry.getTimers().get(client.metricId("network-requests-duration")).getCount()) 83 | .isEqualTo(0); 84 | 85 | Request request = new Request.Builder().url(baseUrl).build(); 86 | 87 | try (Response response = client.newCall(request).execute()) { 88 | assertThat(registry.getMeters().get(client.metricId("network-requests-submitted")).getCount()) 89 | .isEqualTo(1); 90 | assertThat(registry.getCounters().get(client.metricId("network-requests-running")).getCount()) 91 | .isEqualTo(0); 92 | assertThat(registry.getMeters().get(client.metricId("network-requests-completed")).getCount()) 93 | .isEqualTo(1); 94 | assertThat(registry.getTimers().get(client.metricId("network-requests-duration")).getCount()) 95 | .isEqualTo(1); 96 | } 97 | } 98 | 99 | @Test 100 | public void aSyncNetworkRequestsAreInstrumented() { 101 | MockResponse mockResponse = 102 | new MockResponse() 103 | .addHeader("Cache-Control:public, max-age=31536000") 104 | .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) 105 | .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) 106 | .setBody("one"); 107 | server.enqueue(mockResponse); 108 | HttpUrl baseUrl = server.url("/"); 109 | 110 | final InstrumentedOkHttpClient client = new InstrumentedOkHttpClient(registry, rawClient, null); 111 | 112 | assertThat(registry.getMeters().get(client.metricId("network-requests-submitted")).getCount()) 113 | .isEqualTo(0); 114 | assertThat(registry.getCounters().get(client.metricId("network-requests-running")).getCount()) 115 | .isEqualTo(0); 116 | assertThat(registry.getMeters().get(client.metricId("network-requests-completed")).getCount()) 117 | .isEqualTo(0); 118 | assertThat(registry.getTimers().get(client.metricId("network-requests-duration")).getCount()) 119 | .isEqualTo(0); 120 | 121 | final Request request = new Request.Builder().url(baseUrl).build(); 122 | 123 | client 124 | .newCall(request) 125 | .enqueue( 126 | new Callback() { 127 | @Override 128 | public void onFailure(Call call, IOException e) { 129 | fail(); 130 | } 131 | 132 | @Override 133 | public void onResponse(Call call, Response response) throws IOException { 134 | assertThat( 135 | registry 136 | .getMeters() 137 | .get(client.metricId("network-requests-submitted")) 138 | .getCount()) 139 | .isEqualTo(1); 140 | assertThat( 141 | registry 142 | .getCounters() 143 | .get(client.metricId("network-requests-running")) 144 | .getCount()) 145 | .isEqualTo(0); 146 | assertThat( 147 | registry 148 | .getMeters() 149 | .get(client.metricId("network-requests-completed")) 150 | .getCount()) 151 | .isEqualTo(1); 152 | assertThat( 153 | registry 154 | .getTimers() 155 | .get(client.metricId("network-requests-duration")) 156 | .getCount()) 157 | .isEqualTo(1); 158 | response.body().close(); 159 | } 160 | }); 161 | } 162 | 163 | @Test 164 | public void httpCacheIsInstrumented() throws Exception { 165 | MockResponse mockResponse = 166 | new MockResponse() 167 | .addHeader("Cache-Control:public, max-age=31536000") 168 | .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) 169 | .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) 170 | .setBody("one"); 171 | server.enqueue(mockResponse); 172 | HttpUrl baseUrl = server.url("/"); 173 | 174 | Cache cache = new Cache(cacheRule.getRoot(), Long.MAX_VALUE); 175 | rawClient = rawClient.newBuilder().cache(cache).build(); 176 | InstrumentedOkHttpClient client = new InstrumentedOkHttpClient(registry, rawClient, null); 177 | 178 | assertThat(registry.getGauges().get(client.metricId("cache-max-size")).getValue()) 179 | .isEqualTo(Long.MAX_VALUE); 180 | assertThat(registry.getGauges().get(client.metricId("cache-current-size")).getValue()) 181 | .isEqualTo(0L); 182 | 183 | Request request = new Request.Builder().url(baseUrl).build(); 184 | Response response = client.newCall(request).execute(); 185 | 186 | assertThat(registry.getGauges().get(client.metricId("cache-current-size")).getValue()) 187 | .isEqualTo(rawClient.cache().size()); 188 | 189 | response.body().close(); 190 | } 191 | 192 | @Test 193 | public void connectionPoolIsInstrumented() throws Exception { 194 | server.enqueue(new MockResponse().setBody("one")); 195 | server.enqueue(new MockResponse().setBody("two")); 196 | HttpUrl baseUrl = server.url("/"); 197 | 198 | InstrumentedOkHttpClient client = new InstrumentedOkHttpClient(registry, rawClient, null); 199 | 200 | assertThat(registry.getGauges().get(client.metricId("connection-pool-total-count")).getValue()) 201 | .isEqualTo(0); 202 | assertThat(registry.getGauges().get(client.metricId("connection-pool-idle-count")).getValue()) 203 | .isEqualTo(0); 204 | 205 | Request req1 = new Request.Builder().url(baseUrl).build(); 206 | Request req2 = new Request.Builder().url(baseUrl).build(); 207 | Response resp1 = client.newCall(req1).execute(); 208 | Response resp2 = client.newCall(req2).execute(); 209 | 210 | assertThat(registry.getGauges().get(client.metricId("connection-pool-total-count")).getValue()) 211 | .isEqualTo(2); 212 | assertThat(registry.getGauges().get(client.metricId("connection-pool-idle-count")).getValue()) 213 | .isEqualTo(0); 214 | 215 | resp1.body().close(); 216 | resp2.body().close(); 217 | } 218 | 219 | @Test 220 | public void eventListenerIsInstrumented() throws Exception { 221 | server.enqueue(new MockResponse().setBody("one")); 222 | server.enqueue(new MockResponse().setBody("two")); 223 | HttpUrl baseUrl = server.url("/"); 224 | 225 | InstrumentedOkHttpClient client = new InstrumentedOkHttpClient(registry, rawClient, null); 226 | 227 | assertThat(registry.getMeters().keySet()) 228 | .doesNotContain(MetricRegistry.name(EventListener.class, "calls-start")); 229 | assertThat(registry.getMeters().keySet()) 230 | .doesNotContain(MetricRegistry.name(EventListener.class, "calls-end")); 231 | assertThat(registry.getMeters().keySet()) 232 | .doesNotContain(MetricRegistry.name(EventListener.class, "calls-failed")); 233 | assertThat(registry.getTimers().keySet()) 234 | .doesNotContain(MetricRegistry.name(EventListener.class, "calls-duration")); 235 | assertThat(registry.getMeters().keySet()) 236 | .doesNotContain(MetricRegistry.name(EventListener.class, "dns-start")); 237 | assertThat(registry.getMeters().keySet()) 238 | .doesNotContain(MetricRegistry.name(EventListener.class, "dns-end")); 239 | assertThat(registry.getTimers().keySet()) 240 | .doesNotContain(MetricRegistry.name(EventListener.class, "dns-duration")); 241 | assertThat(registry.getMeters().keySet()) 242 | .doesNotContain(MetricRegistry.name(EventListener.class, "connections-start")); 243 | assertThat(registry.getMeters().keySet()) 244 | .doesNotContain(MetricRegistry.name(EventListener.class, "connections-end")); 245 | assertThat(registry.getMeters().keySet()) 246 | .doesNotContain(MetricRegistry.name(EventListener.class, "connections-failed")); 247 | assertThat(registry.getTimers().keySet()) 248 | .doesNotContain(MetricRegistry.name(EventListener.class, "connections-duration")); 249 | assertThat(registry.getMeters().keySet()) 250 | .doesNotContain(MetricRegistry.name(EventListener.class, "connections-acquired")); 251 | assertThat(registry.getMeters().keySet()) 252 | .doesNotContain(MetricRegistry.name(EventListener.class, "connections-released")); 253 | 254 | Request req1 = new Request.Builder().url(baseUrl).build(); 255 | Request req2 = new Request.Builder().url(baseUrl).build(); 256 | Response resp1 = client.newCall(req1).execute(); 257 | Response resp2 = client.newCall(req2).execute(); 258 | 259 | assertThat( 260 | registry 261 | .getMeters() 262 | .get(MetricRegistry.name(EventListener.class, "calls-start")) 263 | .getCount()) 264 | .isEqualTo(2); 265 | assertThat( 266 | registry 267 | .getMeters() 268 | .get(MetricRegistry.name(EventListener.class, "calls-end")) 269 | .getCount()) 270 | .isEqualTo(0); 271 | assertThat( 272 | registry 273 | .getMeters() 274 | .get(MetricRegistry.name(EventListener.class, "calls-failed")) 275 | .getCount()) 276 | .isEqualTo(0); 277 | assertThat( 278 | registry 279 | .getTimers() 280 | .get(MetricRegistry.name(EventListener.class, "calls-duration")) 281 | .getCount()) 282 | .isEqualTo(0); 283 | assertThat( 284 | registry 285 | .getMeters() 286 | .get(MetricRegistry.name(EventListener.class, "dns-start")) 287 | .getCount()) 288 | .isEqualTo(2); 289 | assertThat( 290 | registry 291 | .getMeters() 292 | .get(MetricRegistry.name(EventListener.class, "dns-end")) 293 | .getCount()) 294 | .isEqualTo(2); 295 | assertThat( 296 | registry 297 | .getTimers() 298 | .get(MetricRegistry.name(EventListener.class, "dns-duration")) 299 | .getCount()) 300 | .isEqualTo(2); 301 | assertThat( 302 | registry 303 | .getMeters() 304 | .get(MetricRegistry.name(EventListener.class, "connections-start")) 305 | .getCount()) 306 | .isEqualTo(2); 307 | assertThat( 308 | registry 309 | .getMeters() 310 | .get(MetricRegistry.name(EventListener.class, "connections-end")) 311 | .getCount()) 312 | .isEqualTo(2); 313 | assertThat( 314 | registry 315 | .getMeters() 316 | .get(MetricRegistry.name(EventListener.class, "connections-failed")) 317 | .getCount()) 318 | .isEqualTo(0); 319 | assertThat( 320 | registry 321 | .getTimers() 322 | .get(MetricRegistry.name(EventListener.class, "connections-duration")) 323 | .getCount()) 324 | .isEqualTo(2); 325 | assertThat( 326 | registry 327 | .getMeters() 328 | .get(MetricRegistry.name(EventListener.class, "connections-acquired")) 329 | .getCount()) 330 | .isEqualTo(2); 331 | assertThat( 332 | registry 333 | .getMeters() 334 | .get(MetricRegistry.name(EventListener.class, "connections-released")) 335 | .getCount()) 336 | .isEqualTo(0); 337 | 338 | // Some end/release events don't fire until after the response bodies are closed/consumed. 339 | resp1.close(); 340 | resp2.close(); 341 | 342 | assertThat( 343 | registry 344 | .getMeters() 345 | .get(MetricRegistry.name(EventListener.class, "calls-start")) 346 | .getCount()) 347 | .isEqualTo(2); 348 | assertThat( 349 | registry 350 | .getMeters() 351 | .get(MetricRegistry.name(EventListener.class, "calls-end")) 352 | .getCount()) 353 | .isEqualTo(2); 354 | assertThat( 355 | registry 356 | .getMeters() 357 | .get(MetricRegistry.name(EventListener.class, "calls-failed")) 358 | .getCount()) 359 | .isEqualTo(0); 360 | assertThat( 361 | registry 362 | .getTimers() 363 | .get(MetricRegistry.name(EventListener.class, "calls-duration")) 364 | .getCount()) 365 | .isEqualTo(2); 366 | assertThat( 367 | registry 368 | .getMeters() 369 | .get(MetricRegistry.name(EventListener.class, "connections-released")) 370 | .getCount()) 371 | .isEqualTo(2); 372 | } 373 | 374 | @Test 375 | public void eventListenerDelegatesSuccessfully() throws Exception { 376 | server.enqueue(new MockResponse().setBody("one")); 377 | server.enqueue(new MockResponse().setBody("two")); 378 | HttpUrl baseUrl = server.url("/"); 379 | 380 | RecordingEventListener delegate = new RecordingEventListener(); 381 | OkHttpClient configureClient = rawClient.newBuilder().eventListener(delegate).build(); 382 | 383 | InstrumentedOkHttpClient client = new InstrumentedOkHttpClient(registry, configureClient, null); 384 | Request request = new Request.Builder().url(baseUrl).build(); 385 | Response response = client.newCall(request).execute(); 386 | response.close(); 387 | 388 | List expectedEvents = 389 | Arrays.asList( 390 | "CallStart", 391 | "DnsStart", 392 | "DnsEnd", 393 | "ConnectStart", 394 | "ConnectEnd", 395 | "ConnectionAcquired", 396 | "RequestHeadersStart", 397 | "RequestHeadersEnd", 398 | "ResponseHeadersStart", 399 | "ResponseHeadersEnd", 400 | "ResponseBodyStart", 401 | "ResponseBodyEnd", 402 | "ConnectionReleased", 403 | "CallEnd"); 404 | Assertions.assertThat(delegate.recordedEventTypes()).isEqualTo(expectedEvents); 405 | } 406 | 407 | @Test 408 | public void executorServiceIsInstrumented() throws Exception { 409 | server.enqueue(new MockResponse().setBody("one")); 410 | server.enqueue(new MockResponse().setBody("two")); 411 | HttpUrl baseUrl = server.url("/"); 412 | 413 | // Force the requests to execute on this unit tests thread. 414 | rawClient = 415 | rawClient 416 | .newBuilder() 417 | .dispatcher(new Dispatcher(MoreExecutors.newDirectExecutorService())) 418 | .build(); 419 | InstrumentedOkHttpClient client = new InstrumentedOkHttpClient(registry, rawClient, null); 420 | 421 | assertThat(registry.getMeters().get(client.metricId("network-requests-submitted")).getCount()) 422 | .isEqualTo(0); 423 | assertThat(registry.getMeters().get(client.metricId("network-requests-completed")).getCount()) 424 | .isEqualTo(0); 425 | 426 | Request req1 = new Request.Builder().url(baseUrl).build(); 427 | Request req2 = new Request.Builder().url(baseUrl).build(); 428 | client.newCall(req1).enqueue(new TestCallback()); 429 | client.newCall(req2).enqueue(new TestCallback()); 430 | 431 | assertThat(registry.getMeters().get(client.metricId("network-requests-submitted")).getCount()) 432 | .isEqualTo(2); 433 | assertThat(registry.getMeters().get(client.metricId("network-requests-completed")).getCount()) 434 | .isEqualTo(2); 435 | } 436 | 437 | @Test 438 | public void providedNameUsedInMetricId() { 439 | String prefix = "custom"; 440 | String baseId = "network-requests-submitted"; 441 | 442 | assertThat(registry.getMeters()).isEmpty(); 443 | 444 | InstrumentedOkHttpClient client = new InstrumentedOkHttpClient(registry, rawClient, prefix); 445 | String generatedId = client.metricId(baseId); 446 | 447 | assertThat(registry.getMeters().get(generatedId)).isNotNull(); 448 | } 449 | 450 | /** 451 | * @param delta the offset from the current date to use. Negative values yield dates in the past; 452 | * positive values yield dates in the future. 453 | */ 454 | private String formatDate(long delta, TimeUnit timeUnit) { 455 | return formatDate(new Date(System.currentTimeMillis() + timeUnit.toMillis(delta))); 456 | } 457 | 458 | private String formatDate(Date date) { 459 | DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); 460 | rfc1123.setTimeZone(TimeZone.getTimeZone("GMT")); 461 | return rfc1123.format(date); 462 | } 463 | 464 | private static final class TestCallback implements Callback { 465 | @Override 466 | public void onFailure(Call call, IOException e) {} 467 | 468 | @Override 469 | public void onResponse(Call call, Response response) throws IOException { 470 | response.body().close(); 471 | } 472 | } 473 | } 474 | -------------------------------------------------------------------------------- /metrics-okhttp/src/test/java/com/raskasa/metrics/okhttp/InstrumentedOkHttpClientsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Ras Kasa Williams 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 | * http://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 com.raskasa.metrics.okhttp; 17 | 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | import static org.mockito.Mockito.mock; 20 | 21 | import com.codahale.metrics.MetricRegistry; 22 | import okhttp3.OkHttpClient; 23 | import org.junit.Before; 24 | import org.junit.Test; 25 | 26 | public final class InstrumentedOkHttpClientsTest { 27 | private MetricRegistry registry; 28 | 29 | @Before 30 | public void setUp() { 31 | registry = mock(MetricRegistry.class); 32 | } 33 | 34 | @Test 35 | public void instrumentDefaultClient() { 36 | OkHttpClient client = InstrumentedOkHttpClients.create(registry); 37 | 38 | // The connection, read, and write timeouts are the only configurations applied by default. 39 | assertThat(client.connectTimeoutMillis()).isEqualTo(10_000); 40 | assertThat(client.readTimeoutMillis()).isEqualTo(10_000); 41 | assertThat(client.writeTimeoutMillis()).isEqualTo(10_000); 42 | } 43 | 44 | @Test 45 | public void instrumentAndNameDefaultClient() { 46 | OkHttpClient client = InstrumentedOkHttpClients.create(registry, "custom"); 47 | 48 | // The connection, read, and write timeouts are the only configurations applied by default. 49 | assertThat(client.connectTimeoutMillis()).isEqualTo(10_000); 50 | assertThat(client.readTimeoutMillis()).isEqualTo(10_000); 51 | assertThat(client.writeTimeoutMillis()).isEqualTo(10_000); 52 | } 53 | 54 | @Test 55 | public void instrumentProvidedClient() { 56 | OkHttpClient rawClient = new OkHttpClient(); 57 | OkHttpClient client = InstrumentedOkHttpClients.create(registry, rawClient); 58 | assertThatClientsAreEqual(client, rawClient); 59 | } 60 | 61 | @Test 62 | public void instrumentAndNameProvidedClient() { 63 | OkHttpClient rawClient = new OkHttpClient(); 64 | OkHttpClient client = InstrumentedOkHttpClients.create(registry, rawClient, "custom"); 65 | assertThatClientsAreEqual(client, rawClient); 66 | } 67 | 68 | private void assertThatClientsAreEqual(OkHttpClient clientA, OkHttpClient clientB) { 69 | assertThat(clientA.authenticator()).isEqualTo(clientB.authenticator()); 70 | assertThat(clientA.cache()).isEqualTo(clientB.cache()); 71 | assertThat(clientA.certificatePinner()).isEqualTo(clientB.certificatePinner()); 72 | assertThat(clientA.connectionPool()).isEqualTo(clientB.connectionPool()); 73 | assertThat(clientA.connectionSpecs()).isEqualTo(clientB.connectionSpecs()); 74 | assertThat(clientA.connectTimeoutMillis()).isEqualTo(clientB.connectTimeoutMillis()); 75 | assertThat(clientA.cookieJar()).isEqualTo(clientB.cookieJar()); 76 | // We don't assert on Dispatcher since we create a new instance during instrumentation. 77 | assertThat(clientA.dns()).isEqualTo(clientB.dns()); 78 | assertThat(clientA.followRedirects()).isEqualTo(clientB.followRedirects()); 79 | assertThat(clientA.followSslRedirects()).isEqualTo(clientB.followSslRedirects()); 80 | assertThat(clientA.hostnameVerifier()).isEqualTo(clientB.hostnameVerifier()); 81 | assertThat(clientA.interceptors().size()).isEqualTo(clientB.interceptors().size()); 82 | assertThat(clientA.pingIntervalMillis()).isEqualTo(clientB.pingIntervalMillis()); 83 | assertThat(clientA.protocols()).isEqualTo(clientB.protocols()); 84 | assertThat(clientA.proxy()).isEqualTo(clientB.proxy()); 85 | assertThat(clientA.proxyAuthenticator()).isEqualTo(clientB.proxyAuthenticator()); 86 | assertThat(clientA.proxySelector()).isEqualTo(clientB.proxySelector()); 87 | assertThat(clientA.readTimeoutMillis()).isEqualTo(clientB.readTimeoutMillis()); 88 | assertThat(clientA.retryOnConnectionFailure()).isEqualTo(clientB.retryOnConnectionFailure()); 89 | assertThat(clientA.socketFactory()).isEqualTo(clientB.socketFactory()); 90 | assertThat(clientA.sslSocketFactory()).isEqualTo(clientB.sslSocketFactory()); 91 | assertThat(clientA.writeTimeoutMillis()).isEqualTo(clientB.writeTimeoutMillis()); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /metrics-okhttp/src/test/java/okhttp3/RecordingEventListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 Square, 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 | * http://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 okhttp3; 17 | 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | 20 | import java.io.IOException; 21 | import java.net.InetAddress; 22 | import java.net.InetSocketAddress; 23 | import java.net.Proxy; 24 | import java.util.ArrayList; 25 | import java.util.Arrays; 26 | import java.util.Deque; 27 | import java.util.List; 28 | import java.util.concurrent.ConcurrentLinkedDeque; 29 | import javax.annotation.Nullable; 30 | 31 | public final class RecordingEventListener extends EventListener { 32 | final Deque eventSequence = new ConcurrentLinkedDeque<>(); 33 | 34 | final List forbiddenLocks = new ArrayList<>(); 35 | 36 | /** Confirm that the thread does not hold a lock on {@code lock} during the callback. */ 37 | public void forbidLock(Object lock) { 38 | forbiddenLocks.add(lock); 39 | } 40 | 41 | /** 42 | * Removes recorded events up to (and including) an event is found whose class equals {@code 43 | * eventClass} and returns it. 44 | */ 45 | public T removeUpToEvent(Class eventClass) { 46 | Object event = eventSequence.poll(); 47 | while (event != null && !eventClass.isInstance(event)) { 48 | event = eventSequence.poll(); 49 | } 50 | if (event == null) throw new AssertionError(); 51 | return eventClass.cast(event); 52 | } 53 | 54 | public List recordedEventTypes() { 55 | List eventTypes = new ArrayList<>(); 56 | for (CallEvent event : eventSequence) { 57 | eventTypes.add(event.getName()); 58 | } 59 | return eventTypes; 60 | } 61 | 62 | public void clearAllEvents() { 63 | eventSequence.clear(); 64 | } 65 | 66 | private void logEvent(CallEvent e) { 67 | for (Object lock : forbiddenLocks) { 68 | assertThat(Thread.holdsLock(lock)).overridingErrorMessage(lock.toString()).isFalse(); 69 | } 70 | 71 | CallEvent startEvent = e.closes(); 72 | 73 | if (startEvent != null) { 74 | assertThat(eventSequence.contains(startEvent)) 75 | .overridingErrorMessage(e.getName() + " without matching " + startEvent.getName()) 76 | .isTrue(); 77 | } 78 | 79 | eventSequence.offer(e); 80 | } 81 | 82 | @Override 83 | public void dnsStart(Call call, String domainName) { 84 | logEvent(new DnsStart(call, domainName)); 85 | } 86 | 87 | @Override 88 | public void dnsEnd(Call call, String domainName, List inetAddressList) { 89 | logEvent(new DnsEnd(call, domainName, inetAddressList)); 90 | } 91 | 92 | @Override 93 | public void connectStart(Call call, InetSocketAddress inetSocketAddress, Proxy proxy) { 94 | logEvent(new ConnectStart(call, inetSocketAddress, proxy)); 95 | } 96 | 97 | @Override 98 | public void secureConnectStart(Call call) { 99 | logEvent(new SecureConnectStart(call)); 100 | } 101 | 102 | @Override 103 | public void secureConnectEnd(Call call, Handshake handshake) { 104 | logEvent(new SecureConnectEnd(call, handshake)); 105 | } 106 | 107 | @Override 108 | public void connectEnd( 109 | Call call, InetSocketAddress inetSocketAddress, @Nullable Proxy proxy, Protocol protocol) { 110 | logEvent(new ConnectEnd(call, inetSocketAddress, proxy, protocol)); 111 | } 112 | 113 | @Override 114 | public void connectFailed( 115 | Call call, 116 | InetSocketAddress inetSocketAddress, 117 | Proxy proxy, 118 | @Nullable Protocol protocol, 119 | IOException ioe) { 120 | logEvent(new ConnectFailed(call, inetSocketAddress, proxy, protocol, ioe)); 121 | } 122 | 123 | @Override 124 | public void connectionAcquired(Call call, Connection connection) { 125 | logEvent(new ConnectionAcquired(call, connection)); 126 | } 127 | 128 | @Override 129 | public void connectionReleased(Call call, Connection connection) { 130 | logEvent(new ConnectionReleased(call, connection)); 131 | } 132 | 133 | @Override 134 | public void callStart(Call call) { 135 | logEvent(new CallStart(call)); 136 | } 137 | 138 | @Override 139 | public void requestHeadersStart(Call call) { 140 | logEvent(new RequestHeadersStart(call)); 141 | } 142 | 143 | @Override 144 | public void requestHeadersEnd(Call call, Request request) { 145 | logEvent(new RequestHeadersEnd(call, request.headers.byteCount())); 146 | } 147 | 148 | @Override 149 | public void requestBodyStart(Call call) { 150 | logEvent(new RequestBodyStart(call)); 151 | } 152 | 153 | @Override 154 | public void requestBodyEnd(Call call, long byteCount) { 155 | logEvent(new RequestBodyEnd(call, byteCount)); 156 | } 157 | 158 | @Override 159 | public void requestFailed(Call call, IOException ioe) { 160 | logEvent(new RequestFailed(call, ioe)); 161 | } 162 | 163 | @Override 164 | public void responseHeadersStart(Call call) { 165 | logEvent(new ResponseHeadersStart(call)); 166 | } 167 | 168 | @Override 169 | public void responseHeadersEnd(Call call, Response response) { 170 | logEvent(new ResponseHeadersEnd(call, response.headers.byteCount())); 171 | } 172 | 173 | @Override 174 | public void responseBodyStart(Call call) { 175 | logEvent(new ResponseBodyStart(call)); 176 | } 177 | 178 | @Override 179 | public void responseBodyEnd(Call call, long byteCount) { 180 | logEvent(new ResponseBodyEnd(call, byteCount)); 181 | } 182 | 183 | @Override 184 | public void responseFailed(Call call, IOException ioe) { 185 | logEvent(new ResponseFailed(call, ioe)); 186 | } 187 | 188 | @Override 189 | public void callEnd(Call call) { 190 | logEvent(new CallEnd(call)); 191 | } 192 | 193 | @Override 194 | public void callFailed(Call call, IOException ioe) { 195 | logEvent(new CallFailed(call, ioe)); 196 | } 197 | 198 | static class CallEvent { 199 | final Call call; 200 | final List params; 201 | 202 | CallEvent(Call call, Object... params) { 203 | this.call = call; 204 | this.params = Arrays.asList(params); 205 | } 206 | 207 | public String getName() { 208 | return getClass().getSimpleName(); 209 | } 210 | 211 | @Override 212 | public boolean equals(Object o) { 213 | if (this == o) return true; 214 | if (!(o instanceof CallEvent)) return false; 215 | 216 | CallEvent callEvent = (CallEvent) o; 217 | 218 | if (!getName().equals(callEvent.getName())) return false; 219 | if (!call.equals(callEvent.call)) return false; 220 | return params.equals(callEvent.params); 221 | } 222 | 223 | @Override 224 | public int hashCode() { 225 | int result = call.hashCode(); 226 | result = 31 * result + getName().hashCode(); 227 | result = 31 * result + params.hashCode(); 228 | return result; 229 | } 230 | 231 | public @Nullable CallEvent closes() { 232 | return null; 233 | } 234 | } 235 | 236 | static final class DnsStart extends CallEvent { 237 | final String domainName; 238 | 239 | DnsStart(Call call, String domainName) { 240 | super(call, domainName); 241 | this.domainName = domainName; 242 | } 243 | } 244 | 245 | static final class DnsEnd extends CallEvent { 246 | final String domainName; 247 | final List inetAddressList; 248 | 249 | DnsEnd(Call call, String domainName, List inetAddressList) { 250 | super(call, domainName, inetAddressList); 251 | this.domainName = domainName; 252 | this.inetAddressList = inetAddressList; 253 | } 254 | 255 | @Override 256 | public @Nullable CallEvent closes() { 257 | return new DnsStart(call, domainName); 258 | } 259 | } 260 | 261 | static final class ConnectStart extends CallEvent { 262 | final InetSocketAddress inetSocketAddress; 263 | final Proxy proxy; 264 | 265 | ConnectStart(Call call, InetSocketAddress inetSocketAddress, Proxy proxy) { 266 | super(call, inetSocketAddress, proxy); 267 | this.inetSocketAddress = inetSocketAddress; 268 | this.proxy = proxy; 269 | } 270 | } 271 | 272 | static final class ConnectEnd extends CallEvent { 273 | final InetSocketAddress inetSocketAddress; 274 | final Protocol protocol; 275 | final Proxy proxy; 276 | 277 | ConnectEnd(Call call, InetSocketAddress inetSocketAddress, Proxy proxy, Protocol protocol) { 278 | super(call, inetSocketAddress, proxy, protocol); 279 | this.inetSocketAddress = inetSocketAddress; 280 | this.proxy = proxy; 281 | this.protocol = protocol; 282 | } 283 | 284 | @Override 285 | public CallEvent closes() { 286 | return new ConnectStart(call, inetSocketAddress, proxy); 287 | } 288 | } 289 | 290 | static final class ConnectFailed extends CallEvent { 291 | final InetSocketAddress inetSocketAddress; 292 | final Protocol protocol; 293 | final Proxy proxy; 294 | final IOException ioe; 295 | 296 | ConnectFailed( 297 | Call call, 298 | InetSocketAddress inetSocketAddress, 299 | Proxy proxy, 300 | Protocol protocol, 301 | IOException ioe) { 302 | super(call, inetSocketAddress, proxy, protocol, ioe); 303 | this.inetSocketAddress = inetSocketAddress; 304 | this.proxy = proxy; 305 | this.protocol = protocol; 306 | this.ioe = ioe; 307 | } 308 | 309 | @Override 310 | public @Nullable CallEvent closes() { 311 | return new ConnectStart(call, inetSocketAddress, proxy); 312 | } 313 | } 314 | 315 | static final class SecureConnectStart extends CallEvent { 316 | SecureConnectStart(Call call) { 317 | super(call); 318 | } 319 | } 320 | 321 | static final class SecureConnectEnd extends CallEvent { 322 | final Handshake handshake; 323 | 324 | SecureConnectEnd(Call call, Handshake handshake) { 325 | super(call, handshake); 326 | this.handshake = handshake; 327 | } 328 | 329 | @Override 330 | public @Nullable CallEvent closes() { 331 | return new SecureConnectStart(call); 332 | } 333 | } 334 | 335 | static final class ConnectionAcquired extends CallEvent { 336 | final Connection connection; 337 | 338 | ConnectionAcquired(Call call, Connection connection) { 339 | super(call, connection); 340 | this.connection = connection; 341 | } 342 | } 343 | 344 | static final class ConnectionReleased extends CallEvent { 345 | final Connection connection; 346 | 347 | ConnectionReleased(Call call, Connection connection) { 348 | super(call, connection); 349 | this.connection = connection; 350 | } 351 | 352 | @Override 353 | public @Nullable CallEvent closes() { 354 | return new ConnectionAcquired(call, connection); 355 | } 356 | } 357 | 358 | static final class CallStart extends CallEvent { 359 | CallStart(Call call) { 360 | super(call); 361 | } 362 | } 363 | 364 | static final class CallEnd extends CallEvent { 365 | CallEnd(Call call) { 366 | super(call); 367 | } 368 | 369 | @Override 370 | public @Nullable CallEvent closes() { 371 | return new CallStart(call); 372 | } 373 | } 374 | 375 | static final class CallFailed extends CallEvent { 376 | final IOException ioe; 377 | 378 | CallFailed(Call call, IOException ioe) { 379 | super(call, ioe); 380 | this.ioe = ioe; 381 | } 382 | } 383 | 384 | static final class RequestHeadersStart extends CallEvent { 385 | RequestHeadersStart(Call call) { 386 | super(call); 387 | } 388 | } 389 | 390 | static final class RequestHeadersEnd extends CallEvent { 391 | final long headerLength; 392 | 393 | RequestHeadersEnd(Call call, long headerLength) { 394 | super(call, headerLength); 395 | this.headerLength = headerLength; 396 | } 397 | 398 | @Override 399 | public @Nullable CallEvent closes() { 400 | return new RequestHeadersStart(call); 401 | } 402 | } 403 | 404 | static final class RequestBodyStart extends CallEvent { 405 | RequestBodyStart(Call call) { 406 | super(call); 407 | } 408 | } 409 | 410 | static final class RequestBodyEnd extends CallEvent { 411 | final long bytesWritten; 412 | 413 | RequestBodyEnd(Call call, long bytesWritten) { 414 | super(call, bytesWritten); 415 | this.bytesWritten = bytesWritten; 416 | } 417 | 418 | @Override 419 | public @Nullable CallEvent closes() { 420 | return new RequestBodyStart(call); 421 | } 422 | } 423 | 424 | static final class RequestFailed extends CallEvent { 425 | final IOException ioe; 426 | 427 | RequestFailed(Call call, IOException ioe) { 428 | super(call, ioe); 429 | this.ioe = ioe; 430 | } 431 | } 432 | 433 | static final class ResponseHeadersStart extends CallEvent { 434 | ResponseHeadersStart(Call call) { 435 | super(call); 436 | } 437 | } 438 | 439 | static final class ResponseHeadersEnd extends CallEvent { 440 | final long headerLength; 441 | 442 | ResponseHeadersEnd(Call call, long headerLength) { 443 | super(call, headerLength); 444 | this.headerLength = headerLength; 445 | } 446 | 447 | @Override 448 | public @Nullable CallEvent closes() { 449 | return new RequestHeadersStart(call); 450 | } 451 | } 452 | 453 | static final class ResponseBodyStart extends CallEvent { 454 | ResponseBodyStart(Call call) { 455 | super(call); 456 | } 457 | } 458 | 459 | static final class ResponseBodyEnd extends CallEvent { 460 | final long bytesRead; 461 | 462 | ResponseBodyEnd(Call call, long bytesRead) { 463 | super(call, bytesRead); 464 | this.bytesRead = bytesRead; 465 | } 466 | 467 | @Override 468 | public @Nullable CallEvent closes() { 469 | return new ResponseBodyStart(call); 470 | } 471 | } 472 | 473 | static final class ResponseFailed extends CallEvent { 474 | final IOException ioe; 475 | 476 | ResponseFailed(Call call, IOException ioe) { 477 | super(call, ioe); 478 | this.ioe = ioe; 479 | } 480 | } 481 | } 482 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | 6 | org.sonatype.oss 7 | oss-parent 8 | 7 9 | 10 | 11 | com.raskasa.metrics 12 | metrics-okhttp-parent 13 | 0.5.0-SNAPSHOT 14 | pom 15 | Metrics Integration for OkHttp (Parent) 16 | 17 | 18 | metrics-okhttp 19 | sample 20 | 21 | 22 | 23 | 24 | UTF-8 25 | 26 | 27 | 1.8 28 | 4.2.3 29 | 3.12.4 30 | 3.14.9 31 | 32 | 33 | 3.21.0 34 | 31.0.1-android 35 | 4.13.2 36 | 37 | 38 | 39 | https://github.com/raskasa/metrics-okhttp 40 | scm:git:https://github.com/raskasa/metrics-okhttp.git 41 | scm:git:git@github.com:raskasa/metrics-okhttp.git 42 | HEAD 43 | 44 | 45 | 46 | GitHub Issues 47 | https://github.com/raskasa/metrics-okhttp/issues 48 | 49 | 50 | 51 | 52 | Apache 2.0 53 | http://www.apache.org/licenses/LICENSE-2.0.txt 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | io.dropwizard.metrics 62 | metrics-core 63 | ${metrics.version} 64 | 65 | 66 | com.squareup.okhttp3 67 | okhttp 68 | ${okhttp.version} 69 | 70 | 71 | 72 | com.google.code.findbugs 73 | jsr305 74 | provided 75 | 76 | 77 | 78 | 79 | com.google.guava 80 | guava 81 | ${guava.version} 82 | test 83 | 84 | 85 | junit 86 | junit 87 | ${junit.version} 88 | test 89 | 90 | 91 | org.assertj 92 | assertj-core 93 | ${assertj.version} 94 | test 95 | 96 | 97 | org.mockito 98 | mockito-core 99 | ${mockito.version} 100 | test 101 | 102 | 103 | com.squareup.okhttp3 104 | mockwebserver 105 | ${okhttp.version} 106 | test 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | org.apache.maven.plugins 116 | maven-compiler-plugin 117 | 3.8.1 118 | 119 | ${java.version} 120 | ${java.version} 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | com.coveo 129 | fmt-maven-plugin 130 | 2.9 131 | 132 | 133 | 134 | format 135 | 136 | 137 | 138 | 139 | 140 | org.apache.maven.plugins 141 | maven-release-plugin 142 | 2.5.3 143 | 144 | true 145 | 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /sample/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | 6 | metrics-okhttp-parent 7 | com.raskasa.metrics 8 | 0.5.0-SNAPSHOT 9 | 10 | 11 | sample 12 | Sample 13 | 14 | 15 | 16 | io.dropwizard.metrics 17 | metrics-core 18 | 19 | 20 | com.raskasa.metrics 21 | metrics-okhttp 22 | ${project.version} 23 | 24 | 25 | com.squareup.okhttp3 26 | okhttp 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /sample/src/main/java/com/raskasa/metrics/okhttp/sample/App.java: -------------------------------------------------------------------------------- 1 | package com.raskasa.metrics.okhttp.sample; 2 | 3 | import com.codahale.metrics.ConsoleReporter; 4 | import com.codahale.metrics.MetricRegistry; 5 | import com.raskasa.metrics.okhttp.InstrumentedOkHttpClients; 6 | import java.util.concurrent.TimeUnit; 7 | import okhttp3.OkHttpClient; 8 | import okhttp3.Request; 9 | import okhttp3.Response; 10 | 11 | /** Fetches user information from the GitHub public API */ 12 | public final class App { 13 | public static void main(String[] args) throws Exception { 14 | MetricRegistry metrics = new MetricRegistry(); 15 | 16 | ConsoleReporter reporter = 17 | ConsoleReporter.forRegistry(metrics) 18 | .convertRatesTo(TimeUnit.SECONDS) 19 | .convertDurationsTo(TimeUnit.MILLISECONDS) 20 | .build(); 21 | reporter.start(15, TimeUnit.SECONDS); 22 | 23 | OkHttpClient client = InstrumentedOkHttpClients.create(metrics); 24 | 25 | // noinspection InfiniteLoopStatement 26 | for (; ; ) { 27 | 28 | Request request = 29 | new Request.Builder().url("https://api.github.com/repos/raskasa/metrics-okhttp").build(); 30 | 31 | try (Response response = client.newCall(request).execute()) { 32 | System.out.println(response.body().string()); 33 | } 34 | 35 | Thread.sleep(15_000); // 15 seconds 36 | } 37 | } 38 | } 39 | --------------------------------------------------------------------------------