├── .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 | *
73 | *
the fully qualified name of the {@link OkHttpClient} class
74 | *
the name of the instrumented client, if provided
75 | *
the given {@code metric}
76 | *
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 | *