├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── configuration └── ide │ └── eclipse │ └── formatting │ └── formatting.xml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── opentracing-jfr-tracer ├── .classpath ├── .gitignore ├── .project ├── .settings │ ├── org.eclipse.buildship.core.prefs │ └── org.eclipse.jdt.core.prefs ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── jdks.gradle ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── io │ │ │ └── opentracing │ │ │ └── contrib │ │ │ └── jfrtracer │ │ │ ├── JfrTracerFactory.java │ │ │ └── impl │ │ │ ├── jfr │ │ │ ├── AbstractJfrEmitter.java │ │ │ ├── AbstractJfrSpanEmitter.java │ │ │ ├── JfrEmitter.java │ │ │ ├── JfrEmitterFactory.java │ │ │ ├── JfrScopeEmitterImpl.java │ │ │ └── JfrSpanEmitterImpl.java │ │ │ └── wrapper │ │ │ ├── ScopeManagerWrapper.java │ │ │ ├── ScopeWrapper.java │ │ │ ├── SpanBuilderWrapper.java │ │ │ ├── SpanWrapper.java │ │ │ └── TracerWrapper.java │ └── java11 │ │ └── io │ │ └── opentracing │ │ └── contrib │ │ └── jfrtracer │ │ └── impl │ │ └── jfr │ │ ├── JfrScopeEmitterImpl.java │ │ └── JfrSpanEmitterImpl.java │ └── test │ ├── java │ └── io │ │ └── opentracing │ │ └── contrib │ │ └── jfrtracer │ │ ├── DifferentSpanTest.java │ │ ├── ImplementationsJFRTest.java │ │ ├── JfrTestUtils.java │ │ ├── JfrTracerTest.java │ │ └── impl │ │ └── wrapper │ │ └── SpanBuilderWrapperTest.java │ ├── java11 │ └── io │ │ └── opentracing │ │ └── contrib │ │ └── jfrtracer │ │ ├── DifferentSpanTest.java │ │ ├── ImplementationsJFRTest.java │ │ ├── JfrTestUtils.java │ │ └── JfrTracerTest.java │ └── resources │ └── io │ └── opentracing │ └── contrib │ └── jfrtracer │ └── opentracing.jfc └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | /.gradle/ 2 | /bin/ 3 | /build/ 4 | *.bak 5 | /.nb-gradle/ 6 | nbproject/ 7 | nb-configuration.xml 8 | nbactions.xml 9 | .attach_pid* 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | addons: 2 | hosts: 3 | - localhost 4 | language: java 5 | install: true 6 | dist: trusty 7 | jdk: oraclejdk8 8 | script: 9 | - wget https://github.com/sormuras/bach/raw/master/install-jdk.sh 10 | - sudo chmod 755 ./install-jdk.sh 11 | - sudo ./install-jdk.sh -F 11 -L GPL -t jdk-11 -e -s 12 | - export ORG_GRADLE_PROJECT_JAVA_8=$JAVA_HOME 13 | - export ORG_GRADLE_PROJECT_JAVA_11=/home/travis/build/opentracing-contrib/java-jfr-tracer/jdk-11 14 | - export JAVA_HOME=$ORG_GRADLE_PROJECT_JAVA_8 15 | - ./gradlew build 16 | branches: 17 | only: 18 | - master 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/opentracing-contrib/java-jfr-tracer.svg?branch=master)](https://travis-ci.org/opentracing-contrib/java-jfr-tracer) 2 | # JFR Tracer 3 | This is a delegating tracer to be used with OpenTracing. It records span and scope information into the JDK Flight Recorder, enabling very deep tracing capabilities. 4 | 5 | ## Using the JFR Tracer 6 | First add a dependency to it. For example, in Maven (note that this version has not been released yet, we're waiting for opentracing v0.32.0 to come on line): 7 | 8 | ```xml 9 | 10 | io.opentracing.contrib 11 | opentracing-jfr-tracer 12 | 0.0.4 13 | 14 | ``` 15 | 16 | Next, in whatever code you use to set up the OpenTracing tracer, wrap your tracer in the JFR tracer: 17 | 18 | ```java 19 | GlobalTracer.register( 20 | JfrTracerFactory.create(yourFavouriteTracer)); 21 | ``` 22 | 23 | ## Supported Tracers 24 | The JFR tracer supports all tracers that support OpenTracing 0.32.0 or later. 25 | 26 | ## Supported Java Versions 27 | The JFR tracer supports running on Oracle JDK 8+ (except Oracle JDK 9 and 10) and OpenJDK 11+. 28 | 29 | ## Example 30 | An example app with OpenTracing enabled, and which is using the JFR tracer, can be found here: 31 | [https://github.com/thegreystone/problematic-microservices](https://github.com/thegreystone/problematic-microservices) 32 | 33 | ## Building 34 | To build the JFR Tracer, and install it into the local maven repo, first ensure that you 35 | have installed an Oracle JDK 8, and an Open JDK 11. These will be required to build the 36 | tracer. Once built, the tracer can be used with Oracle JDK 8+ (except Oracle JDK 9 and 10), and OpenJDK 11+. 37 | 38 | Ensure that the following two environment variables are set to the JAVA_HOME of the JDKs: 39 | 40 | ``` 41 | JAVA_8 42 | JAVA_11 43 | ``` 44 | 45 | Once that is done, simply run: 46 | 47 | ```bash 48 | ./gradlew publishToMavenLocal 49 | ``` 50 | 51 | Note that you will need to have an Oracle JDK 8 and an OpenJDK (or Oracle JDK) JDK 11 available. Parts of the code will be compiled using JDK 8 and parts using JDK 11. Note that the resulting MRJAR will run on Oracle JDK 8 and later, and OpenJDK (or Oracle JDK) 11 and later. 52 | 53 | 54 | ## About 55 | This tracer was built for Code One 2018 as an example of using JFR and OpenTracing together to provide cross process, and when needed very deep, tracing capabilities, using open source technologies. 56 | 57 | If you find this project useful, please consider contributing. 58 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | allprojects{ 2 | apply plugin: 'java-library' 3 | } -------------------------------------------------------------------------------- /configuration/ide/eclipse/formatting/formatting.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opentracing-contrib/java-jfr-tracer/b89065f3bb403480c842593fa9e000419816c068/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Dec 12 17:50:12 CET 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.0-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/.gitignore: -------------------------------------------------------------------------------- 1 | /.gradle/ 2 | /build/ 3 | bin/ -------------------------------------------------------------------------------- /opentracing-jfr-tracer/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | opentracing-jfr-tracer 4 | Provides a OpenTracing tracer which records information to JFR 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.buildship.core.gradleprojectbuilder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.buildship.core.gradleprojectnature 22 | 23 | 24 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/.settings/org.eclipse.buildship.core.prefs: -------------------------------------------------------------------------------- 1 | connection.project.dir= 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled 3 | org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore 4 | org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull 5 | org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= 6 | org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault 7 | org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= 8 | org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable 9 | org.eclipse.jdt.core.compiler.annotation.nullable.secondary= 10 | org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled 11 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 12 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=11 13 | org.eclipse.jdt.core.compiler.compliance=11 14 | org.eclipse.jdt.core.compiler.problem.APILeak=warning 15 | org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning 16 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 17 | org.eclipse.jdt.core.compiler.problem.autoboxing=ignore 18 | org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning 19 | org.eclipse.jdt.core.compiler.problem.deadCode=warning 20 | org.eclipse.jdt.core.compiler.problem.deprecation=warning 21 | org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled 22 | org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled 23 | org.eclipse.jdt.core.compiler.problem.discouragedReference=warning 24 | org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore 25 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 26 | org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore 27 | org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore 28 | org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled 29 | org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore 30 | org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning 31 | org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning 32 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=ignore 33 | org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning 34 | org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled 35 | org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning 36 | org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning 37 | org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore 38 | org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore 39 | org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning 40 | org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore 41 | org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore 42 | org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled 43 | org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore 44 | org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore 45 | org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled 46 | org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore 47 | org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore 48 | org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning 49 | org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning 50 | org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore 51 | org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning 52 | org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning 53 | org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error 54 | org.eclipse.jdt.core.compiler.problem.nullReference=warning 55 | org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error 56 | org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning 57 | org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning 58 | org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore 59 | org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning 60 | org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore 61 | org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore 62 | org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore 63 | org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning 64 | org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning 65 | org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore 66 | org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore 67 | org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore 68 | org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore 69 | org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore 70 | org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled 71 | org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning 72 | org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled 73 | org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled 74 | org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled 75 | org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore 76 | org.eclipse.jdt.core.compiler.problem.terminalDeprecation=warning 77 | org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning 78 | org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled 79 | org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning 80 | org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning 81 | org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore 82 | org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning 83 | org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=warning 84 | org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=disabled 85 | org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=info 86 | org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore 87 | org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore 88 | org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore 89 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore 90 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled 91 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled 92 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled 93 | org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore 94 | org.eclipse.jdt.core.compiler.problem.unusedImport=warning 95 | org.eclipse.jdt.core.compiler.problem.unusedLabel=warning 96 | org.eclipse.jdt.core.compiler.problem.unusedLocal=warning 97 | org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore 98 | org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore 99 | org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled 100 | org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled 101 | org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled 102 | org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning 103 | org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore 104 | org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning 105 | org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning 106 | org.eclipse.jdt.core.compiler.source=11 107 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java-library' 2 | apply plugin: 'maven-publish' 3 | apply plugin: 'signing' 4 | apply from: 'jdks.gradle' 5 | 6 | repositories { 7 | mavenCentral() 8 | mavenLocal() 9 | } 10 | 11 | sourceSets { 12 | java11 { 13 | java { 14 | srcDirs = ['src/main/java11'] 15 | compileClasspath += main.output.classesDirs 16 | runtimeClasspath += main.output.classesDirs 17 | } 18 | } 19 | 20 | testJava11 { 21 | java { 22 | srcDirs = ['src/test/java11'] 23 | compileClasspath += java11.output.classesDirs + main.output.classesDirs 24 | runtimeClasspath += java11.output.classesDirs + main.output.classesDirs 25 | } 26 | } 27 | } 28 | configurations { 29 | java11Compile { 30 | extendsFrom compile 31 | } 32 | 33 | testJava11Compile { 34 | extendsFrom testCompile 35 | } 36 | } 37 | 38 | dependencies { 39 | compile 'io.opentracing:opentracing-api:0.32.0' 40 | testCompile 'io.opentracing:opentracing-mock:0.32.0' 41 | testCompile 'io.jaegertracing:jaeger-core:0.35.2' 42 | testCompile 'io.opentracing.brave:brave-opentracing:0.34.0' 43 | testCompile 'io.opentracing.contrib:opentracing-concurrent:0.2.0' 44 | testCompile 'org.awaitility:awaitility:3.1.3' 45 | testCompile 'org.junit.jupiter:junit-jupiter-api:5.3.1' 46 | testCompile 'org.junit.jupiter:junit-jupiter-engine:5.3.1' 47 | } 48 | 49 | compileJava { 50 | options.compilerArgs.addAll(['-Xlint:all,-deprecation', '-Werror']) 51 | sourceCompatibility = 1.8 52 | targetCompatibility = 1.8 53 | } 54 | 55 | compileTestJava { 56 | options.compilerArgs.addAll(['-Xlint:all,-deprecation,-path']) 57 | sourceCompatibility = compileJava.sourceCompatibility 58 | targetCompatibility = compileJava.targetCompatibility 59 | } 60 | 61 | test { 62 | def RESOLVED_8 = project.hasProperty('JAVA_8') ? project.getProperty('JAVA_8') : System.env.JAVA_8 63 | useJUnitPlatform() 64 | executable = "${RESOLVED_8}/bin/java" 65 | forkEvery = 1 66 | testLogging { 67 | events "passed", "skipped", "failed" 68 | exceptionFormat "full" 69 | } 70 | } 71 | 72 | compileJava11Java { 73 | options.compilerArgs.addAll(['--release', '11', '-Xlint:all', '-Werror']) 74 | sourceCompatibility = 11 75 | targetCompatibility = 11 76 | } 77 | 78 | compileTestJava11Java { 79 | options.compilerArgs.addAll(['--release', '11', '-Xlint:all']) 80 | sourceCompatibility = compileJava11Java.sourceCompatibility 81 | targetCompatibility = compileJava11Java.targetCompatibility 82 | } 83 | 84 | task testJava11(type: Test) { 85 | def RESOLVED_11 = project.hasProperty('JAVA_11') ? project.getProperty('JAVA_11') : System.env.JAVA_11 86 | dependsOn testJava11Classes 87 | testClassesDirs = sourceSets.testJava11.output.classesDirs 88 | classpath = sourceSets.testJava11.runtimeClasspath 89 | useJUnitPlatform() 90 | executable = "${RESOLVED_11}/bin/java" 91 | testLogging { 92 | events "passed", "skipped", "failed" 93 | exceptionFormat "full" 94 | } 95 | } 96 | 97 | test.dependsOn testJava11 98 | 99 | jar { 100 | into('META-INF/versions/11') { 101 | from sourceSets.java11.output 102 | } 103 | manifest.attributes( 104 | 'Multi-Release': 'true', 105 | ) 106 | } 107 | 108 | javadoc { 109 | source = sourceSets.main.allJava 110 | classpath = configurations.compile 111 | include '**DelegatingJfrTracer**' 112 | } 113 | 114 | task javadocJar(type: Jar) { 115 | classifier = 'javadoc' 116 | from javadoc 117 | } 118 | 119 | task sourcesJar(type: Jar) { 120 | classifier = 'sources' 121 | from sourceSets.main.allSource 122 | } 123 | 124 | artifacts { 125 | archives javadocJar, sourcesJar 126 | } 127 | 128 | publishing { 129 | publications { 130 | mavenJava(MavenPublication) { 131 | artifact sourcesJar 132 | artifact javadocJar 133 | groupId = 'io.opentracing.contrib' 134 | artifactId = 'jfr-tracer' 135 | 136 | from components.java 137 | 138 | pom { 139 | name = 'JFR Tracer' 140 | description = 'An OpenTracing Tracer which records contextual information into the JDK Flight Recorder' 141 | url = 'https://github.com/opentracing-contrib/java-jfr-tracer' 142 | 143 | licenses { 144 | license { 145 | name = 'Apache v2.0' 146 | url = 'https://www.apache.org/licenses/LICENSE-2.0' 147 | } 148 | } 149 | 150 | developers { 151 | developer { 152 | id = 'thegreystone' 153 | name = 'Marcus Hirt' 154 | email = 'marcus@hirt.se' 155 | } 156 | developer { 157 | id = 'sfriberg' 158 | name = 'Staffan Friberg' 159 | email = 'sfriberg@kth.se' 160 | } 161 | } 162 | 163 | scm { 164 | connection = 'scm:git:https://github.com/opentracing-contrib/java-jfr-tracer.git' 165 | developerConnection = 'scm:git:https://github.com/opentracing-contrib/java-jfr-tracer.git' 166 | url = 'https://github.com/opentracing-contrib/java-jfr-tracer' 167 | } 168 | } 169 | } 170 | } 171 | } 172 | 173 | def ossrhUsername = project.findProperty('ossrhUsername') ?: '' 174 | def ossrhPassword = project.findProperty('ossrhPassword') ?: '' 175 | 176 | if(ossrhUsername?.trim() && ossrhPassword?.trim()){ 177 | apply plugin: 'signing' 178 | 179 | repositories { 180 | maven { 181 | def releasesRepoUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 182 | def snapshotsRepoUrl = "https://oss.sonatype.org/content/repositories/snapshots/" 183 | url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl 184 | credentials { 185 | username ossrhUsername 186 | password ossrhPassword 187 | } 188 | } 189 | } 190 | 191 | signing { 192 | sign publishing.publications.mavenJava 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/gradle.properties: -------------------------------------------------------------------------------- 1 | version = 0.0.4-SNAPSHOT 2 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opentracing-contrib/java-jfr-tracer/b89065f3bb403480c842593fa9e000419816c068/opentracing-jfr-tracer/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /opentracing-jfr-tracer/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.0-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/jdks.gradle: -------------------------------------------------------------------------------- 1 | String compat(String src) { 2 | if (src.contains('.')) { 3 | src.substring(src.lastIndexOf('.')+1) 4 | } else { 5 | src 6 | } 7 | } 8 | 9 | // We will always need to use the appropriate Java version to build the various 10 | // components. This is since we want to run on JDK 8 and above. Since the JFR 11 | // APIs changed in JDK 9, we will need to use these specific JDKs to build... 12 | project.afterEvaluate { 13 | tasks.withType(JavaCompile) { 14 | def version = compat(sourceCompatibility) 15 | def jdkHome = project.ext.has("JAVA_${version}") ? project.ext.get("JAVA_${version}") : System.getenv("JAVA_${version}") 16 | if (!jdkHome) { 17 | println "Warning: Please set path to JDK ${sourceCompatibility} using Gradle property or environment variable JAVA_${version}" 18 | println "Falling back to current JDK" 19 | } else { 20 | options.fork = true 21 | options.forkOptions.javaHome = file(jdkHome) 22 | doFirst { 23 | println "$name compiles using JDK $version, $jdkHome" 24 | } 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /opentracing-jfr-tracer/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'opentracing-jfr-tracer' 2 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/JfrTracerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer; 17 | 18 | import io.opentracing.Tracer; 19 | import io.opentracing.contrib.jfrtracer.impl.wrapper.TracerWrapper; 20 | 21 | import java.util.logging.Logger; 22 | 23 | /** 24 | * Factory responsible for creating the wrapper tracer used to emit the flight recorder events. 25 | *

26 | * Note that this is only supported API. 27 | */ 28 | public final class JfrTracerFactory { 29 | 30 | private static final Logger LOG = Logger.getLogger(JfrTracerFactory.class.getName()); 31 | 32 | private JfrTracerFactory() { 33 | } 34 | 35 | /** 36 | * Wraps a tracer in a tracer which will provide contextual JFR events The tracer will be small 37 | * and the overhead small. 38 | * 39 | * @param delegate 40 | * the tracer responsible for the normal open tracing work. This can, for example, be 41 | * your usual Jaeger or Zipkin tracer. 42 | * @return the wrapped tracer to use. You would normally register this tracer as your global 43 | * tracer. 44 | */ 45 | public static Tracer create(Tracer delegate) { 46 | 47 | LOG.info("Using DelegatingJfrTracer to capture contextual information into JFR."); 48 | 49 | if (delegate instanceof TracerWrapper) { 50 | throw new IllegalArgumentException("You may not wrap a jfr tracer!"); 51 | } 52 | 53 | return new TracerWrapper(delegate); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/jfr/AbstractJfrEmitter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.jfr; 17 | 18 | import java.util.logging.Logger; 19 | 20 | import io.opentracing.Span; 21 | 22 | /** 23 | * Abstract super class for emitters. 24 | */ 25 | abstract class AbstractJfrEmitter implements JfrEmitter { 26 | static final Logger LOGGER = Logger.getLogger(JfrScopeEmitterImpl.class.getName()); 27 | protected Span span; 28 | 29 | AbstractJfrEmitter(Span span) { 30 | this.span = span; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/jfr/AbstractJfrSpanEmitter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.jfr; 17 | 18 | import java.util.concurrent.ArrayBlockingQueue; 19 | import java.util.concurrent.ThreadPoolExecutor; 20 | import java.util.concurrent.TimeUnit; 21 | 22 | import io.opentracing.Span; 23 | 24 | /** 25 | * Abstract super class for span emitters. 26 | */ 27 | abstract class AbstractJfrSpanEmitter extends AbstractJfrEmitter { 28 | 29 | protected final static ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(1, 1, Long.MAX_VALUE, 30 | TimeUnit.NANOSECONDS, new ArrayBlockingQueue(50), (r) -> { 31 | Thread thread = new Thread(r, "JfrTracer Span Events"); 32 | thread.setDaemon(true); 33 | return thread; 34 | }, (r, e) -> { 35 | // Seems very unlikely to happen, but just to be sure... 36 | LOGGER.warning("Span Event queue full - dropped span event"); 37 | }); 38 | 39 | AbstractJfrSpanEmitter(Span span) { 40 | super(span); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/jfr/JfrEmitter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.jfr; 17 | 18 | /** 19 | * Interface for something capable of emitting a JFR event. 20 | */ 21 | public interface JfrEmitter extends AutoCloseable { 22 | /** 23 | * Emits an event with the associated operation name. 24 | * 25 | * @param parentId 26 | * the id of the parent span. 27 | * @param operationName 28 | * the operation to emit. 29 | */ 30 | void start(String parentId, String operationName); 31 | 32 | /** 33 | * Finishes the event. 34 | */ 35 | @Override 36 | public void close(); 37 | } 38 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/jfr/JfrEmitterFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.jfr; 17 | 18 | import io.opentracing.Span; 19 | 20 | /** 21 | * For creating JfrEmitters. 22 | */ 23 | public class JfrEmitterFactory { 24 | /** 25 | * Thread locally emitted events for scopes. Note that the calls to 26 | * {@link JfrEmitter#start(String)} and {@link JfrEmitter#close()} must be started and closed in 27 | * the same thread. 28 | * 29 | * @param span 30 | * the span containing the information to be recorded. 31 | * @return an emitter that can be used to emit the information to JFR 32 | */ 33 | public JfrEmitter createScopeEmitter(Span span) { 34 | return new JfrScopeEmitterImpl(span); 35 | } 36 | 37 | /** 38 | * Events emitted for spans. Note that these are posted to a separate thread, and can be 39 | * started/ended in different threads. 40 | * 41 | * @param span 42 | * the span containing the information to be recorded. 43 | * @return an emitter that can be used to emit the information 44 | */ 45 | public JfrEmitter createSpanEmitter(Span span) { 46 | return new JfrSpanEmitterImpl(span); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/jfr/JfrScopeEmitterImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.jfr; 17 | 18 | import java.net.URI; 19 | import java.util.logging.Level; 20 | 21 | import com.oracle.jrockit.jfr.EventDefinition; 22 | import com.oracle.jrockit.jfr.EventToken; 23 | import com.oracle.jrockit.jfr.InstantEvent; 24 | import com.oracle.jrockit.jfr.InvalidEventDefinitionException; 25 | import com.oracle.jrockit.jfr.InvalidValueException; 26 | import com.oracle.jrockit.jfr.Producer; 27 | import com.oracle.jrockit.jfr.TimedEvent; 28 | import com.oracle.jrockit.jfr.ValueDefinition; 29 | 30 | import io.opentracing.Span; 31 | 32 | /** 33 | * This is the JDK 8 implementation. For the JDK 11 and later implementation, see src/main/java11. 34 | */ 35 | @SuppressWarnings({"deprecation"}) 36 | final class JfrScopeEmitterImpl extends AbstractJfrEmitter { 37 | 38 | private static final Producer PRODUCER; 39 | private static final EventToken SCOPE_EVENT_TOKEN; 40 | 41 | static { 42 | URI producerURI = URI.create("http://opentracing.io/jfr-tracer"); 43 | PRODUCER = new Producer("jfr-tracer", "Events produced by the OpenTracing jfr-tracer.", producerURI); 44 | PRODUCER.register(); 45 | SCOPE_EVENT_TOKEN = register(ScopeEvent.class); 46 | } 47 | 48 | private ScopeEvent currentEvent; 49 | 50 | JfrScopeEmitterImpl(Span span) { 51 | super(span); 52 | } 53 | 54 | @Override 55 | public void close() { 56 | if (currentEvent != null) { 57 | if (currentEvent.shouldWrite()) { 58 | currentEvent.end(); 59 | currentEvent.commit(); 60 | } 61 | currentEvent = null; 62 | } 63 | } 64 | 65 | @Override 66 | public void start(String parentId, String operationName) { 67 | currentEvent = new ScopeEvent(SCOPE_EVENT_TOKEN); 68 | currentEvent.operationName = operationName; 69 | currentEvent.parentId = parentId; 70 | currentEvent.traceId = span.context().toTraceId(); 71 | currentEvent.spanId = span.context().toSpanId(); 72 | currentEvent.begin(); 73 | } 74 | 75 | @Override 76 | public String toString() { 77 | return "JDK 8 JFR Scope Emitter"; 78 | } 79 | 80 | /** 81 | * Helper method to register an event class with the jfr-tracer producer. 82 | * 83 | * @param clazz 84 | * the event class to register. 85 | * @return the token associated with the event class. 86 | */ 87 | static EventToken register(Class clazz) { 88 | try { 89 | EventToken token = PRODUCER.addEvent(clazz); 90 | LOGGER.fine("Registered EventType " + clazz.getName()); 91 | return token; 92 | } catch (InvalidEventDefinitionException | InvalidValueException e) { 93 | LOGGER.log(Level.SEVERE, "Failed to register the event class " + clazz.getName() 94 | + ". Event will not be available. Please check your configuration.", e); 95 | } 96 | return null; 97 | } 98 | 99 | @EventDefinition(path = "opentracing/scopeevent", name = "Scope", description = "A thread local event triggered by scope activation", stacktrace = true, thread = true) 100 | public static class ScopeEvent extends TimedEvent { 101 | 102 | @ValueDefinition(name = "Operation Name") 103 | private String operationName; 104 | 105 | @ValueDefinition(name = "Trace Id") 106 | private String traceId; 107 | 108 | @ValueDefinition(name = "Span Id") 109 | private String spanId; 110 | 111 | @ValueDefinition(name = "Parent Id") 112 | private String parentId; 113 | 114 | ScopeEvent(EventToken eventToken) { 115 | super(eventToken); 116 | } 117 | 118 | @SuppressWarnings("unused") 119 | public String getOperationName() { 120 | return operationName; 121 | } 122 | 123 | @SuppressWarnings("unused") 124 | public String getTraceId() { 125 | return traceId; 126 | } 127 | 128 | @SuppressWarnings("unused") 129 | public String getSpanId() { 130 | return spanId; 131 | } 132 | 133 | @SuppressWarnings("unused") 134 | public String getParentId() { 135 | return parentId; 136 | } 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/jfr/JfrSpanEmitterImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.jfr; 17 | 18 | import com.oracle.jrockit.jfr.EventDefinition; 19 | import com.oracle.jrockit.jfr.EventToken; 20 | import com.oracle.jrockit.jfr.TimedEvent; 21 | import com.oracle.jrockit.jfr.ValueDefinition; 22 | 23 | import io.opentracing.Span; 24 | 25 | /** 26 | * This is the JDK 8 implementation for emitting Span events. For the JDK 11 and later 27 | * implementation, see src/main/java11. 28 | */ 29 | @SuppressWarnings("deprecation") 30 | final class JfrSpanEmitterImpl extends AbstractJfrSpanEmitter { 31 | 32 | private static final EventToken SPAN_EVENT_TOKEN; 33 | 34 | static { 35 | SPAN_EVENT_TOKEN = JfrScopeEmitterImpl.register(SpanEvent.class); 36 | } 37 | 38 | private SpanEvent currentEvent; 39 | 40 | JfrSpanEmitterImpl(Span span) { 41 | super(span); 42 | } 43 | 44 | @Override 45 | public void start(String parentId, String operationName) { 46 | currentEvent = new SpanEvent(SPAN_EVENT_TOKEN); 47 | if (currentEvent.getEventInfo().isEnabled()) { 48 | currentEvent.operationName = operationName; 49 | currentEvent.traceId = span.context().toTraceId(); 50 | currentEvent.spanId = span.context().toSpanId(); 51 | currentEvent.parentId = parentId; 52 | currentEvent.startThread = Thread.currentThread(); 53 | } 54 | EXECUTOR.execute(new BeginEventCommand(currentEvent)); 55 | } 56 | 57 | @Override 58 | public void close() { 59 | if (currentEvent != null) { 60 | currentEvent.endThread = Thread.currentThread(); 61 | EXECUTOR.execute(new EndEventCommand(currentEvent)); 62 | currentEvent = null; 63 | } 64 | } 65 | 66 | @Override 67 | public String toString() { 68 | return "JDK 8 JFR Span Emitter"; 69 | } 70 | 71 | // Must be public for JFR to access it 72 | @EventDefinition(path = "opentracing/spanevent", name = "Span", description = "And event representing an OpenTracing span", stacktrace = false, thread = true) 73 | public static class SpanEvent extends TimedEvent { 74 | 75 | @ValueDefinition(name = "Operation Name") 76 | private String operationName; 77 | 78 | @ValueDefinition(name = "Trace Id") 79 | private String traceId; 80 | 81 | @ValueDefinition(name = "Span Id") 82 | private String spanId; 83 | 84 | @ValueDefinition(name = "Parent Id") 85 | private String parentId; 86 | 87 | @ValueDefinition(name = "Start Thread", description = "The thread initiating the span") 88 | private Thread startThread; 89 | 90 | @ValueDefinition(name = "End Thread", description = "The thread ending the span") 91 | private Thread endThread; 92 | 93 | SpanEvent(EventToken eventToken) { 94 | super(eventToken); 95 | } 96 | 97 | @SuppressWarnings("unused") 98 | public String getTraceId() { 99 | return traceId; 100 | } 101 | 102 | @SuppressWarnings("unused") 103 | public String getSpanId() { 104 | return spanId; 105 | } 106 | 107 | @SuppressWarnings("unused") 108 | public String getParentId() { 109 | return parentId; 110 | } 111 | 112 | @SuppressWarnings("unused") 113 | public Thread getStartThread() { 114 | return startThread; 115 | } 116 | 117 | @SuppressWarnings("unused") 118 | public Thread getEndThread() { 119 | return endThread; 120 | } 121 | 122 | @SuppressWarnings("unused") 123 | public String getOperationName() { 124 | return operationName; 125 | } 126 | } 127 | 128 | private static class EndEventCommand implements Runnable { 129 | 130 | private final SpanEvent event; 131 | 132 | EndEventCommand(SpanEvent event) { 133 | this.event = event; 134 | } 135 | 136 | @Override 137 | public void run() { 138 | if (event.shouldWrite()) { 139 | event.end(); 140 | event.commit(); 141 | } 142 | } 143 | } 144 | 145 | private static class BeginEventCommand implements Runnable { 146 | 147 | private final SpanEvent event; 148 | 149 | BeginEventCommand(SpanEvent event) { 150 | this.event = event; 151 | } 152 | 153 | @Override 154 | public void run() { 155 | event.begin(); 156 | } 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/wrapper/ScopeManagerWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.wrapper; 17 | 18 | import io.opentracing.Scope; 19 | import io.opentracing.ScopeManager; 20 | import io.opentracing.Span; 21 | 22 | /** 23 | * Wrapper for {@link ScopeManager}. 24 | */ 25 | final class ScopeManagerWrapper implements ScopeManager { 26 | private final ScopeManager delegate; 27 | private final ThreadLocal activeScope = new ThreadLocal<>(); 28 | 29 | ScopeManagerWrapper(ScopeManager delegate) { 30 | this.delegate = delegate; 31 | } 32 | 33 | @Override 34 | @Deprecated 35 | public Scope activate(Span span, boolean finishSpanOnClose) { 36 | ScopeWrapper wrapper; 37 | if (!(span instanceof SpanWrapper)) { 38 | // This should be rather unlikely... 39 | SpanWrapper spanWrapper = new SpanWrapper("", span, ""); 40 | wrapper = new ScopeWrapper(this, spanWrapper, delegate.activate(span, finishSpanOnClose), 41 | finishSpanOnClose); 42 | } else { 43 | SpanWrapper spanWrapper = (SpanWrapper) span; 44 | wrapper = new ScopeWrapper(this, spanWrapper, 45 | delegate.activate(spanWrapper.getDelegate(), finishSpanOnClose), finishSpanOnClose); 46 | } 47 | activeScope.set(wrapper); 48 | return wrapper; 49 | } 50 | 51 | @Override 52 | @Deprecated 53 | public Scope active() { 54 | return activeScope.get(); 55 | } 56 | 57 | void setActive(ScopeWrapper scope) { 58 | activeScope.set(scope); 59 | } 60 | 61 | @Override 62 | public Scope activate(Span arg) { 63 | return activate(arg, false); 64 | } 65 | 66 | @Override 67 | @SuppressWarnings("deprecation") 68 | public Span activeSpan() { 69 | Scope scope = active(); 70 | return scope == null ? null : scope.span(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/wrapper/ScopeWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.wrapper; 17 | 18 | import io.opentracing.Scope; 19 | import io.opentracing.Span; 20 | import io.opentracing.contrib.jfrtracer.impl.jfr.JfrEmitter; 21 | 22 | import java.util.logging.Logger; 23 | import java.util.logging.Level; 24 | 25 | /** 26 | * Wrapper for {@link Scope}. 27 | */ 28 | final class ScopeWrapper implements Scope { 29 | 30 | private static final Logger LOG = Logger.getLogger(ScopeWrapper.class.getName()); 31 | 32 | private final ScopeManagerWrapper scopeManagerWrapper; 33 | private final Scope delegate; 34 | private final JfrEmitter emitter; 35 | private final SpanWrapper spanWrapper; 36 | private final boolean finishSpanOnClose; 37 | private final ScopeWrapper parentScope; 38 | 39 | ScopeWrapper(ScopeManagerWrapper scopeManagerWrapper, SpanWrapper spanWrapper, Scope delegate, 40 | boolean finishSpanOnClose) { 41 | this.scopeManagerWrapper = scopeManagerWrapper; 42 | this.parentScope = (ScopeWrapper) scopeManagerWrapper.active(); 43 | this.spanWrapper = spanWrapper; 44 | this.delegate = delegate; 45 | emitter = SpanWrapper.EMITTER_FACTORY.createScopeEmitter(spanWrapper); 46 | emitter.start(spanWrapper.getParentId(), spanWrapper.getOperationName()); 47 | this.finishSpanOnClose = finishSpanOnClose; 48 | } 49 | 50 | @Override 51 | public void close() { 52 | delegate.close(); 53 | closeEmitter(); 54 | if (finishSpanOnClose) { 55 | spanWrapper.closeEmitter(); 56 | } 57 | scopeManagerWrapper.setActive(parentScope); 58 | } 59 | 60 | @Override 61 | @Deprecated 62 | public Span span() { 63 | return spanWrapper; 64 | } 65 | 66 | private void closeEmitter() { 67 | try { 68 | emitter.close(); 69 | } catch (Exception ex) { 70 | LOG.log(Level.SEVERE, "Error closing JFR Span", ex); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/wrapper/SpanBuilderWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.wrapper; 17 | 18 | import io.opentracing.Scope; 19 | import io.opentracing.Span; 20 | import io.opentracing.SpanContext; 21 | import io.opentracing.Tracer.SpanBuilder; 22 | import io.opentracing.tag.Tag; 23 | 24 | /** 25 | * Wrapper for {@link SpanBuilder}. 26 | */ 27 | final class SpanBuilderWrapper implements SpanBuilder { 28 | 29 | private final TracerWrapper owner; 30 | private final SpanBuilder delegate; 31 | private final String operationName; 32 | // Not sure how likely it is that these builders get passed around, 33 | // but assumption is the mother of all... 34 | private volatile String parentId; 35 | 36 | SpanBuilderWrapper(TracerWrapper owner, String operationName, SpanBuilder delegate) { 37 | this.owner = owner; 38 | this.delegate = delegate; 39 | this.operationName = operationName; 40 | } 41 | 42 | @Override 43 | public SpanBuilder asChildOf(SpanContext parent) { 44 | delegate.asChildOf(parent); 45 | if (parent == null) { 46 | return this; 47 | } 48 | parentId = parent.toSpanId(); 49 | return this; 50 | } 51 | 52 | @Override 53 | public SpanBuilder asChildOf(Span parent) { 54 | delegate.asChildOf(parent); 55 | if (parent == null) { 56 | return this; 57 | } 58 | parentId = parent.context().toSpanId(); 59 | return this; 60 | } 61 | 62 | @Override 63 | public SpanBuilder addReference(String referenceType, SpanContext referencedContext) { 64 | delegate.addReference(referenceType, referencedContext); 65 | if (referencedContext == null) { 66 | return this; 67 | } 68 | parentId = referencedContext.toSpanId(); 69 | return this; 70 | } 71 | 72 | @Override 73 | public SpanBuilder ignoreActiveSpan() { 74 | delegate.ignoreActiveSpan(); 75 | return this; 76 | } 77 | 78 | @Override 79 | public SpanBuilder withTag(String key, String value) { 80 | delegate.withTag(key, value); 81 | return this; 82 | } 83 | 84 | @Override 85 | public SpanBuilder withTag(String key, boolean value) { 86 | delegate.withTag(key, value); 87 | return this; 88 | } 89 | 90 | @Override 91 | public SpanBuilder withTag(String key, Number value) { 92 | delegate.withTag(key, value); 93 | return this; 94 | } 95 | 96 | @Override 97 | public SpanBuilder withTag(Tag key, T value) { 98 | delegate.withTag(key, value); 99 | return this; 100 | } 101 | 102 | @Override 103 | public SpanBuilder withStartTimestamp(long microseconds) { 104 | delegate.withStartTimestamp(microseconds); 105 | return this; 106 | } 107 | 108 | @Override 109 | @Deprecated 110 | public Scope startActive(boolean finishSpanOnClose) { 111 | return owner.scopeManager().activate(start(), finishSpanOnClose); 112 | } 113 | 114 | @Override 115 | @Deprecated 116 | public Span startManual() { 117 | return new SpanWrapper(getParentSpanId(), delegate.startManual(), operationName); 118 | } 119 | 120 | @Override 121 | public Span start() { 122 | SpanWrapper spanWrapper = new SpanWrapper(getParentSpanId(), delegate.start(), operationName); 123 | spanWrapper.start(); 124 | return spanWrapper; 125 | } 126 | 127 | private String getParentSpanId() { 128 | Span activeSpan = owner.scopeManager().activeSpan(); 129 | return parentId != null ? parentId : activeSpan != null ? activeSpan.context().toSpanId() : null; 130 | } 131 | 132 | /** 133 | * hook for unit test 134 | */ 135 | String parentId() { 136 | return parentId; 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/wrapper/SpanWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.wrapper; 17 | 18 | import java.util.Map; 19 | 20 | import io.opentracing.Span; 21 | import io.opentracing.SpanContext; 22 | import io.opentracing.contrib.jfrtracer.impl.jfr.JfrEmitter; 23 | import io.opentracing.contrib.jfrtracer.impl.jfr.JfrEmitterFactory; 24 | import io.opentracing.tag.Tag; 25 | 26 | /** 27 | * Wrapper for {@link Span}. 28 | */ 29 | final class SpanWrapper implements Span { 30 | static JfrEmitterFactory EMITTER_FACTORY = new JfrEmitterFactory(); 31 | 32 | private final String parentId; 33 | private final Span delegate; 34 | private final JfrEmitter spanEmitter; 35 | // If we don't want to support updates of the operation name, this could be 36 | // final too... 37 | // If we want to ignore the fact that this could be updated in a separate 38 | // thread, we could make it non-volatile... 39 | private volatile String operationName; 40 | 41 | SpanWrapper(String parentId, Span delegate, String operationName) { 42 | this.delegate = delegate; 43 | this.parentId = parentId; 44 | this.operationName = operationName; 45 | spanEmitter = EMITTER_FACTORY.createSpanEmitter(delegate); 46 | } 47 | 48 | @Override 49 | public SpanContext context() { 50 | return delegate.context(); 51 | } 52 | 53 | @Override 54 | public Span setTag(String key, String value) { 55 | delegate.setTag(key, value); 56 | return this; 57 | } 58 | 59 | @Override 60 | public Span setTag(String key, boolean value) { 61 | delegate.setTag(key, value); 62 | return this; 63 | } 64 | 65 | @Override 66 | public Span setTag(String key, Number value) { 67 | delegate.setTag(key, value); 68 | return this; 69 | } 70 | 71 | @Override 72 | public Span log(Map fields) { 73 | delegate.log(fields); 74 | return this; 75 | } 76 | 77 | @Override 78 | public Span log(long timestampMicroseconds, Map fields) { 79 | delegate.log(timestampMicroseconds, fields); 80 | return this; 81 | } 82 | 83 | @Override 84 | public Span log(String event) { 85 | delegate.log(event); 86 | return this; 87 | } 88 | 89 | @Override 90 | public Span log(long timestampMicroseconds, String event) { 91 | delegate.log(timestampMicroseconds, event); 92 | return this; 93 | } 94 | 95 | @Override 96 | public Span setBaggageItem(String key, String value) { 97 | delegate.setBaggageItem(key, value); 98 | return this; 99 | } 100 | 101 | @Override 102 | public String getBaggageItem(String key) { 103 | return delegate.getBaggageItem(key); 104 | } 105 | 106 | @Override 107 | public Span setOperationName(String operationName) { 108 | this.operationName = operationName; 109 | delegate.setOperationName(operationName); 110 | return this; 111 | } 112 | 113 | @Override 114 | public void finish() { 115 | delegate.finish(); 116 | closeEmitter(); 117 | } 118 | 119 | @Override 120 | public void finish(long finishMicros) { 121 | delegate.finish(finishMicros); 122 | closeEmitter(); 123 | } 124 | 125 | @Override 126 | public Span setTag(Tag key, T value) { 127 | delegate.setTag(key, value); 128 | return this; 129 | } 130 | 131 | Span getDelegate() { 132 | return delegate; 133 | } 134 | 135 | void start() { 136 | spanEmitter.start(parentId, operationName); 137 | } 138 | 139 | String getOperationName() { 140 | return operationName; 141 | } 142 | 143 | String getParentId() { 144 | return parentId; 145 | } 146 | 147 | void closeEmitter() { 148 | try { 149 | spanEmitter.close(); 150 | } catch (Exception e) { 151 | // Ignore any JFR related problems at this point 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java/io/opentracing/contrib/jfrtracer/impl/wrapper/TracerWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.wrapper; 17 | 18 | import io.opentracing.Scope; 19 | import io.opentracing.ScopeManager; 20 | import io.opentracing.Span; 21 | import io.opentracing.SpanContext; 22 | import io.opentracing.Tracer; 23 | import io.opentracing.propagation.Format; 24 | 25 | import static java.util.Objects.isNull; 26 | import static java.util.Objects.requireNonNull; 27 | 28 | /** 29 | * A tracer that records context information into the JDK Flight Recorder, making it possible to 30 | * correlate interesting findings in distributed traces with detailed information in the flight 31 | * recordings. 32 | *

33 | * For scopes and spans the following will be recorded: 34 | *

39 | */ 40 | public final class TracerWrapper implements Tracer { 41 | 42 | private final Tracer delegate; 43 | private final ScopeManagerWrapper scopeManager; 44 | 45 | public TracerWrapper(Tracer delegate) { 46 | this.delegate = requireNonNull(delegate); 47 | this.scopeManager = new ScopeManagerWrapper(delegate.scopeManager()); 48 | } 49 | 50 | @Override 51 | public ScopeManager scopeManager() { 52 | return scopeManager; 53 | } 54 | 55 | @Override 56 | @Deprecated 57 | public Span activeSpan() { 58 | Scope active = scopeManager.active(); 59 | return isNull(active) ? null : active.span(); 60 | } 61 | 62 | @Override 63 | public SpanBuilder buildSpan(String operationName) { 64 | return new SpanBuilderWrapper(this, operationName, delegate.buildSpan(operationName)); 65 | } 66 | 67 | @Override 68 | public void inject(SpanContext spanContext, Format format, C carrier) { 69 | delegate.inject(spanContext, format, carrier); 70 | } 71 | 72 | @Override 73 | public SpanContext extract(Format format, C carrier) { 74 | return delegate.extract(format, carrier); 75 | } 76 | 77 | @Override 78 | @SuppressWarnings("deprecation") 79 | public Scope activateSpan(Span span) { 80 | return scopeManager.activate(span, true); 81 | } 82 | 83 | @Override 84 | public void close() { 85 | delegate.close(); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java11/io/opentracing/contrib/jfrtracer/impl/jfr/JfrScopeEmitterImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.jfr; 17 | 18 | import jdk.jfr.Event; 19 | import jdk.jfr.Name; 20 | import jdk.jfr.Label; 21 | import jdk.jfr.Category; 22 | import jdk.jfr.Description; 23 | 24 | import io.opentracing.Span; 25 | 26 | /** 27 | * This is the JDK 9 or later implementation of the JfrEmitter. 28 | */ 29 | public class JfrScopeEmitterImpl extends AbstractJfrEmitter { 30 | 31 | private ScopeEvent currentEvent; 32 | 33 | @Name("io.opentracing.Scope") 34 | @Category("Open Tracing") 35 | @Label("Scope") 36 | @Description("Open tracing event corresponding to an activation scope") 37 | private static class ScopeEvent extends Event { 38 | 39 | @Label("Operation Name") 40 | private String operationName; 41 | 42 | @Label("Trace Id") 43 | private String traceId; 44 | 45 | @Label("Span Id") 46 | private String spanId; 47 | 48 | @Label("Parent Id") 49 | private String parentId; 50 | } 51 | 52 | JfrScopeEmitterImpl(Span span) { 53 | super(span); 54 | } 55 | 56 | @Override 57 | public void close() { 58 | if (currentEvent != null) { 59 | currentEvent.commit(); 60 | currentEvent = null; 61 | } 62 | } 63 | 64 | @Override 65 | public void start(String parentId, String operationName) { 66 | currentEvent = new ScopeEvent(); 67 | if (currentEvent.isEnabled()) { 68 | currentEvent.operationName = operationName; 69 | currentEvent.parentId = parentId; 70 | currentEvent.traceId = span.context().toTraceId(); 71 | currentEvent.spanId = span.context().toSpanId(); 72 | } 73 | currentEvent.begin(); 74 | } 75 | 76 | @Override 77 | public String toString() { 78 | return "JDK 11 JFR Emitter"; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/main/java11/io/opentracing/contrib/jfrtracer/impl/jfr/JfrSpanEmitterImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer.impl.jfr; 17 | 18 | import jdk.jfr.Event; 19 | import jdk.jfr.Name; 20 | import jdk.jfr.Label; 21 | import jdk.jfr.Category; 22 | import jdk.jfr.Description; 23 | import jdk.jfr.StackTrace; 24 | 25 | import io.opentracing.Span; 26 | 27 | /** 28 | * This is the JDK 9 or later implementation of the JfrEmitter. 29 | */ 30 | public class JfrSpanEmitterImpl extends AbstractJfrSpanEmitter { 31 | 32 | private volatile SpanEvent currentEvent; 33 | 34 | @Name("io.opentracing.Span") 35 | @Label("Span") 36 | @Description("Open tracing event corresponding to a span.") 37 | @Category("Open Tracing") 38 | @StackTrace(false) 39 | private static class SpanEvent extends Event { 40 | 41 | @Label("Operation Name") 42 | private String operationName; 43 | 44 | @Label("Trace Id") 45 | private String traceId; 46 | 47 | @Label("Span Id") 48 | private String spanId; 49 | 50 | @Label("Parent Id") 51 | private String parentId; 52 | 53 | @Label("Start Thread") 54 | @Description("The thread initiating the span") 55 | private Thread startThread; 56 | 57 | @Label("End Thread") 58 | @Description("The thread ending the span") 59 | private Thread endThread; 60 | } 61 | 62 | private static class EndEventCommand implements Runnable { 63 | 64 | private final SpanEvent event; 65 | 66 | EndEventCommand(SpanEvent event) { 67 | this.event = event; 68 | } 69 | 70 | @Override 71 | public void run() { 72 | if (event.shouldCommit()) { 73 | event.end(); 74 | event.commit(); 75 | } 76 | } 77 | } 78 | 79 | private static class BeginEventCommand implements Runnable { 80 | 81 | private final SpanEvent event; 82 | 83 | BeginEventCommand(SpanEvent event) { 84 | this.event = event; 85 | } 86 | 87 | @Override 88 | public void run() { 89 | event.begin(); 90 | } 91 | } 92 | 93 | JfrSpanEmitterImpl(Span span) { 94 | super(span); 95 | } 96 | 97 | @Override 98 | public void close() { 99 | if (currentEvent != null) { 100 | currentEvent.endThread = Thread.currentThread(); 101 | EXECUTOR.execute(new EndEventCommand(currentEvent)); 102 | currentEvent = null; 103 | } 104 | } 105 | 106 | @Override 107 | public void start(String parentId, String operationName) { 108 | currentEvent = new SpanEvent(); 109 | if (currentEvent.isEnabled()) { 110 | currentEvent.operationName = operationName; 111 | currentEvent.parentId = parentId; 112 | currentEvent.traceId = span.context().toTraceId(); 113 | currentEvent.spanId = span.context().toSpanId(); 114 | currentEvent.startThread = Thread.currentThread(); 115 | } 116 | EXECUTOR.execute(new BeginEventCommand(currentEvent)); 117 | } 118 | 119 | @Override 120 | public String toString() { 121 | return "JDK 11 JFR Emitter"; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/test/java/io/opentracing/contrib/jfrtracer/DifferentSpanTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer; 17 | 18 | import io.opentracing.Span; 19 | import io.opentracing.Tracer; 20 | import io.opentracing.contrib.concurrent.TracedExecutorService; 21 | import io.opentracing.mock.MockSpan; 22 | import io.opentracing.mock.MockTracer; 23 | import oracle.jrockit.jfr.parser.FLREvent; 24 | import org.junit.jupiter.api.Test; 25 | 26 | import java.io.IOException; 27 | import java.nio.file.Files; 28 | import java.nio.file.Path; 29 | import java.util.List; 30 | import java.util.Map; 31 | import java.util.concurrent.ExecutionException; 32 | import java.util.concurrent.Executors; 33 | import java.util.concurrent.TimeUnit; 34 | import java.util.concurrent.TimeoutException; 35 | import java.util.stream.Collectors; 36 | 37 | import static org.junit.jupiter.api.Assertions.assertEquals; 38 | import static org.junit.jupiter.api.Assertions.assertNotEquals; 39 | import static org.junit.jupiter.api.Assertions.assertNotNull; 40 | 41 | @SuppressWarnings("deprecation") 42 | public class DifferentSpanTest { 43 | 44 | @Test 45 | public void spansInMultipleThreads() 46 | throws IOException, InterruptedException, ExecutionException, TimeoutException { 47 | Path output = Files.createTempFile("test-recording-multple-threads", ".jfr"); 48 | 49 | try { 50 | // Setup tracers 51 | MockTracer mockTracer = new MockTracer(); 52 | Tracer tracer = JfrTracerFactory.create(mockTracer); 53 | 54 | // Start JFR 55 | JfrTestUtils.startJFR(); 56 | 57 | // Generate spans 58 | Span span = tracer.buildSpan("test span").start(); 59 | TracedExecutorService executor = new TracedExecutorService(Executors.newSingleThreadExecutor(), tracer); 60 | executor.submit(() -> { 61 | tracer.buildSpan("executor span").start().finish(); 62 | }).get(5, TimeUnit.SECONDS); 63 | span.finish(); 64 | 65 | // Stop recording 66 | //Ugly Sleep for now 67 | Thread.sleep(100); 68 | List events = JfrTestUtils.stopJfr(output); 69 | 70 | // Validate span was created and recorded in JFR 71 | assertEquals(2, mockTracer.finishedSpans().size()); 72 | 73 | Map finishedSpans = mockTracer.finishedSpans().stream() 74 | .collect(Collectors.toMap(e -> e.operationName(), e -> e)); 75 | assertEquals(finishedSpans.size(), events.size()); 76 | events.stream().forEach(e -> { 77 | MockSpan finishedSpan = finishedSpans.get(e.getValue("operationName").toString()); 78 | assertNotNull(finishedSpan); 79 | assertEquals(Long.toString(finishedSpan.context().traceId()), e.getValue("traceId")); 80 | assertEquals(Long.toString(finishedSpan.context().spanId()), e.getValue("spanId")); 81 | assertEquals(finishedSpan.operationName(), e.getValue("operationName")); 82 | }); 83 | 84 | } finally { 85 | JfrTestUtils.delete(output); 86 | } 87 | } 88 | 89 | @Test 90 | public void passingSpanBetweenThreads() 91 | throws IOException, InterruptedException, TimeoutException, ExecutionException { 92 | Path output = Files.createTempFile("test-recording-between-threads", ".jfr"); 93 | 94 | try { 95 | // Setup tracers 96 | MockTracer mockTracer = new MockTracer(); 97 | Tracer tracer = JfrTracerFactory.create(mockTracer); 98 | 99 | // Start JFR 100 | JfrTestUtils.startJFR(); 101 | 102 | // Generate spans 103 | TracedExecutorService executor = new TracedExecutorService(Executors.newSingleThreadExecutor(), tracer); 104 | long expectedStartThread = Thread.currentThread().getId(); 105 | Span span = tracer.buildSpan("test span").start(); 106 | long expectedFinishThread = executor.submit(() -> { 107 | span.finish(); 108 | return Thread.currentThread().getId(); 109 | }).get(5, TimeUnit.SECONDS); 110 | 111 | // Stop recording 112 | Thread.sleep(100); 113 | List events = JfrTestUtils.stopJfr(output); 114 | 115 | // Validate span was created and recorded in JFR 116 | assertEquals(1, mockTracer.finishedSpans().size()); 117 | 118 | Map finishedSpans = mockTracer.finishedSpans().stream() 119 | .collect(Collectors.toMap(e -> e.operationName(), e -> e)); 120 | assertEquals(finishedSpans.size(), events.size()); 121 | events.stream().forEach(e -> { 122 | MockSpan finishedSpan = finishedSpans.get(e.getValue("operationName").toString()); 123 | assertNotNull(finishedSpan); 124 | assertEquals(Long.toString(finishedSpan.context().traceId()), e.getValue("traceId")); 125 | assertEquals(Long.toString(finishedSpan.context().spanId()), e.getValue("spanId")); 126 | assertEquals(finishedSpan.operationName(), e.getValue("operationName")); 127 | assertNotEquals(expectedStartThread, e.getThread()); 128 | assertNotEquals(expectedFinishThread, e.getThread()); 129 | assertEquals(expectedStartThread, e.getValue("startThread")); 130 | assertEquals(expectedFinishThread, e.getValue("endThread")); 131 | }); 132 | 133 | } finally { 134 | JfrTestUtils.delete(output); 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/test/java/io/opentracing/contrib/jfrtracer/ImplementationsJFRTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer; 17 | 18 | import brave.Tracing; 19 | import brave.opentracing.BraveTracer; 20 | import brave.propagation.B3Propagation; 21 | import brave.propagation.ExtraFieldPropagation; 22 | import brave.propagation.Propagation.Factory; 23 | import io.jaegertracing.Configuration.CodecConfiguration; 24 | import io.jaegertracing.Configuration.ReporterConfiguration; 25 | import io.jaegertracing.Configuration.SamplerConfiguration; 26 | import io.opentracing.Span; 27 | import io.opentracing.Tracer; 28 | import oracle.jrockit.jfr.parser.FLREvent; 29 | import org.junit.jupiter.api.Disabled; 30 | import org.junit.jupiter.api.Test; 31 | 32 | import java.io.IOException; 33 | import java.nio.file.Files; 34 | import java.nio.file.Path; 35 | import java.util.Arrays; 36 | import java.util.List; 37 | 38 | import static io.jaegertracing.Configuration.JAEGER_AGENT_HOST; 39 | import static io.jaegertracing.Configuration.JAEGER_AGENT_PORT; 40 | import static io.jaegertracing.Configuration.JAEGER_PROPAGATION; 41 | import static io.jaegertracing.Configuration.JAEGER_SAMPLER_PARAM; 42 | import static io.jaegertracing.Configuration.JAEGER_SAMPLER_TYPE; 43 | import static org.junit.jupiter.api.Assertions.assertEquals; 44 | import static org.junit.jupiter.api.Assertions.assertNotNull; 45 | 46 | @SuppressWarnings("deprecation") 47 | public class ImplementationsJFRTest { 48 | 49 | @Test 50 | public void jaegerB3() throws IOException { 51 | System.setProperty(JAEGER_SAMPLER_TYPE, "const"); 52 | System.setProperty(JAEGER_SAMPLER_PARAM, "1"); 53 | System.setProperty(JAEGER_AGENT_HOST, "localhost"); 54 | System.setProperty(JAEGER_AGENT_PORT, "6831"); 55 | System.setProperty(JAEGER_PROPAGATION, "B3"); 56 | 57 | Tracer jaegerTracer = new io.jaegertracing.Configuration("test").withSampler(SamplerConfiguration.fromEnv()) 58 | .withCodec(CodecConfiguration.fromEnv()).withReporter(ReporterConfiguration.fromEnv()).getTracer(); 59 | innerTest(jaegerTracer); 60 | } 61 | 62 | @Test 63 | public void jaegerUber() throws IOException { 64 | System.setProperty(JAEGER_SAMPLER_TYPE, "const"); 65 | System.setProperty(JAEGER_SAMPLER_PARAM, "1"); 66 | System.setProperty(JAEGER_AGENT_HOST, "localhost"); 67 | System.setProperty(JAEGER_AGENT_PORT, "6831"); 68 | System.setProperty(JAEGER_PROPAGATION, "JAEGER"); 69 | 70 | Tracer jaegerTracer = new io.jaegertracing.Configuration("test").withSampler(SamplerConfiguration.fromEnv()) 71 | .withCodec(CodecConfiguration.fromEnv()).withReporter(ReporterConfiguration.fromEnv()).getTracer(); 72 | innerTest(jaegerTracer); 73 | } 74 | 75 | @Test 76 | public void brave() throws IOException { 77 | 78 | Factory propagationFactory = ExtraFieldPropagation.newFactoryBuilder(B3Propagation.FACTORY) 79 | .addPrefixedFields("baggage-", Arrays.asList("country-code", "user-id")).build(); 80 | 81 | Tracing braveTracing = Tracing.newBuilder().localServiceName("my-service") 82 | .propagationFactory(propagationFactory).build(); 83 | innerTest(BraveTracer.create(braveTracing)); 84 | } 85 | 86 | private void innerTest(Tracer testTracer) throws IOException { 87 | Path output = Files.createTempFile("test-recording", ".jfr"); 88 | try { 89 | 90 | Tracer tracer = JfrTracerFactory.create(testTracer); 91 | 92 | // Start JFR 93 | JfrTestUtils.startJFR(); 94 | 95 | // Generate span 96 | Span start = tracer.buildSpan("outer span").start(); 97 | tracer.scopeManager().activate(start, false); 98 | tracer.buildSpan("inner span").startActive(true).close(); 99 | tracer.scopeManager().active().close(); 100 | start.finish(); 101 | 102 | try { 103 | // Stop recording 104 | Thread.sleep(100); 105 | } catch (InterruptedException ex) { 106 | } 107 | List events = JfrTestUtils.stopJfr(output); 108 | 109 | // Validate span was created and recorded in JFR 110 | assertEquals(4, events.size()); 111 | events.stream().forEach(e -> { 112 | assertNotNull(e.getValue("operationName")); 113 | if (e.getValue("operationName").equals("inner span")) { 114 | assertNotNull(e.getValue("parentId")); 115 | } 116 | assertNotNull(e.getValue("traceId")); 117 | assertNotNull(e.getValue("spanId")); 118 | }); 119 | 120 | } finally { 121 | Files.delete(output); 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/test/java/io/opentracing/contrib/jfrtracer/JfrTestUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer; 17 | 18 | import oracle.jrockit.jfr.JFR; 19 | import oracle.jrockit.jfr.parser.ChunkParser; 20 | import oracle.jrockit.jfr.parser.FLREvent; 21 | import oracle.jrockit.jfr.parser.Parser; 22 | 23 | import java.io.IOException; 24 | import java.lang.management.ManagementFactory; 25 | import java.nio.file.Files; 26 | import java.nio.file.Path; 27 | import java.nio.file.StandardCopyOption; 28 | import java.time.Duration; 29 | import java.util.ArrayList; 30 | import java.util.List; 31 | 32 | import javax.management.InstanceNotFoundException; 33 | import javax.management.MBeanException; 34 | import javax.management.MBeanServer; 35 | import javax.management.MalformedObjectNameException; 36 | import javax.management.ObjectName; 37 | import javax.management.ReflectionException; 38 | 39 | import static java.util.Objects.nonNull; 40 | import static org.junit.jupiter.api.Assertions.assertTimeout; 41 | import static org.junit.jupiter.api.Assertions.fail; 42 | 43 | @SuppressWarnings("deprecation") 44 | public final class JfrTestUtils { 45 | 46 | private JfrTestUtils() { 47 | } 48 | 49 | private static Path getJfrConfig() throws IOException { 50 | Path jfrConfig = Files.createTempFile("opentracing", ".jfc"); 51 | Files.copy(JfrTestUtils.class.getResourceAsStream("opentracing.jfc"), jfrConfig, StandardCopyOption.REPLACE_EXISTING); 52 | return jfrConfig; 53 | } 54 | 55 | public static void startJFR() { 56 | 57 | Path jfrConfig = null; 58 | try { 59 | jfrConfig = getJfrConfig(); 60 | } catch (IOException ex) { 61 | fail(ex.getMessage()); 62 | } 63 | 64 | MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); 65 | try { 66 | mbs.invoke(new ObjectName("com.sun.management:type=DiagnosticCommand"), "vmUnlockCommercialFeatures", new Object[0], new String[0]); 67 | mbs.invoke(new ObjectName("com.sun.management:type=DiagnosticCommand"), "jfrStart", 68 | new Object[] {new String[] {"name=opentracing-jfr", "settings=" + jfrConfig.toAbsolutePath().toString()}}, 69 | new String[] {String[].class.getName()}); 70 | 71 | assertTimeout(Duration.ofSeconds(10), () -> { 72 | while (JFR.get().getMBean().getRecordings().isEmpty()) { 73 | System.out.println("Waiting for recording to start"); 74 | Thread.sleep(10); 75 | } 76 | }); 77 | } catch (InstanceNotFoundException | MBeanException | MalformedObjectNameException | ReflectionException ex) { 78 | fail(ex.getMessage()); 79 | } finally { 80 | if (nonNull(jfrConfig)) { 81 | try { 82 | Files.delete(jfrConfig); 83 | } catch (IOException ex) { 84 | } 85 | } 86 | } 87 | } 88 | 89 | public static List stopJfr(Path output) throws IOException { 90 | try { 91 | MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); 92 | mbs.invoke(new ObjectName("com.sun.management:type=DiagnosticCommand"), "jfrStop", 93 | new Object[] {new String[] {"name=opentracing-jfr", "filename=" + output.toAbsolutePath().toString()}}, 94 | new String[] {String[].class.getName()}); 95 | } catch (InstanceNotFoundException | MBeanException | MalformedObjectNameException | ReflectionException ex) { 96 | fail(ex.getMessage()); 97 | } 98 | 99 | try (Parser parser = new Parser(output.toFile())) { 100 | List readAllEvents = new ArrayList<>(); 101 | for (ChunkParser chunkParser : parser) { 102 | for (FLREvent event : chunkParser) { 103 | if (event.getPath().startsWith("opentracing")) { 104 | readAllEvents.add(event); 105 | } 106 | } 107 | } 108 | return readAllEvents; 109 | } 110 | } 111 | 112 | public static void delete(Path output) { 113 | try { 114 | Files.delete(output); 115 | } catch (Throwable t) { 116 | // Should not affect test... 117 | System.err.println("Failed to delete test JFR-file: " + t.getMessage()); 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/test/java/io/opentracing/contrib/jfrtracer/JfrTracerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer; 17 | 18 | import io.opentracing.Tracer; 19 | import io.opentracing.mock.MockSpan; 20 | import io.opentracing.mock.MockTracer; 21 | import oracle.jrockit.jfr.parser.FLREvent; 22 | import org.junit.jupiter.api.Test; 23 | 24 | import java.io.IOException; 25 | import java.nio.file.Files; 26 | import java.nio.file.Path; 27 | import java.util.List; 28 | import java.util.Map; 29 | import java.util.stream.Collectors; 30 | 31 | import static org.junit.jupiter.api.Assertions.assertEquals; 32 | import static org.junit.jupiter.api.Assertions.assertNotNull; 33 | 34 | @SuppressWarnings("deprecation") 35 | public class JfrTracerTest { 36 | 37 | /** 38 | * Test JFR gets the generated span 39 | * 40 | * @throws java.io.IOException 41 | * on error 42 | */ 43 | @Test 44 | public void basicEvent() throws IOException, InterruptedException { 45 | Path output = Files.createTempFile("opentracing", ".jfr"); 46 | 47 | try { 48 | // Setup tracers 49 | MockTracer mockTracer = new MockTracer(); 50 | Tracer tracer = JfrTracerFactory.create(mockTracer); 51 | 52 | // Start JFR 53 | JfrTestUtils.startJFR(); 54 | // Generate span 55 | tracer.buildSpan("test span").start().finish(); 56 | 57 | // To be removed when test are fixed, it's used due to concurrency issue 58 | Thread.sleep(100); 59 | 60 | // Stop recording 61 | List events = JfrTestUtils.stopJfr(output); 62 | 63 | // To be removed when test are fixed, it's used due to concurrency issue 64 | Thread.sleep(100); 65 | 66 | // Validate span was created and recorded in JFR 67 | assertEquals(1, mockTracer.finishedSpans().size()); 68 | 69 | Map finishedSpans = mockTracer.finishedSpans().stream() 70 | .collect(Collectors.toMap(e -> e.operationName(), e -> e)); 71 | assertEquals(finishedSpans.size(), events.size()); 72 | events.stream().forEach(e -> { 73 | MockSpan finishedSpan = finishedSpans.get(e.getValue("operationName").toString()); 74 | assertNotNull(finishedSpan); 75 | assertEquals(Long.toString(finishedSpan.context().traceId()), e.getValue("traceId")); 76 | assertEquals(Long.toString(finishedSpan.context().spanId()), e.getValue("spanId")); 77 | assertEquals(finishedSpan.operationName(), e.getValue("operationName")); 78 | }); 79 | 80 | } finally { 81 | // Files.delete(output); 82 | } 83 | } 84 | 85 | @Test 86 | public void noJFR() throws IOException { 87 | // Setup tracers 88 | MockTracer mockTracer = new MockTracer(); 89 | Tracer tracer = JfrTracerFactory.create(mockTracer); 90 | 91 | // Generate span 92 | tracer.buildSpan("test span").start().finish(); 93 | 94 | // Validate span was created and recorded in JFR 95 | assertEquals(1, mockTracer.finishedSpans().size()); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/test/java/io/opentracing/contrib/jfrtracer/impl/wrapper/SpanBuilderWrapperTest.java: -------------------------------------------------------------------------------- 1 | package io.opentracing.contrib.jfrtracer.impl.wrapper; 2 | 3 | import io.opentracing.References; 4 | import io.opentracing.Span; 5 | import io.opentracing.SpanContext; 6 | import io.opentracing.Tracer.SpanBuilder; 7 | import io.opentracing.mock.MockTracer; 8 | import org.junit.jupiter.api.Test; 9 | 10 | import static org.junit.jupiter.api.Assertions.assertEquals; 11 | import static org.junit.jupiter.api.Assertions.assertNotNull; 12 | import static org.junit.jupiter.api.Assertions.assertNull; 13 | import static org.junit.jupiter.api.Assertions.assertSame; 14 | 15 | class SpanBuilderWrapperTest { 16 | 17 | @Test 18 | void asChildOfOnParentSpanContext() { 19 | MockTracer delegateTracer = new MockTracer(); 20 | Span parentSpan = delegateTracer.buildSpan("parentSpan").start(); 21 | TracerWrapper tracerWrapper = new TracerWrapper(delegateTracer); 22 | String operationName = "asChildOfOnParentSpanContext"; 23 | SpanBuilderWrapper spanBuilderWrapper = new SpanBuilderWrapper(tracerWrapper, operationName, 24 | delegateTracer.buildSpan(operationName)); 25 | 26 | SpanBuilder spanBuilder = spanBuilderWrapper.asChildOf(parentSpan.context()); 27 | assertSame(spanBuilderWrapper, spanBuilder); 28 | assertNotNull(spanBuilderWrapper.parentId()); 29 | assertEquals(parentSpan.context().toSpanId(), spanBuilderWrapper.parentId()); 30 | } 31 | 32 | @Test 33 | void asChildOfOnParentSpanContextNull() { 34 | MockTracer delegateTracer = new MockTracer(); 35 | TracerWrapper tracerWrapper = new TracerWrapper(delegateTracer); 36 | String operationName = "asChildOfOnParentSpanContextNull"; 37 | SpanBuilderWrapper spanBuilderWrapper = new SpanBuilderWrapper(tracerWrapper, operationName, 38 | delegateTracer.buildSpan(operationName)); 39 | 40 | SpanBuilder spanBuilder = spanBuilderWrapper.asChildOf((SpanContext) null); 41 | assertSame(spanBuilderWrapper, spanBuilder); 42 | assertNull(spanBuilderWrapper.parentId()); 43 | } 44 | 45 | @Test 46 | void asChildOfOnParentSpan() { 47 | MockTracer delegateTracer = new MockTracer(); 48 | Span parentSpan = delegateTracer.buildSpan("parentSpan").start(); 49 | TracerWrapper tracerWrapper = new TracerWrapper(delegateTracer); 50 | String operationName = "asChildOfOnParentSpan"; 51 | SpanBuilderWrapper spanBuilderWrapper = new SpanBuilderWrapper(tracerWrapper, operationName, 52 | delegateTracer.buildSpan(operationName)); 53 | 54 | SpanBuilder spanBuilder = spanBuilderWrapper.asChildOf(parentSpan); 55 | assertSame(spanBuilderWrapper, spanBuilder); 56 | assertNotNull(spanBuilderWrapper.parentId()); 57 | assertEquals(parentSpan.context().toSpanId(), spanBuilderWrapper.parentId()); 58 | } 59 | 60 | @Test 61 | void asChildOfOnParentSpanNull() { 62 | MockTracer delegateTracer = new MockTracer(); 63 | TracerWrapper tracerWrapper = new TracerWrapper(delegateTracer); 64 | String operationName = "asChildOfOnParentSpanNull"; 65 | SpanBuilderWrapper spanBuilderWrapper = new SpanBuilderWrapper(tracerWrapper, operationName, 66 | delegateTracer.buildSpan(operationName)); 67 | 68 | SpanBuilder spanBuilder = spanBuilderWrapper.asChildOf((Span) null); 69 | assertSame(spanBuilderWrapper, spanBuilder); 70 | assertNull(spanBuilderWrapper.parentId()); 71 | } 72 | 73 | @Test 74 | void addReferenceOnParentSpanContext() { 75 | MockTracer delegateTracer = new MockTracer(); 76 | Span parentSpan = delegateTracer.buildSpan("parentSpan").start(); 77 | TracerWrapper tracerWrapper = new TracerWrapper(delegateTracer); 78 | String operationName = "addReferenceOnParentSpanContext"; 79 | SpanBuilderWrapper spanBuilderWrapper = new SpanBuilderWrapper(tracerWrapper, operationName, 80 | delegateTracer.buildSpan(operationName)); 81 | 82 | SpanBuilder spanBuilder = spanBuilderWrapper.addReference(References.CHILD_OF, parentSpan.context()); 83 | assertSame(spanBuilderWrapper, spanBuilder); 84 | assertNotNull(spanBuilderWrapper.parentId()); 85 | assertEquals(parentSpan.context().toSpanId(), spanBuilderWrapper.parentId()); 86 | } 87 | 88 | @Test 89 | void addReferenceOnParentSpanContextNull() { 90 | MockTracer delegateTracer = new MockTracer(); 91 | TracerWrapper tracerWrapper = new TracerWrapper(delegateTracer); 92 | String operationName = "addReferenceOnParentSpanContextNull"; 93 | SpanBuilderWrapper spanBuilderWrapper = new SpanBuilderWrapper(tracerWrapper, operationName, 94 | delegateTracer.buildSpan(operationName)); 95 | 96 | SpanBuilder spanBuilder = spanBuilderWrapper.addReference(References.CHILD_OF, null); 97 | assertSame(spanBuilderWrapper, spanBuilder); 98 | assertNull(spanBuilderWrapper.parentId()); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/test/java11/io/opentracing/contrib/jfrtracer/DifferentSpanTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer; 17 | 18 | import io.opentracing.Scope; 19 | import io.opentracing.Span; 20 | import io.opentracing.Tracer; 21 | import io.opentracing.contrib.concurrent.TracedExecutorService; 22 | import io.opentracing.mock.MockSpan; 23 | import io.opentracing.mock.MockTracer; 24 | import jdk.jfr.Recording; 25 | import jdk.jfr.consumer.RecordedEvent; 26 | import jdk.jfr.consumer.RecordingFile; 27 | import org.junit.jupiter.api.Test; 28 | 29 | import java.io.IOException; 30 | import java.nio.file.Files; 31 | import java.nio.file.Path; 32 | import java.util.List; 33 | import java.util.Map; 34 | import java.util.concurrent.ExecutionException; 35 | import java.util.concurrent.Executors; 36 | import java.util.concurrent.TimeUnit; 37 | import java.util.concurrent.TimeoutException; 38 | import java.util.stream.Collectors; 39 | 40 | import static org.junit.jupiter.api.Assertions.assertEquals; 41 | import static org.junit.jupiter.api.Assertions.assertNotEquals; 42 | import static org.junit.jupiter.api.Assertions.assertNotNull; 43 | 44 | public class DifferentSpanTest { 45 | 46 | @Test 47 | public void spansInMultipleThreads() 48 | throws IOException, InterruptedException, ExecutionException, TimeoutException { 49 | Path output = Files.createTempFile("test-recording-span-multiple", ".jfr"); 50 | try { 51 | // Setup tracers 52 | MockTracer mockTracer = new MockTracer(); 53 | Tracer tracer = JfrTracerFactory.create(mockTracer); 54 | 55 | try (Recording recording = JfrTestUtils.startJFR()) { 56 | // Generate spans 57 | Scope scope = tracer.activateSpan(tracer.buildSpan("test span").start()); 58 | TracedExecutorService executor = new TracedExecutorService(Executors.newSingleThreadExecutor(), tracer); 59 | executor.submit(() -> { 60 | tracer.activateSpan(tracer.buildSpan("executor span").start()).close(); 61 | }).get(5, TimeUnit.SECONDS); 62 | scope.close(); 63 | 64 | recording.dump(output); 65 | } 66 | 67 | // Validate span was created and recorded in JFR 68 | assertEquals(2, mockTracer.finishedSpans().size()); 69 | 70 | Map finishedSpans = mockTracer.finishedSpans().stream() 71 | .collect(Collectors.toMap(e -> e.operationName(), e -> e)); 72 | List events = RecordingFile.readAllEvents(output); 73 | events.stream().forEach(e -> { 74 | MockSpan finishedSpan = finishedSpans.get(e.getString("operationName")); 75 | assertNotNull(finishedSpan); 76 | assertEquals(Long.toString(finishedSpan.context().traceId()), e.getString("traceId")); 77 | assertEquals(Long.toString(finishedSpan.context().spanId()), e.getString("spanId")); 78 | assertEquals(finishedSpan.operationName(), e.getString("operationName")); 79 | if ("executor span".equals(e.getString("operationName"))) { 80 | assertNotNull(e.getString("parentId")); 81 | } 82 | }); 83 | 84 | } finally { 85 | Files.delete(output); 86 | } 87 | } 88 | 89 | @Test 90 | public void passingSpanBetweenThreads() 91 | throws IOException, InterruptedException, TimeoutException, ExecutionException { 92 | Path output = Files.createTempFile("test-recording-span-between-threads", ".jfr"); 93 | try { 94 | // Setup tracers 95 | MockTracer mockTracer = new MockTracer(); 96 | Tracer tracer = JfrTracerFactory.create(mockTracer); 97 | 98 | try (Recording recording = JfrTestUtils.startJFR()) { 99 | 100 | // Generate spans 101 | Span span = tracer.buildSpan("test span").start(); 102 | TracedExecutorService executor = new TracedExecutorService(Executors.newSingleThreadExecutor(), tracer); 103 | executor.submit(() -> { 104 | span.finish(); 105 | }).get(5, TimeUnit.SECONDS); 106 | 107 | recording.dump(output); 108 | } 109 | 110 | // Validate span was created and recorded in JFR 111 | assertEquals(1, mockTracer.finishedSpans().size()); 112 | 113 | Map finishedSpans = mockTracer.finishedSpans().stream() 114 | .collect(Collectors.toMap(e -> e.operationName(), e -> e)); 115 | List events = RecordingFile.readAllEvents(output); 116 | assertEquals(finishedSpans.size(), events.size()); 117 | events.stream().forEach(e -> { 118 | MockSpan finishedSpan = finishedSpans.get(e.getString("operationName")); 119 | assertNotNull(finishedSpan); 120 | assertEquals(Long.toString(finishedSpan.context().traceId()), e.getString("traceId")); 121 | assertEquals(Long.toString(finishedSpan.context().spanId()), e.getString("spanId")); 122 | assertEquals(finishedSpan.operationName(), e.getString("operationName")); 123 | assertNotEquals(Thread.currentThread().getName(), e.getThread().getJavaName()); 124 | }); 125 | 126 | } finally { 127 | Files.delete(output); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/test/java11/io/opentracing/contrib/jfrtracer/ImplementationsJFRTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer; 17 | 18 | import brave.Tracing; 19 | import brave.opentracing.BraveTracer; 20 | import brave.propagation.B3Propagation; 21 | import brave.propagation.ExtraFieldPropagation; 22 | import brave.propagation.Propagation.Factory; 23 | import io.jaegertracing.Configuration.CodecConfiguration; 24 | import io.jaegertracing.Configuration.ReporterConfiguration; 25 | import io.jaegertracing.Configuration.SamplerConfiguration; 26 | import io.opentracing.Scope; 27 | import io.opentracing.Span; 28 | import io.opentracing.Tracer; 29 | import jdk.jfr.Recording; 30 | import jdk.jfr.consumer.RecordedEvent; 31 | import jdk.jfr.consumer.RecordingFile; 32 | import org.junit.jupiter.api.Disabled; 33 | import org.junit.jupiter.api.Test; 34 | 35 | import java.io.IOException; 36 | import java.nio.file.Files; 37 | import java.nio.file.Path; 38 | import java.util.Arrays; 39 | import java.util.List; 40 | 41 | import static io.jaegertracing.Configuration.JAEGER_AGENT_HOST; 42 | import static io.jaegertracing.Configuration.JAEGER_AGENT_PORT; 43 | import static io.jaegertracing.Configuration.JAEGER_PROPAGATION; 44 | import static io.jaegertracing.Configuration.JAEGER_SAMPLER_PARAM; 45 | import static io.jaegertracing.Configuration.JAEGER_SAMPLER_TYPE; 46 | import static org.junit.jupiter.api.Assertions.assertEquals; 47 | import static org.junit.jupiter.api.Assertions.assertNotNull; 48 | 49 | public class ImplementationsJFRTest { 50 | 51 | @Test 52 | public void jaegerB3() throws IOException { 53 | System.setProperty(JAEGER_SAMPLER_TYPE, "const"); 54 | System.setProperty(JAEGER_SAMPLER_PARAM, "1"); 55 | System.setProperty(JAEGER_AGENT_HOST, "localhost"); 56 | System.setProperty(JAEGER_AGENT_PORT, "6831"); 57 | System.setProperty(JAEGER_PROPAGATION, "B3"); 58 | 59 | Tracer jaegerTracer = new io.jaegertracing.Configuration("test").withSampler(SamplerConfiguration.fromEnv()) 60 | .withCodec(CodecConfiguration.fromEnv()).withReporter(ReporterConfiguration.fromEnv()).getTracer(); 61 | innerTest(jaegerTracer); 62 | } 63 | 64 | @Test 65 | public void jaegerUber() throws IOException { 66 | System.setProperty(JAEGER_SAMPLER_TYPE, "const"); 67 | System.setProperty(JAEGER_SAMPLER_PARAM, "1"); 68 | System.setProperty(JAEGER_AGENT_HOST, "localhost"); 69 | System.setProperty(JAEGER_AGENT_PORT, "6831"); 70 | System.setProperty(JAEGER_PROPAGATION, "JAEGER"); 71 | 72 | Tracer jaegerTracer = new io.jaegertracing.Configuration("test").withSampler(SamplerConfiguration.fromEnv()) 73 | .withCodec(CodecConfiguration.fromEnv()).withReporter(ReporterConfiguration.fromEnv()).getTracer(); 74 | innerTest(jaegerTracer); 75 | } 76 | 77 | @Test 78 | public void brave() throws IOException { 79 | 80 | Factory propagationFactory = ExtraFieldPropagation.newFactoryBuilder(B3Propagation.FACTORY) 81 | .addPrefixedFields("baggage-", Arrays.asList("country-code", "user-id")).build(); 82 | 83 | Tracing braveTracing = Tracing.newBuilder().localServiceName("my-service") 84 | .propagationFactory(propagationFactory).build(); 85 | innerTest(BraveTracer.create(braveTracing)); 86 | } 87 | 88 | @SuppressWarnings("try") 89 | private void innerTest(Tracer testTracer) throws IOException { 90 | Path output = Files.createTempFile("test-recording", ".jfr"); 91 | try { 92 | 93 | Tracer tracer = JfrTracerFactory.create(testTracer); 94 | 95 | try (Recording recording = JfrTestUtils.startJFR()) { 96 | 97 | // Generate span 98 | Span start = tracer.buildSpan("outer span").start(); 99 | try (Scope activate = tracer.scopeManager().activate(start)) { 100 | tracer.activateSpan(tracer.buildSpan("inner span").start()).close(); 101 | } 102 | start.finish(); 103 | 104 | recording.dump(output); 105 | } 106 | 107 | // Validate span was created and recorded in JFR 108 | List events = RecordingFile.readAllEvents(output); 109 | assertEquals(4, events.size()); 110 | events.stream().forEach(e -> { 111 | assertNotNull(e.getString("operationName")); 112 | if (e.getString("operationName").equals("inner span")) { 113 | assertNotNull(e.getString("parentId")); 114 | } 115 | assertNotNull(e.getString("traceId")); 116 | assertNotNull(e.getString("spanId")); 117 | }); 118 | 119 | } finally { 120 | Files.delete(output); 121 | } 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/test/java11/io/opentracing/contrib/jfrtracer/JfrTestUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer; 17 | 18 | import java.nio.file.Files; 19 | import java.nio.file.Path; 20 | 21 | import jdk.jfr.Recording; 22 | 23 | public final class JfrTestUtils { 24 | 25 | private JfrTestUtils() { 26 | } 27 | 28 | public static Recording startJFR() { 29 | Recording recording = new Recording(); 30 | recording.start(); 31 | return recording; 32 | } 33 | 34 | public static void sleep(int millis) { 35 | try { 36 | Thread.sleep(millis); 37 | } catch (InterruptedException e) { 38 | } 39 | } 40 | 41 | public static void delete(Path output) { 42 | try { 43 | Files.delete(output); 44 | } catch (Throwable t) { 45 | // Should not affect test... 46 | System.err.println("Failed to delete test JFR-file: " + t.getMessage()); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/test/java11/io/opentracing/contrib/jfrtracer/JfrTracerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The OpenTracing Authors 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 io.opentracing.contrib.jfrtracer; 17 | 18 | import io.opentracing.Scope; 19 | import io.opentracing.Span; 20 | import io.opentracing.Tracer; 21 | import io.opentracing.mock.MockSpan; 22 | import io.opentracing.mock.MockTracer; 23 | import jdk.jfr.FlightRecorder; 24 | import jdk.jfr.Recording; 25 | import jdk.jfr.consumer.RecordedEvent; 26 | import jdk.jfr.consumer.RecordingFile; 27 | import org.junit.jupiter.api.Disabled; 28 | import org.junit.jupiter.api.Test; 29 | 30 | import java.io.IOException; 31 | import java.nio.file.Files; 32 | import java.nio.file.Path; 33 | import java.util.List; 34 | import java.util.Map; 35 | import java.util.concurrent.TimeUnit; 36 | import java.util.stream.Collectors; 37 | 38 | import static org.awaitility.Awaitility.await; 39 | import static org.junit.jupiter.api.Assertions.assertEquals; 40 | import static org.junit.jupiter.api.Assertions.assertFalse; 41 | import static org.junit.jupiter.api.Assertions.assertNotEquals; 42 | import static org.junit.jupiter.api.Assertions.assertNotNull; 43 | import static org.junit.jupiter.api.Assertions.assertNull; 44 | import static org.junit.jupiter.api.Assertions.assertTrue; 45 | 46 | public class JfrTracerTest { 47 | 48 | /** 49 | * Test JFR gets the generated span 50 | * 51 | * @throws java.io.IOException 52 | * on error 53 | */ 54 | @SuppressWarnings("deprecation") 55 | @Test 56 | public void basicEvent() throws IOException, InterruptedException { 57 | Path output = Files.createTempFile("test-recording-basic-11", ".jfr"); 58 | try { 59 | // Setup tracers 60 | MockTracer mockTracer = new MockTracer(); 61 | Tracer tracer = JfrTracerFactory.create(mockTracer); 62 | 63 | try (Recording recording = JfrTestUtils.startJFR()) { 64 | 65 | // Generate span 66 | tracer.buildSpan("test span").start().finish(); 67 | 68 | // To be removed when test are fixed, it's used due to concurrency issue 69 | Thread.sleep(100); 70 | 71 | recording.dump(output); 72 | recording.stop(); 73 | } 74 | 75 | // Validate span was created and recorded in JFR 76 | assertEquals(1, mockTracer.finishedSpans().size()); 77 | 78 | Map finishedSpans = mockTracer.finishedSpans().stream() 79 | .collect(Collectors.toMap(e -> e.operationName(), e -> e)); 80 | List events = RecordingFile.readAllEvents(output); 81 | assertEquals(finishedSpans.size(), events.size()); 82 | events.stream().forEach(e -> { 83 | MockSpan finishedSpan = finishedSpans.get(e.getString("operationName")); 84 | assertNotNull(finishedSpan); 85 | assertEquals(Long.toString(finishedSpan.context().traceId()), e.getString("traceId")); 86 | assertEquals(Long.toString(finishedSpan.context().spanId()), e.getString("spanId")); 87 | assertEquals(finishedSpan.operationName(), e.getString("operationName")); 88 | assertTrue(e.getEventType().getName().contains("Span")); 89 | }); 90 | 91 | } finally { 92 | JfrTestUtils.delete(output); 93 | } 94 | } 95 | 96 | @Test 97 | public void noJFR() throws IOException { 98 | // Setup tracers 99 | MockTracer mockTracer = new MockTracer(); 100 | Tracer tracer = JfrTracerFactory.create(mockTracer); 101 | 102 | // Generate span 103 | assertNull(tracer.scopeManager().activeSpan()); 104 | tracer.activateSpan(tracer.buildSpan("test span").start()).close(); 105 | 106 | // Validate span was created and recorded in JFR 107 | assertEquals(1, mockTracer.finishedSpans().size()); 108 | assertNull(tracer.scopeManager().activeSpan()); 109 | } 110 | 111 | @Test 112 | @Disabled("This test is currently unreliable, and should be fixed") 113 | @SuppressWarnings("try") 114 | public void noRunningJFR() throws IOException, InterruptedException { 115 | // Setup tracers 116 | MockTracer mockTracer = new MockTracer(); 117 | Tracer tracer = JfrTracerFactory.create(mockTracer); 118 | 119 | Recording recording = JfrTestUtils.startJFR(); 120 | 121 | // Generate span 122 | assertNull(tracer.scopeManager().activeSpan()); 123 | try (Scope scope = tracer.activateSpan(tracer.buildSpan("outer span").start())) { 124 | Span activeSpanOuter = tracer.scopeManager().activeSpan(); 125 | assertNotNull(activeSpanOuter); 126 | recording.close(); 127 | while (!FlightRecorder.getFlightRecorder().getRecordings().isEmpty()) { 128 | System.out.println(FlightRecorder.getFlightRecorder().getRecordings().size()); 129 | } 130 | await().atMost(20, TimeUnit.SECONDS) 131 | .until(() -> FlightRecorder.getFlightRecorder().getRecordings().isEmpty()); 132 | try (Scope inner = tracer.activateSpan(tracer.buildSpan("inner span").start())) { 133 | Span activeSpanInner = tracer.scopeManager().activeSpan(); 134 | assertNotNull(activeSpanInner); 135 | assertNotEquals(activeSpanOuter, activeSpanInner); 136 | } 137 | } 138 | try (Scope scope = tracer.activateSpan(tracer.buildSpan("separate span").start())) { 139 | Span activeSpan = tracer.scopeManager().activeSpan(); 140 | assertNotNull(activeSpan); 141 | assertFalse(activeSpan.getClass().getSimpleName().contains("Span")); 142 | } 143 | 144 | // Validate span was created and recorded in JFR 145 | assertEquals(3, mockTracer.finishedSpans().size()); 146 | assertNull(tracer.scopeManager().activeSpan()); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /opentracing-jfr-tracer/src/test/resources/io/opentracing/contrib/jfrtracer/opentracing.jfc: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | true 7 | false 8 | 9 | 10 | true 11 | true 12 | 13 | 14 | 15 | 16 | 17 | 18 | true 19 | 20 | 21 | 22 | true 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'java-jfr-tracer' 2 | 3 | include 'opentracing-jfr-tracer' --------------------------------------------------------------------------------