├── .dockerignore ├── .github ├── CODEOWNERS ├── header-checker-lint.yml ├── snippet-bot.yml └── workflows │ ├── codeql-analysis.yml │ └── pr-build.yml ├── .gitignore ├── LICENSE ├── README.md ├── RELEASING.md ├── SECURITY.md ├── build.gradle ├── buildscripts ├── spotless.license.dockerfile ├── spotless.license.gradle ├── spotless.license.java ├── spotless.license.shell └── spotless.license.yaml ├── cloudbuild-e2e-cloud-functions-gen2.yaml ├── cloudbuild-e2e-cloud-run.yaml ├── cloudbuild-e2e-gae.yaml ├── cloudbuild-e2e-gce.yaml ├── cloudbuild-e2e-gke.yaml ├── cloudbuild-e2e-image.yaml ├── cloudbuild-e2e-local.yaml ├── detectors └── resources-support │ ├── README.md │ ├── build.gradle │ ├── gradle.properties │ └── src │ ├── main │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── detection │ │ ├── AttributeKeys.java │ │ ├── DetectedPlatform.java │ │ ├── EnvironmentVariables.java │ │ ├── GCPMetadataConfig.java │ │ ├── GCPPlatformDetector.java │ │ ├── GoogleAppEngine.java │ │ ├── GoogleCloudFunction.java │ │ ├── GoogleCloudRun.java │ │ ├── GoogleCloudRunJob.java │ │ ├── GoogleComputeEngine.java │ │ ├── GoogleKubernetesEngine.java │ │ ├── GoogleServerlessCompute.java │ │ └── UnknownPlatform.java │ └── test │ └── java │ └── com │ └── google │ └── cloud │ └── opentelemetry │ └── detection │ ├── EnvVarMock.java │ ├── GCPMetadataConfigTest.java │ ├── GCPPlatformDetectorTest.java │ └── TestUtils.java ├── docs ├── code-of-conduct.md └── contributing.md ├── e2e-test-server ├── README.md ├── build.gradle ├── gradle.properties ├── src │ └── main │ │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── endtoend │ │ ├── CloudFunctionHandler.java │ │ ├── Constants.java │ │ ├── PubSubMessageHandler.java │ │ ├── PubSubPullServer.java │ │ ├── PubSubPushServer.java │ │ ├── PubSubServer.java │ │ ├── Request.java │ │ ├── Response.java │ │ ├── ScenarioHandler.java │ │ ├── ScenarioHandlerManager.java │ │ └── Server.java └── wait-for-image.sh ├── e2e.Dockerfile ├── examples ├── autoconf │ ├── README.md │ ├── build.gradle │ ├── job.yaml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── example │ │ └── autoconf │ │ └── AutoconfExample.java ├── autoinstrument │ ├── README.md │ ├── build.gradle │ ├── deployment.yaml │ ├── run_in_cloud-run.sh │ ├── run_in_docker.sh │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── example │ │ │ ├── CloudTraceLogAttacher.java │ │ │ ├── GreetingClient.java │ │ │ └── TestMain.java │ │ └── resources │ │ ├── application.properties │ │ └── logback.xml ├── instrumentation-quickstart │ ├── .dockerignore │ ├── .gitignore │ ├── Dockerfile │ ├── README.md │ ├── build.gradle │ ├── cloudbuild-integration.yaml │ ├── cloudbuild-uninstrumented-app.yaml │ ├── docker-compose.cloudbuild.yaml │ ├── docker-compose.creds.yaml │ ├── docker-compose.yaml │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── integrationtest │ │ ├── go.mod │ │ ├── go.sum │ │ └── quickstart_test.go │ ├── otel-collector-config.yaml │ ├── settings.gradle │ ├── src │ │ ├── main │ │ │ ├── java │ │ │ │ └── com │ │ │ │ │ └── example │ │ │ │ │ └── demo │ │ │ │ │ ├── DemoApplication.java │ │ │ │ │ ├── MultiController.java │ │ │ │ │ └── SingleController.java │ │ │ └── resources │ │ │ │ └── log4j2.xml │ │ └── test │ │ │ └── java │ │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ └── DemoApplicationTests.java │ └── uninstrumented.Dockerfile ├── metrics │ ├── README.md │ ├── build.gradle │ ├── run_as_cloud-run-job.sh │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── example │ │ └── metrics │ │ └── MetricsExporterExample.java ├── otlp-spring │ ├── README.md │ ├── build.gradle │ ├── k8s │ │ └── deployment.yaml │ └── src │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── google │ │ │ │ └── cloud │ │ │ │ └── opentelemetry │ │ │ │ └── examples │ │ │ │ └── otlpspring │ │ │ │ ├── ApplicationController.java │ │ │ │ ├── Main.java │ │ │ │ └── configuration │ │ │ │ └── OpenTelemetryConfiguration.java │ │ └── resources │ │ │ └── application.properties │ │ └── test │ │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── examples │ │ └── otlpspring │ │ └── MainClient.java ├── otlpmetric │ ├── README.md │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── example │ │ └── otlpmetric │ │ └── OTLPMetricExample.java ├── otlpmetrics-function │ ├── README.md │ ├── build.gradle │ ├── collector-deployment │ │ ├── Dockerfile │ │ └── collector-config.yaml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── examples │ │ └── otlpmetricsfunction │ │ ├── HelloWorld.java │ │ └── OpenTelemetryConfig.java ├── otlptrace │ ├── README.md │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── example │ │ └── otlptrace │ │ └── OTLPTraceExample.java ├── resource │ ├── README.md │ ├── build.gradle │ ├── job.yaml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── example │ │ └── resource │ │ └── ResourceExample.java ├── spring-boot-starter │ ├── README.md │ ├── build.gradle │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── cloud │ │ │ └── opentelemetry │ │ │ └── example │ │ │ └── springbootstarter │ │ │ ├── AppController.java │ │ │ └── SpringBootStarterApplication.java │ │ └── resources │ │ └── application.properties ├── spring-sleuth │ ├── README.md │ ├── build.gradle │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── cloud │ │ │ └── opentelemetry │ │ │ └── example │ │ │ └── springsleuth │ │ │ ├── GreetingClient.java │ │ │ └── Main.java │ │ └── resources │ │ └── application.properties ├── spring │ ├── README.md │ ├── build.gradle │ ├── run_in_cloud-run.sh │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── google │ │ │ └── cloud │ │ │ └── opentelemetry │ │ │ └── example │ │ │ └── spring │ │ │ ├── AppController.java │ │ │ ├── Main.java │ │ │ └── OpenTelemetryConfiguration.java │ │ └── resources │ │ └── application.properties └── trace │ ├── README.md │ ├── build.gradle │ └── src │ ├── main │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── example │ │ └── trace │ │ └── TraceExporterExample.java │ └── test │ └── java │ └── com │ └── google │ └── cloud │ └── opentelemetry │ └── example │ └── trace │ └── TraceExporterExampleTest.java ├── exporters ├── auto │ ├── README.md │ ├── build.gradle │ ├── gradle.properties │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── auto │ │ ├── Constants.java │ │ ├── GoogleCloudMetricExporterFactory.java │ │ └── GoogleCloudSpanExporterFactory.java ├── metrics │ ├── README.md │ ├── build.gradle │ ├── gradle.properties │ └── src │ │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── google │ │ │ └── cloud │ │ │ └── opentelemetry │ │ │ └── metric │ │ │ ├── AggregateByLabelMetricTimeSeriesBuilder.java │ │ │ ├── CloudMetricClient.java │ │ │ ├── CloudMetricClientImpl.java │ │ │ ├── GoogleCloudMetricExporter.java │ │ │ ├── InternalMetricExporter.java │ │ │ ├── MetricConfiguration.java │ │ │ ├── MetricDescriptorStrategy.java │ │ │ ├── MetricTimeSeriesBuilder.java │ │ │ ├── MetricTranslator.java │ │ │ ├── MetricWithLabels.java │ │ │ ├── MonitoredResourceDescription.java │ │ │ ├── NoopMetricExporter.java │ │ │ └── ResourceTranslator.java │ │ └── test │ │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── metric │ │ ├── EndToEndTest.java │ │ ├── FakeData.java │ │ ├── GoogleCloudMetricExporterTest.java │ │ ├── MetricConfigurationTest.java │ │ ├── MetricDescriptorStrategyTest.java │ │ ├── MetricTranslatorTest.java │ │ └── MockServerStartupException.java └── trace │ ├── README.md │ ├── build.gradle │ ├── gradle.properties │ └── src │ ├── main │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── trace │ │ ├── CloudTraceClient.java │ │ ├── CloudTraceClientImpl.java │ │ ├── InternalTraceExporter.java │ │ ├── NoopSpanExporter.java │ │ ├── TraceConfiguration.java │ │ ├── TraceExporter.java │ │ ├── TraceTranslator.java │ │ └── TraceVersions.java │ └── test │ └── java │ └── com │ └── google │ └── cloud │ └── opentelemetry │ └── trace │ ├── EndToEndTest.java │ ├── MockCloudTraceClient.java │ ├── MockServerStartupException.java │ ├── TraceConfigurationTest.java │ ├── TraceExporterTest.java │ ├── TraceTranslatorTest.java │ └── TraceVersionsTest.java ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── propagators ├── README.md └── gcp │ ├── README.md │ ├── build.gradle │ ├── gradle.properties │ └── src │ ├── main │ └── java │ │ └── com │ │ └── google │ │ └── cloud │ │ └── opentelemetry │ │ └── propagators │ │ ├── OneWayXCloudTraceConfigurablePropagatorProvider.java │ │ ├── XCloudTraceConfigurablePropagatorProvider.java │ │ └── XCloudTraceContextPropagator.java │ └── test │ └── java │ └── com │ └── google │ └── cloud │ └── opentelemetry │ └── propagators │ ├── AutoConfigureTest.java │ └── PropagatorTest.java ├── settings.gradle └── shared └── resourcemapping ├── build.gradle ├── gradle.properties └── src ├── main └── java │ └── com │ └── google │ └── cloud │ └── opentelemetry │ └── resource │ ├── GcpResource.java │ ├── ResourceLabels.java │ └── ResourceTranslator.java └── test └── java └── com └── google └── cloud └── opentelemetry └── resource └── ResourceTranslatorTest.java /.dockerignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | .gradle/ 3 | out/ 4 | .project 5 | .settings 6 | .classpath 7 | 8 | # IDE(A) files 9 | .idea/ 10 | .settings/ 11 | .vscode/ 12 | .classpath 13 | .project 14 | 15 | # Build artifacts 16 | **/build/ 17 | **/bin/ 18 | 19 | # Mock server download 20 | mock_server* 21 | 22 | # Docker files 23 | *Dockerfile 24 | 25 | # Git repo contents 26 | .git/ 27 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # Global owners 16 | * @GoogleCloudPlatform/opentelemetry-ops 17 | -------------------------------------------------------------------------------- /.github/header-checker-lint.yml: -------------------------------------------------------------------------------- 1 | allowedLicenses: 2 | - Apache-2.0 3 | sourceFileExtensions: 4 | - gradle 5 | - java 6 | - sh 7 | - Dockerfile 8 | allowedCopyrightHolders: 9 | - Google LLC 10 | ignoreFiles: 11 | - buildscripts/* 12 | -------------------------------------------------------------------------------- /.github/snippet-bot.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoogleCloudPlatform/opentelemetry-operations-java/4a5876da5552cdd5207e0b71011b85327265574b/.github/snippet-bot.yml -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL Analysis" 2 | 3 | on: 4 | workflow_dispatch: 5 | schedule: 6 | # ┌───────────── minute (0 - 59) 7 | # │ ┌───────────── hour (0 - 23) 8 | # │ │ ┌───────────── day of the month (1 - 31) 9 | # │ │ │ ┌───────────── month (1 - 12 or JAN-DEC) 10 | # │ │ │ │ ┌───────────── day of the week (0 - 6 or SUN-SAT) 11 | # │ │ │ │ │ 12 | # │ │ │ │ │ 13 | # │ │ │ │ │ 14 | # * * * * * 15 | - cron: '30 1 * * *' 16 | push: 17 | branches: [ main ] 18 | pull_request: 19 | 20 | jobs: 21 | CodeQL-Build: 22 | runs-on: ubuntu-latest 23 | 24 | steps: 25 | - name: Checkout repository 26 | uses: actions/checkout@v4 27 | 28 | - name: Set up Java 17 29 | uses: actions/setup-java@v3 30 | with: 31 | distribution: temurin 32 | java-version: 17 33 | 34 | # Initializes the CodeQL tools for scanning. 35 | - name: Initialize CodeQL 36 | uses: github/codeql-action/init@v2 37 | with: 38 | languages: java 39 | # using "latest" helps to keep up with the latest Kotlin support 40 | # see https://github.com/github/codeql-action/issues/1555#issuecomment-1452228433 41 | tools: latest 42 | 43 | - uses: gradle/gradle-build-action@v2 44 | with: 45 | # skipping build cache is needed so that all modules will be analyzed 46 | arguments: assemble --no-build-cache 47 | 48 | - name: Perform CodeQL Analysis 49 | uses: github/codeql-action/analyze@v2 50 | -------------------------------------------------------------------------------- /.github/workflows/pr-build.yml: -------------------------------------------------------------------------------- 1 | name: "Pull Request Build" 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | jobs: 8 | test: 9 | strategy: 10 | matrix: 11 | java-version: [11] 12 | build-root: [".", "examples/instrumentation-quickstart"] 13 | include: 14 | - build-root: . 15 | name: root 16 | name: Test (${{matrix.name || matrix.build-root}}, java-${{matrix.java-version}}) 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v2 20 | with: 21 | fetch-depth: 0 22 | - id: setup-java 23 | name: Setup Java ${{matrix.java-version}} 24 | uses: actions/setup-java@v1 25 | with: 26 | java-version: ${{matrix.java-version}} 27 | - uses: burrunan/gradle-cache-action@v1.6 28 | with: 29 | job-id: java-${{matrix.java-version}} 30 | remote-build-cache-proxy-enabled: false 31 | build-root-directory: ${{matrix.build-root}} 32 | arguments: test 33 | shadow: 34 | strategy: 35 | matrix: 36 | java-version: [11] 37 | name: Shadow Jar Build (Java ${{matrix.java-version}}) 38 | runs-on: ubuntu-latest 39 | steps: 40 | - id: checkout-repo 41 | uses: actions/checkout@v2 42 | with: 43 | fetch-depth: 0 44 | - id: setup-java 45 | name: Setup Java ${{matrix.java-version}} 46 | uses: actions/setup-java@v1 47 | with: 48 | java-version: ${{matrix.java-version}} 49 | - id: setup-gradle-cache 50 | name: Run Gradle Build with ShadowJar 51 | uses: burrunan/gradle-cache-action@v1.6 52 | with: 53 | job-id: gradle-shadow-java-${{matrix.java-version}} 54 | remote-build-cache-proxy-enabled: false 55 | build-root-directory: . 56 | arguments: shadowJar 57 | style: 58 | name: Stylecheck (${{matrix.name || matrix.build-root}}) 59 | runs-on: ubuntu-latest 60 | strategy: 61 | matrix: 62 | java-version: [11] 63 | build-root: [".", "examples/instrumentation-quickstart"] 64 | include: 65 | - build-root: . 66 | name: root 67 | steps: 68 | - uses: actions/checkout@v2 69 | with: 70 | fetch-depth: 0 71 | - id: setup-java 72 | name: Setup Java ${{matrix.java-version}} 73 | uses: actions/setup-java@v1 74 | with: 75 | java-version: ${{matrix.java-version}} 76 | - uses: burrunan/gradle-cache-action@v1.6 77 | with: 78 | job-id: java-${{matrix.java-version}} 79 | remote-build-cache-proxy-enabled: false 80 | build-root-directory: ${{matrix.build-root}} 81 | arguments: spotlessCheck 82 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | .gradle/ 3 | out/ 4 | .project 5 | .settings 6 | .classpath 7 | 8 | # IDE(A) files 9 | .idea/ 10 | .settings/ 11 | .vscode/ 12 | .classpath 13 | .project 14 | 15 | # Build artifacts 16 | build/ 17 | bin/ 18 | 19 | # Mock server download 20 | mock_server* 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Open-Telemetry Operations Exporters for Java 2 | 3 | [![Maven Central][maven-image]][maven-url] 4 | 5 | Provides OpenTelemetry Exporters for Google Cloud Operations. 6 | 7 | To get started with instrumentation in Google Cloud, see [Generate traces and metrics with 8 | Java](https://cloud.google.com/stackdriver/docs/instrumentation/setup/java). 9 | 10 | To learn more about instrumentation and observability, including opinionated recommendations 11 | for Google Cloud Observability, visit [Instrumentation and 12 | observability](https://cloud.google.com/stackdriver/docs/instrumentation/overview). 13 | 14 | ## Building 15 | 16 | > [!IMPORTANT] 17 | > This project requires Java 11 to build and test. All artifacts published from this project support Java 8 or higher, unless otherwise noted. 18 | 19 | This project requires a mock server for Google Cloud APIs. To build and test, do the following: 20 | 21 | ``` 22 | $ ./gradlew test 23 | ``` 24 | 25 | Note: This project uses [Test Containers](http://testcontainers.org), which requires 26 | docker to be runnable locally by the current users. Please verify `docker run hello-world` works, and if not configure your local docker before building. 27 | 28 | 29 | ## Contributing 30 | 31 | See [contributing guide](docs/contributing.md). 32 | 33 | 34 | ### Enforcing Style 35 | 36 | This project uses the spotless plugin to enforce style. You can automatically correct any issues by running: 37 | 38 | ``` 39 | $ ./gradlew spotlessApply 40 | ``` 41 | 42 | 43 | ## Google Cloud Trace Exporter 44 | 45 | See [Tracing Readme](exporters/trace/README.md) for installation and usage instructions. 46 | 47 | ## Google Cloud Monitoring Exporter 48 | 49 | See [Metrics Readme](exporters/metrics/README.md) for installation and usage instructions. 50 | 51 | ## Google Cloud Autoconfigure module 52 | 53 | *Note: This is an alpha-release.* 54 | 55 | See [Autoconfigure Readme](exporters/auto/README.md) for installation and usage instructions. 56 | 57 | 58 | [maven-image]: https://img.shields.io/maven-central/v/com.google.cloud.opentelemetry/exporter-trace?color=dark-green 59 | [maven-url]: https://central.sonatype.com/artifact/com.google.cloud.opentelemetry/exporter-trace 60 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | We support only the last minor version of each supported major release: bug fixes are released either as part of the next minor version or as an on-demand patch version. Independent of which version is next, all patch versions are cumulative, meaning that they represent the state of our main branch at the moment of the release. For instance, if the latest version is 0.10.0, bug fixes are released either as part of 0.11.0 or 0.10.1. 6 | 7 | Major releases are supported for 12 months after a new major version is released: https://opensource.google/documentation/policies/library-breaking-change. 8 | 9 | Security fixes are given priority and might be enough to cause a new version to be released. 10 | 11 | ## Reporting a Vulnerability 12 | 13 | In order for the vulnerability reports to reach maintainers as soon as possible, please use the `Report a vulnerability` button on the `Security` tab in the respective GitHub repository. It creates a private communication channel between the reporter and the maintainers. 14 | 15 | -------------------------------------------------------------------------------- /buildscripts/spotless.license.dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright $YEAR Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /buildscripts/spotless.license.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright $YEAR Google LLC 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 | -------------------------------------------------------------------------------- /buildscripts/spotless.license.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright $YEAR Google LLC 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 | -------------------------------------------------------------------------------- /buildscripts/spotless.license.shell: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright $YEAR Google LLC 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 | -------------------------------------------------------------------------------- /buildscripts/spotless.license.yaml: -------------------------------------------------------------------------------- 1 | # Copyright $YEAR Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /cloudbuild-e2e-cloud-functions-gen2.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | steps: 15 | # Generate shadowJar for the instrumented test server 16 | - name: "gradle:8.0.2-jdk11" 17 | id: generate-jar 18 | entrypoint: "gradle" 19 | timeout: 4m 20 | args: [":e2e-test-server:build"] 21 | 22 | # Zip the generated JAR file 23 | - name: ubuntu 24 | id: zip-jar 25 | entrypoint: bash 26 | args: 27 | - '-c' 28 | - | 29 | apt-get update && \ 30 | apt-get install zip --assume-yes && \ 31 | cd e2e-test-server/build/libs && \ 32 | zip function-source e2e-test-server-0.1.0-SNAPSHOT-all.jar 33 | 34 | # Run the test 35 | - name: $_TEST_RUNNER_IMAGE 36 | id: run-tests-cloudfunction 37 | dir: / 38 | env: ["PROJECT_ID=$PROJECT_ID"] 39 | args: 40 | - cloud-functions-gen2 41 | - --functionsource=/workspace/e2e-test-server/build/libs/function-source.zip 42 | - --runtime=java11 43 | - --entrypoint=com.google.cloud.opentelemetry.endtoend.CloudFunctionHandler 44 | 45 | logsBucket: gs://opentelemetry-ops-e2e-cloud-build-logs 46 | substitutions: 47 | _TEST_RUNNER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-e2e-testing:0.20.1 48 | _TEST_SERVER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-java-e2e-test-server:${SHORT_SHA} 49 | -------------------------------------------------------------------------------- /cloudbuild-e2e-cloud-run.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | steps: 15 | # Wait for the image to exist 16 | - name: "docker" 17 | id: wait-for-image 18 | entrypoint: "sh" 19 | timeout: 3m 20 | env: ["_TEST_SERVER_IMAGE=${_TEST_SERVER_IMAGE}"] 21 | args: 22 | - e2e-test-server/wait-for-image.sh 23 | 24 | # Run the test 25 | - name: $_TEST_RUNNER_IMAGE 26 | id: run-tests-cloudrun 27 | dir: / 28 | env: ["PROJECT_ID=$PROJECT_ID"] 29 | args: 30 | - cloud-run 31 | - --image=$_TEST_SERVER_IMAGE 32 | 33 | logsBucket: gs://opentelemetry-ops-e2e-cloud-build-logs 34 | substitutions: 35 | _TEST_RUNNER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-e2e-testing:0.20.1 36 | _TEST_SERVER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-java-e2e-test-server:${SHORT_SHA} 37 | -------------------------------------------------------------------------------- /cloudbuild-e2e-gae.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | steps: 15 | # Wait for the image to exist 16 | - name: "docker" 17 | id: wait-for-image 18 | entrypoint: "sh" 19 | timeout: 3m 20 | env: [ "_TEST_SERVER_IMAGE=${_TEST_SERVER_IMAGE}" ] 21 | args: 22 | - e2e-test-server/wait-for-image.sh 23 | 24 | # Run the test 25 | - name: $_TEST_RUNNER_IMAGE 26 | id: run-tests-gae 27 | dir: / 28 | env: [ "PROJECT_ID=$PROJECT_ID" ] 29 | args: 30 | - gae 31 | - --image=$_TEST_SERVER_IMAGE 32 | - --runtime=java11 33 | 34 | logsBucket: gs://opentelemetry-ops-e2e-cloud-build-logs 35 | substitutions: 36 | _TEST_RUNNER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-e2e-testing:0.20.1 37 | _TEST_SERVER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-java-e2e-test-server:${SHORT_SHA} 38 | -------------------------------------------------------------------------------- /cloudbuild-e2e-gce.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | steps: 15 | # Wait for the image to exist 16 | - name: "docker" 17 | id: wait-for-image 18 | entrypoint: "sh" 19 | timeout: 3m 20 | env: ["_TEST_SERVER_IMAGE=${_TEST_SERVER_IMAGE}"] 21 | args: 22 | - e2e-test-server/wait-for-image.sh 23 | 24 | # Run the test 25 | - name: $_TEST_RUNNER_IMAGE 26 | id: run-tests-gce 27 | dir: / 28 | env: ["PROJECT_ID=$PROJECT_ID"] 29 | args: 30 | - gce 31 | - --image=$_TEST_SERVER_IMAGE 32 | 33 | logsBucket: gs://opentelemetry-ops-e2e-cloud-build-logs 34 | substitutions: 35 | _TEST_RUNNER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-e2e-testing:0.20.1 36 | _TEST_SERVER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-java-e2e-test-server:${SHORT_SHA} 37 | -------------------------------------------------------------------------------- /cloudbuild-e2e-gke.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | steps: 15 | # Wait for the image to exist 16 | - name: "docker" 17 | id: wait-for-image 18 | entrypoint: "sh" 19 | timeout: 3m 20 | env: ["_TEST_SERVER_IMAGE=${_TEST_SERVER_IMAGE}"] 21 | args: 22 | - e2e-test-server/wait-for-image.sh 23 | 24 | # Run the test 25 | - name: $_TEST_RUNNER_IMAGE 26 | id: run-tests-gke 27 | dir: / 28 | env: ["PROJECT_ID=$PROJECT_ID"] 29 | args: 30 | - gke 31 | - --image=$_TEST_SERVER_IMAGE 32 | 33 | logsBucket: gs://opentelemetry-ops-e2e-cloud-build-logs 34 | substitutions: 35 | _TEST_RUNNER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-e2e-testing:0.20.1 36 | _TEST_SERVER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-java-e2e-test-server:${SHORT_SHA} 37 | -------------------------------------------------------------------------------- /cloudbuild-e2e-image.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | steps: 15 | - name: docker 16 | entrypoint: "sh" 17 | args: 18 | - -c 19 | - | 20 | if docker manifest inspect ${_TEST_SERVER_IMAGE} > /dev/null; then 21 | echo "Image already exists, will skip building" 22 | exit 23 | fi 24 | docker build --tag=${_TEST_SERVER_IMAGE} --file=e2e.Dockerfile . 25 | docker push ${_TEST_SERVER_IMAGE} 26 | 27 | logsBucket: gs://opentelemetry-ops-e2e-cloud-build-logs 28 | substitutions: 29 | _TEST_SERVER_IMAGE: ${_TEST_SERVER_IMAGE_NAME}:${SHORT_SHA} 30 | _TEST_SERVER_IMAGE_NAME: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-java-e2e-test-server 31 | -------------------------------------------------------------------------------- /cloudbuild-e2e-local.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | steps: 15 | # Wait for the image to exist 16 | - name: "docker" 17 | id: wait-for-image 18 | entrypoint: "sh" 19 | timeout: 3m 20 | env: ["_TEST_SERVER_IMAGE=${_TEST_SERVER_IMAGE}"] 21 | args: 22 | - e2e-test-server/wait-for-image.sh 23 | 24 | - name: "docker" 25 | id: pull-image 26 | args: 27 | - pull 28 | - $_TEST_SERVER_IMAGE 29 | 30 | # Run the test 31 | - name: $_TEST_RUNNER_IMAGE 32 | id: run-tests-local 33 | dir: / 34 | env: ["PROJECT_ID=$PROJECT_ID"] 35 | args: 36 | - local 37 | - --image=$_TEST_SERVER_IMAGE 38 | - --network=cloudbuild 39 | 40 | logsBucket: gs://opentelemetry-ops-e2e-cloud-build-logs 41 | substitutions: 42 | _TEST_RUNNER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-e2e-testing:0.20.1 43 | _TEST_SERVER_IMAGE: us-central1-docker.pkg.dev/${PROJECT_ID}/e2e-testing/opentelemetry-operations-java-e2e-test-server:${SHORT_SHA} 44 | -------------------------------------------------------------------------------- /detectors/resources-support/README.md: -------------------------------------------------------------------------------- 1 | # GCP Resource Detection Support Library 2 | 3 | [![Maven Central][maven-image]][maven-url] 4 | 5 | This library provides detection support for supported GCP environments and is intended to be consumed by the [GCP OpenTelemetry Detector](https://github.com/open-telemetry/opentelemetry-java-contrib/tree/eece7e8ef04170fb463ddf692f61d4527b50febf/gcp-resources). 6 | The GCP environments supported by this library are - 7 | 1. [Google Compute Engine](https://cloud.google.com/compute?hl=en) 8 | 2. [Google Kubernetes Engine](https://cloud.google.com/kubernetes-engine?hl=en) 9 | 3. [Google App Engine](https://cloud.google.com/appengine?hl=en) 10 | 4. [Google Cloud Functions](https://cloud.google.com/functions?hl=en) 11 | 5. [Google Cloud Run](https://cloud.google.com/run?hl=en) 12 | 13 | [maven-image]: https://img.shields.io/maven-central/v/com.google.cloud.opentelemetry/detector-resources-support?color=dark-green 14 | [maven-url]: https://central.sonatype.com/artifact/com.google.cloud.opentelemetry/detector-resources-support 15 | -------------------------------------------------------------------------------- /detectors/resources-support/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 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 | description = 'Support library for Google Cloud Resource Detector' 17 | 18 | dependencies { 19 | testImplementation(testLibraries.assertj) 20 | testImplementation(testLibraries.wiremock) 21 | testImplementation(testLibraries.mockito) 22 | testImplementation(testLibraries.junit5) 23 | testImplementation(testLibraries.junit5_params) 24 | testRuntimeOnly(testLibraries.junit5_runtime) 25 | } 26 | 27 | test { 28 | // required for discovering JUnit 5 tests 29 | useJUnitPlatform() 30 | } 31 | -------------------------------------------------------------------------------- /detectors/resources-support/gradle.properties: -------------------------------------------------------------------------------- 1 | release.enabled=true 2 | -------------------------------------------------------------------------------- /detectors/resources-support/src/main/java/com/google/cloud/opentelemetry/detection/DetectedPlatform.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.detection; 17 | 18 | import java.util.Map; 19 | 20 | /** Represents a GCP specific platform on which a cloud application can run. */ 21 | public interface DetectedPlatform { 22 | /** 23 | * Method to retrieve the underlying compute platform on which application is running. 24 | * 25 | * @return the {@link GCPPlatformDetector.SupportedPlatform} representing the Google Cloud 26 | * platform on which application is running. 27 | */ 28 | GCPPlatformDetector.SupportedPlatform getSupportedPlatform(); 29 | 30 | /** 31 | * Method to retrieve the GCP Project ID in which the GCP specific platform exists. Every valid 32 | * platform must have a GCP Project ID associated with it. 33 | * 34 | * @return the Google Cloud project ID. 35 | */ 36 | String getProjectId(); 37 | 38 | /** 39 | * Method to retrieve the attributes associated with the compute platform on which the application 40 | * is running as key-value pairs. The valid keys to query on this {@link Map} are specified in the 41 | * {@link AttributeKeys}. 42 | * 43 | * @return a {@link Map} of attributes specific to the underlying compute platform. 44 | */ 45 | Map getAttributes(); 46 | } 47 | -------------------------------------------------------------------------------- /detectors/resources-support/src/main/java/com/google/cloud/opentelemetry/detection/EnvironmentVariables.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.detection; 17 | 18 | /** 19 | * Provides API to fetch environment variables. This is useful in order to create a mock class for 20 | * testing. 21 | */ 22 | interface EnvironmentVariables { 23 | /** Returns the current environment variables of the platform this is running in. */ 24 | EnvironmentVariables DEFAULT_INSTANCE = System::getenv; 25 | 26 | /** 27 | * Grabs the system environment variable. Returns null on failure. 28 | * 29 | * @param key the key of the environment variable in {@code System.getenv()} 30 | * @return the value received by {@code System.getenv(key)} 31 | */ 32 | String get(String key); 33 | } 34 | -------------------------------------------------------------------------------- /detectors/resources-support/src/main/java/com/google/cloud/opentelemetry/detection/GoogleCloudFunction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.detection; 17 | 18 | class GoogleCloudFunction extends GoogleServerlessCompute { 19 | GoogleCloudFunction(EnvironmentVariables environmentVariables, GCPMetadataConfig metadataConfig) { 20 | super(environmentVariables, metadataConfig); 21 | } 22 | 23 | @Override 24 | public GCPPlatformDetector.SupportedPlatform getSupportedPlatform() { 25 | return GCPPlatformDetector.SupportedPlatform.GOOGLE_CLOUD_FUNCTIONS; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /detectors/resources-support/src/main/java/com/google/cloud/opentelemetry/detection/GoogleCloudRun.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.detection; 17 | 18 | class GoogleCloudRun extends GoogleServerlessCompute { 19 | GoogleCloudRun(EnvironmentVariables environmentVariables, GCPMetadataConfig metadataConfig) { 20 | super(environmentVariables, metadataConfig); 21 | } 22 | 23 | @Override 24 | public GCPPlatformDetector.SupportedPlatform getSupportedPlatform() { 25 | return GCPPlatformDetector.SupportedPlatform.GOOGLE_CLOUD_RUN; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /detectors/resources-support/src/main/java/com/google/cloud/opentelemetry/detection/GoogleCloudRunJob.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.detection; 17 | 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | 21 | final class GoogleCloudRunJob implements DetectedPlatform { 22 | private final GCPMetadataConfig metadataConfig; 23 | private final EnvironmentVariables environmentVariables; 24 | private final Map availableAttributes; 25 | 26 | GoogleCloudRunJob(EnvironmentVariables environmentVariables, GCPMetadataConfig metadataConfig) { 27 | this.metadataConfig = metadataConfig; 28 | this.environmentVariables = environmentVariables; 29 | this.availableAttributes = prepareAttributes(); 30 | } 31 | 32 | private Map prepareAttributes() { 33 | Map map = new HashMap<>(); 34 | map.put(AttributeKeys.SERVERLESS_COMPUTE_NAME, this.environmentVariables.get("CLOUD_RUN_JOB")); 35 | map.put( 36 | AttributeKeys.GCR_JOB_EXECUTION_KEY, this.environmentVariables.get("CLOUD_RUN_EXECUTION")); 37 | map.put( 38 | AttributeKeys.GCR_JOB_TASK_INDEX, this.environmentVariables.get("CLOUD_RUN_TASK_INDEX")); 39 | map.put(AttributeKeys.SERVERLESS_COMPUTE_INSTANCE_ID, this.metadataConfig.getInstanceId()); 40 | map.put(AttributeKeys.SERVERLESS_COMPUTE_CLOUD_REGION, this.metadataConfig.getRegionFromZone()); 41 | return map; 42 | } 43 | 44 | @Override 45 | public GCPPlatformDetector.SupportedPlatform getSupportedPlatform() { 46 | return GCPPlatformDetector.SupportedPlatform.GOOGLE_CLOUD_RUN_JOB; 47 | } 48 | 49 | @Override 50 | public String getProjectId() { 51 | return metadataConfig.getProjectId(); 52 | } 53 | 54 | @Override 55 | public Map getAttributes() { 56 | return this.availableAttributes; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /detectors/resources-support/src/main/java/com/google/cloud/opentelemetry/detection/GoogleComputeEngine.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.detection; 17 | 18 | import static com.google.cloud.opentelemetry.detection.AttributeKeys.GCE_AVAILABILITY_ZONE; 19 | import static com.google.cloud.opentelemetry.detection.AttributeKeys.GCE_CLOUD_REGION; 20 | import static com.google.cloud.opentelemetry.detection.AttributeKeys.GCE_INSTANCE_HOSTNAME; 21 | import static com.google.cloud.opentelemetry.detection.AttributeKeys.GCE_INSTANCE_ID; 22 | import static com.google.cloud.opentelemetry.detection.AttributeKeys.GCE_INSTANCE_NAME; 23 | import static com.google.cloud.opentelemetry.detection.AttributeKeys.GCE_MACHINE_TYPE; 24 | 25 | import java.util.Collections; 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | 29 | final class GoogleComputeEngine implements DetectedPlatform { 30 | private final GCPMetadataConfig metadataConfig; 31 | private final Map availableAttributes; 32 | 33 | GoogleComputeEngine(GCPMetadataConfig metadataConfig) { 34 | this.metadataConfig = metadataConfig; 35 | this.availableAttributes = prepareAttributes(); 36 | } 37 | 38 | private Map prepareAttributes() { 39 | Map map = new HashMap<>(); 40 | map.put(GCE_AVAILABILITY_ZONE, this.metadataConfig.getZone()); 41 | map.put(GCE_CLOUD_REGION, this.metadataConfig.getRegionFromZone()); 42 | map.put(GCE_INSTANCE_ID, this.metadataConfig.getInstanceId()); 43 | map.put(GCE_INSTANCE_NAME, this.metadataConfig.getInstanceName()); 44 | map.put(GCE_INSTANCE_HOSTNAME, this.metadataConfig.getInstanceHostName()); 45 | map.put(GCE_MACHINE_TYPE, this.metadataConfig.getMachineType()); 46 | return Collections.unmodifiableMap(map); 47 | } 48 | 49 | @Override 50 | public GCPPlatformDetector.SupportedPlatform getSupportedPlatform() { 51 | return GCPPlatformDetector.SupportedPlatform.GOOGLE_COMPUTE_ENGINE; 52 | } 53 | 54 | @Override 55 | public String getProjectId() { 56 | return this.metadataConfig.getProjectId(); 57 | } 58 | 59 | @Override 60 | public Map getAttributes() { 61 | return this.availableAttributes; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /detectors/resources-support/src/main/java/com/google/cloud/opentelemetry/detection/GoogleServerlessCompute.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.detection; 17 | 18 | import java.util.Collections; 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | /** 23 | * GoogleServerlessCompute adds attributes applicable to all serverless compute platforms in GCP. 24 | * Currently, this includes Google Cloud Functions & Google Cloud Run. 25 | */ 26 | abstract class GoogleServerlessCompute implements DetectedPlatform { 27 | private final EnvironmentVariables environmentVariables; 28 | private final GCPMetadataConfig metadataConfig; 29 | private final Map availableAttributes; 30 | 31 | GoogleServerlessCompute( 32 | EnvironmentVariables environmentVariables, GCPMetadataConfig metadataConfig) { 33 | this.environmentVariables = environmentVariables; 34 | this.metadataConfig = metadataConfig; 35 | this.availableAttributes = prepareAttributes(); 36 | } 37 | 38 | private Map prepareAttributes() { 39 | Map map = new HashMap<>(); 40 | map.put(AttributeKeys.SERVERLESS_COMPUTE_NAME, this.environmentVariables.get("K_SERVICE")); 41 | map.put(AttributeKeys.SERVERLESS_COMPUTE_REVISION, this.environmentVariables.get("K_REVISION")); 42 | map.put(AttributeKeys.SERVERLESS_COMPUTE_AVAILABILITY_ZONE, this.metadataConfig.getZone()); 43 | map.put(AttributeKeys.SERVERLESS_COMPUTE_CLOUD_REGION, this.metadataConfig.getRegionFromZone()); 44 | map.put(AttributeKeys.SERVERLESS_COMPUTE_INSTANCE_ID, this.metadataConfig.getInstanceId()); 45 | return Collections.unmodifiableMap(map); 46 | } 47 | 48 | @Override 49 | public String getProjectId() { 50 | return this.metadataConfig.getProjectId(); 51 | } 52 | 53 | @Override 54 | public Map getAttributes() { 55 | return this.availableAttributes; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /detectors/resources-support/src/main/java/com/google/cloud/opentelemetry/detection/UnknownPlatform.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.detection; 17 | 18 | import java.util.Collections; 19 | import java.util.Map; 20 | 21 | class UnknownPlatform implements DetectedPlatform { 22 | 23 | UnknownPlatform() {} 24 | 25 | @Override 26 | public GCPPlatformDetector.SupportedPlatform getSupportedPlatform() { 27 | return GCPPlatformDetector.SupportedPlatform.UNKNOWN_PLATFORM; 28 | } 29 | 30 | @Override 31 | public String getProjectId() { 32 | return ""; 33 | } 34 | 35 | @Override 36 | public Map getAttributes() { 37 | return Collections.emptyMap(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /detectors/resources-support/src/test/java/com/google/cloud/opentelemetry/detection/EnvVarMock.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.detection; 17 | 18 | import java.util.Map; 19 | 20 | class EnvVarMock implements EnvironmentVariables { 21 | private final Map mock; 22 | 23 | public EnvVarMock(Map mock) { 24 | this.mock = mock; 25 | } 26 | 27 | @Override 28 | public String get(String key) { 29 | return mock.get(key); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /detectors/resources-support/src/test/java/com/google/cloud/opentelemetry/detection/TestUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.detection; 17 | 18 | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; 19 | import static com.github.tomakehurst.wiremock.client.WireMock.get; 20 | import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; 21 | import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; 22 | 23 | public final class TestUtils { 24 | // Helper method to help stub endpoints 25 | public static void stubEndpoint(String endpointPath, String responseBody) { 26 | stubFor( 27 | get(urlEqualTo(endpointPath)) 28 | .willReturn( 29 | aResponse().withHeader("Metadata-Flavor", "Google").withBody(responseBody))); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /docs/contributing.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution; 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows [Google's Open Source Community 28 | Guidelines](https://opensource.google/conduct/). 29 | -------------------------------------------------------------------------------- /e2e-test-server/README.md: -------------------------------------------------------------------------------- 1 | # End to End tests 2 | 3 | > [!NOTE] 4 | > This module requires at least Java 11 to run. 5 | 6 | A set of end to end integration tests. These are run inside various environments to ensure 7 | GCP automagiks work and data flows into google cloud. 8 | 9 | 10 | ## Building a Docker image. 11 | 12 | From the *root* directory of the project, run: 13 | 14 | ``` 15 | docker build . --file=e2e.Dockerfile 16 | ``` 17 | -------------------------------------------------------------------------------- /e2e-test-server/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | plugins { 17 | id 'java' 18 | id 'application' 19 | id 'com.github.johnrengelman.shadow' 20 | } 21 | 22 | application { 23 | mainClass.set('com.google.cloud.opentelemetry.endtoend.Server') 24 | } 25 | 26 | // Java 11 required to build this module since it has a dependency on Cloud Functions. 27 | // Cloud Functions (Gen2) have Java 11 minimum requirement. 28 | compileJava{ 29 | // This is only possible since the toolchain guarantees Java 11 presence. 30 | // Toolchain is set in the root build.gradle file. 31 | it.options.release = 11 32 | } 33 | 34 | description = 'End-To-End integration testing server' 35 | 36 | shadowJar { 37 | mergeServiceFiles() 38 | } 39 | 40 | dependencies { 41 | implementation(libraries.opentelemetry_sdk_autoconf) 42 | implementation(libraries.opentelemetry_api) 43 | implementation(libraries.opentelemetry_sdk) 44 | implementation(libraries.google_cloud_trace) 45 | implementation(libraries.google_cloud_pubsub) 46 | implementation(libraries.google_cloud_functions_framework) 47 | implementation(libraries.cloudevents_core) 48 | implementation(libraries.opentelemetry_gcp_resources) 49 | implementation platform(libraries.google_cloud_bom) 50 | implementation platform(libraries.opentelemetry_bom) 51 | implementation project(':exporter-trace') 52 | implementation project(':propagators-gcp') 53 | } 54 | 55 | tasks.build.dependsOn tasks.shadowJar 56 | -------------------------------------------------------------------------------- /e2e-test-server/gradle.properties: -------------------------------------------------------------------------------- 1 | release.enabled=false 2 | -------------------------------------------------------------------------------- /e2e-test-server/src/main/java/com/google/cloud/opentelemetry/endtoend/CloudFunctionHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.endtoend; 17 | 18 | import com.google.cloud.functions.CloudEventsFunction; 19 | import com.google.gson.Gson; 20 | import com.google.gson.JsonElement; 21 | import com.google.gson.JsonParser; 22 | import com.google.pubsub.v1.PubsubMessage; 23 | import io.cloudevents.CloudEvent; 24 | import java.nio.charset.StandardCharsets; 25 | import java.util.Objects; 26 | 27 | /** 28 | * This class serves as an entrypoint for Google Cloud Function entrypoint. This entrypoint works 29 | * for 2nd gen functions that have event-based triggers. 30 | */ 31 | public class CloudFunctionHandler implements CloudEventsFunction { 32 | 33 | /** 34 | * Called to service an incoming event. This interface is implemented by user code to provide the 35 | * action for a given background function. If this method throws any exception (including any 36 | * {@link Error}) then the HTTP response will have a 500 status code. 37 | * 38 | * @param event the event. 39 | */ 40 | @Override 41 | public void accept(CloudEvent event) { 42 | // The Pub/Sub message is passed as the CloudEvent's data payload. 43 | if (event.getData() != null) { 44 | PubsubMessage message = getDecodedMessage(event); 45 | Server server; 46 | try { 47 | server = new Server(); 48 | server.handlePubSubMessage(message); 49 | } catch (Exception e) { 50 | e.printStackTrace(); 51 | } 52 | } 53 | } 54 | 55 | private PubsubMessage getDecodedMessage(CloudEvent event) { 56 | String cloudEventData = 57 | new String(Objects.requireNonNull(event.getData()).toBytes(), StandardCharsets.UTF_8); 58 | Gson gson = new Gson(); 59 | JsonElement jsonRoot = JsonParser.parseString(cloudEventData); 60 | System.out.println("Parsed JSON is " + jsonRoot.toString()); 61 | String msgStr = jsonRoot.getAsJsonObject().get("message").toString(); 62 | System.out.println("Message String is " + msgStr); 63 | PubSubPushServer.Message message = gson.fromJson(msgStr, PubSubPushServer.Message.class); 64 | return PubsubMessage.newBuilder().putAllAttributes(message.getAttributes()).build(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /e2e-test-server/src/main/java/com/google/cloud/opentelemetry/endtoend/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.endtoend; 17 | 18 | import com.google.pubsub.v1.ProjectSubscriptionName; 19 | import com.google.pubsub.v1.ProjectTopicName; 20 | 21 | /** Constants we use in this test. Note: Some are pulled from the env. */ 22 | public class Constants { 23 | 24 | public static final String INSTRUMENTING_MODULE_NAME = "opentelemetry-ops-e2e-test-server"; 25 | public static final String SCENARIO = "scenario"; 26 | public static final String STATUS_CODE = "status_code"; 27 | public static final String TEST_ID = "test_id"; 28 | public static final String TRACE_ID = "trace_id"; 29 | public static final String SUBSCRIPTION_MODE_PUSH = "push"; 30 | public static final String SUBSCRIPTION_MODE_PULL = "pull"; 31 | 32 | // TODO: Add good error messages below. 33 | public static String SUBSCRIPTION_MODE = System.getenv().getOrDefault("SUBSCRIPTION_MODE", ""); 34 | public static String PROJECT_ID = System.getenv().getOrDefault("PROJECT_ID", ""); 35 | public static String REQUEST_SUBSCRIPTION_NAME = 36 | System.getenv().getOrDefault("REQUEST_SUBSCRIPTION_NAME", ""); 37 | public static String RESPONSE_TOPIC_NAME = 38 | System.getenv().getOrDefault("RESPONSE_TOPIC_NAME", ""); 39 | public static String PUSH_PORT = System.getenv().getOrDefault("PUSH_PORT", ""); 40 | 41 | public static ProjectSubscriptionName getRequestSubscription() { 42 | return ProjectSubscriptionName.of(PROJECT_ID, REQUEST_SUBSCRIPTION_NAME); 43 | } 44 | 45 | /** @return The pubsub channel we get test requests from. */ 46 | public static ProjectTopicName getResponseTopic() { 47 | return ProjectTopicName.of(PROJECT_ID, RESPONSE_TOPIC_NAME); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /e2e-test-server/src/main/java/com/google/cloud/opentelemetry/endtoend/PubSubMessageHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.endtoend; 17 | 18 | import com.google.pubsub.v1.PubsubMessage; 19 | 20 | /** 21 | * An interface containing functionality to handle an incoming {@link PubsubMessage} and returning 22 | * appropriate response indicating if handling was successful or not. 23 | */ 24 | public interface PubSubMessageHandler { 25 | 26 | /** 27 | * Represents the possible responses for handling an incoming {@link PubsubMessage} handled via 28 | * PubSubMessageHandler. 29 | */ 30 | enum PubSubMessageResponse { 31 | /** 32 | * Response that should be sent when a {@link PubsubMessage} has been successfully processed. 33 | * The service should not send the message again. 34 | */ 35 | ACK("ack"), 36 | 37 | /** 38 | * Response that should be sent when a {@link PubsubMessage} has not been successfully 39 | * processed. The service should resend the message. 40 | */ 41 | NACK("nack"); 42 | 43 | private final String stringValue; 44 | 45 | /** 46 | * Constructor for the {@link PubSubMessageResponse}. 47 | * 48 | * @param stringValue the string representation for the enum value. 49 | */ 50 | PubSubMessageResponse(String stringValue) { 51 | this.stringValue = stringValue; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return this.stringValue; 57 | } 58 | } 59 | 60 | /** 61 | * This method accepts and processes an incoming {@link PubsubMessage}. 62 | * 63 | * @param message The incoming {@link PubsubMessage} that should be processed. 64 | * @return a {@link PubSubMessageResponse} indicating if the message was processed successfully. 65 | */ 66 | PubSubMessageResponse handlePubSubMessage(PubsubMessage message); 67 | 68 | /** 69 | * This method is responsible for doing any cleanup tasks required for the {@link 70 | * PubSubMessageHandler} when handler is no longer required. 71 | */ 72 | void cleanupMessageHandler(); 73 | } 74 | -------------------------------------------------------------------------------- /e2e-test-server/src/main/java/com/google/cloud/opentelemetry/endtoend/PubSubServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.endtoend; 17 | 18 | /** 19 | * Interface that represents a server program capable of processing {@link 20 | * com.google.pubsub.v1.PubsubMessage}s. 21 | */ 22 | public interface PubSubServer extends AutoCloseable { 23 | /** 24 | * Method responsible for starting the server. Once the server is 'started', it should begin 25 | * listening/processing requests. 26 | */ 27 | void start(); 28 | } 29 | -------------------------------------------------------------------------------- /e2e-test-server/src/main/java/com/google/cloud/opentelemetry/endtoend/Request.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.endtoend; 17 | 18 | import com.google.protobuf.ByteString; 19 | import java.util.Map; 20 | 21 | /** Abstraction of an "RPC Request" in our e2e integration test. */ 22 | public interface Request { 23 | /** The test scenario requested. */ 24 | String testId(); 25 | 26 | /** Text map headers (for eventual trace propagation). */ 27 | Map headers(); 28 | 29 | /** Incoming message data. */ 30 | ByteString data(); 31 | 32 | static Request make( 33 | final String testId, final Map headers, final ByteString data) { 34 | return new Request() { 35 | public String testId() { 36 | return testId; 37 | } 38 | 39 | public Map headers() { 40 | return headers; 41 | } 42 | 43 | public ByteString data() { 44 | return data; 45 | } 46 | }; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /e2e-test-server/src/main/java/com/google/cloud/opentelemetry/endtoend/Response.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.endtoend; 17 | 18 | import com.google.api.gax.rpc.StatusCode.Code; 19 | import com.google.protobuf.ByteString; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | /** 24 | * An "RPC Response", generified. 25 | * 26 | *

This class exposes the minimum API to write rpc-like integration tests. 27 | */ 28 | public interface Response { 29 | /** 30 | * Status code associate with response. 31 | * 32 | *

If this is `OK`, then data will be empty. 33 | */ 34 | Code statusCode(); 35 | 36 | /** string explanation of error codes. */ 37 | ByteString data(); 38 | 39 | Map headers(); 40 | 41 | static Response make(final Code code, final ByteString data) { 42 | return make(code, data, new HashMap<>()); 43 | } 44 | 45 | static Response make(final Code code, final ByteString data, final Map headers) { 46 | return new Response() { 47 | public Code statusCode() { 48 | return code; 49 | } 50 | 51 | public ByteString data() { 52 | return data; 53 | } 54 | 55 | public Map headers() { 56 | return headers; 57 | } 58 | }; 59 | } 60 | 61 | public static Response internalError(Throwable t) { 62 | return make(Code.INTERNAL, ByteString.copyFromUtf8(t.toString())); 63 | } 64 | 65 | public static Response invalidArgument(String message) { 66 | return make(Code.INVALID_ARGUMENT, ByteString.copyFromUtf8(message)); 67 | } 68 | 69 | public static Response unimplemented(String message) { 70 | return make(Code.UNIMPLEMENTED, ByteString.copyFromUtf8(message)); 71 | } 72 | 73 | public static Response ok() { 74 | return make(Code.OK, ByteString.EMPTY); 75 | } 76 | 77 | public static Response ok(Map headers) { 78 | return make(Code.OK, ByteString.EMPTY, headers); 79 | } 80 | 81 | public static Response EMPTY = make(Code.UNKNOWN, ByteString.EMPTY); 82 | } 83 | -------------------------------------------------------------------------------- /e2e-test-server/src/main/java/com/google/cloud/opentelemetry/endtoend/ScenarioHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.endtoend; 17 | 18 | /** A handler for testing scenarios. */ 19 | public interface ScenarioHandler { 20 | /** Handles a given tracing scenario request. Failures should be thrown. */ 21 | public Response handle(Request request); 22 | } 23 | -------------------------------------------------------------------------------- /e2e-test-server/wait-for-image.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Copyright 2023 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | while true; do 18 | if docker manifest inspect ${_TEST_SERVER_IMAGE} > /dev/null; then 19 | echo "Image is available, continuing onto test" 20 | break 21 | else 22 | echo "Image not available yet, will continue to retry" 23 | fi 24 | sleep 5 25 | done 26 | -------------------------------------------------------------------------------- /e2e.Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # Build relative to root of repository i.e. `docker build --file e2e.Dockerfile --tag=$tag ..` 16 | FROM gradle:8.0.2-jdk11 as builder 17 | 18 | COPY --chown=gradle:gradle . /app/src 19 | WORKDIR /app/src 20 | RUN gradle :e2e-test-server:build 21 | 22 | FROM openjdk:11-jre-slim 23 | COPY --from=builder /app/src/e2e-test-server/build/libs/*-all.jar /app/app.jar 24 | WORKDIR /app 25 | CMD java -jar app.jar 26 | -------------------------------------------------------------------------------- /examples/autoconf/README.md: -------------------------------------------------------------------------------- 1 | # Autoconfiguration Example 2 | 3 | An example application that sends custom traces+metric using *only* the OpenTelemetry API. All SDK configuration is done using the autoconfiguration module. 4 | 5 | ### Prerequisites 6 | 7 | ##### Get Google Cloud Credentials on your machine 8 | 9 | ```shell 10 | gcloud auth application-default login 11 | ``` 12 | Executing this command will save your application credentials to default path which will depend on the type of machine - 13 | - Linux, macOS: `$HOME/.config/gcloud/application_default_credentials.json` 14 | - Windows: `%APPDATA%\gcloud\application_default_credentials.json` 15 | 16 | **NOTE: This method of authentication is not recommended for production environments.** 17 | 18 | Next, export the credentials to `GOOGLE_APPLICATION_CREDENTIALS` environment variable - 19 | 20 | For Linux & MacOS: 21 | ```shell 22 | export GOOGLE_APPLICATION_CREDENTIALS=$HOME/.config/gcloud/application_default_credentials.json 23 | ``` 24 | 25 | For Windows: 26 | ```shell 27 | SET GOOGLE_APPLICATION_CREDENTIALS=%APPDATA%\gcloud\application_default_credentials.json 28 | ``` 29 | 30 | ##### Export the Google Cloud Project ID to `GOOGLE_CLOUD_PROJECT` environment variable: 31 | 32 | ```shell 33 | export GOOGLE_CLOUD_PROJECT="my-awesome-gcp-project-id" 34 | ``` 35 | 36 | ## Running in Google Kubernetes Engine 37 | 38 | To spin it up on your own GKE cluster, run the following: 39 | ``` 40 | ./gradlew :examples-autoconf:jib --image="gcr.io/$GOOGLE_CLOUD_PROJECT/hello-autoconfigure-java" 41 | 42 | sed s/%GOOGLE_CLOUD_PROJECT%/$GOOGLE_CLOUD_PROJECT/g \ 43 | examples/autoconf/job.yaml | kubectl apply -f - 44 | ``` 45 | 46 | This will run a batch job which synthesizes a nested trace, latency metrics and exemplars. 47 | 48 | ## Running locally on your machine 49 | 50 | In case you do not want to spin up your own GKE cluster, but still want telemetry to be published to Google Cloud, you can run the example locally. 51 | 52 | From the root of the repository, 53 | ```shell 54 | cd examples/autoconf && gradle run 55 | ``` 56 | 57 | This will run the sample app locally on your machine, synthesizing a nested trace, latency metrics and exemplars. 58 | -------------------------------------------------------------------------------- /examples/autoconf/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | plugins { 17 | id 'java' 18 | id 'application' 19 | id 'com.google.cloud.tools.jib' 20 | } 21 | 22 | description = 'Examples for using java autoconfiguration and Google Cloud Operations' 23 | 24 | // examples are not published, so version can be hardcoded 25 | version = '0.1.0' 26 | 27 | dependencies { 28 | implementation(libraries.opentelemetry_api) 29 | implementation(libraries.opentelemetry_sdk_metrics) 30 | implementation(libraries.opentelemetry_sdk_autoconf) 31 | implementation(libraries.opentelemetry_sdk) 32 | runtimeOnly project(':exporter-auto') 33 | // Provides resources to the autoconfiguration module 34 | runtimeOnly(libraries.opentelemetry_gcp_resources) 35 | } 36 | 37 | // Autoconfiguraation settings. 38 | // See: https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure 39 | def autoconf_config = [ 40 | '-Dotel.traces.exporter=google_cloud_trace', 41 | '-Dotel.metrics.exporter=google_cloud_monitoring', 42 | '-Dotel.logs.exporter=none', 43 | '-Dotel.java.global-autoconfigure.enabled=true', 44 | '-Dotel.service.name=example-autoconf-service', 45 | ] 46 | 47 | application { 48 | applicationDefaultJvmArgs = autoconf_config 49 | mainClassName = 'com.google.cloud.opentelemetry.example.autoconf.AutoconfExample' 50 | } 51 | 52 | 53 | jib { 54 | from.image = 'gcr.io/distroless/java-debian10:11' 55 | containerizingMode = 'packaged' 56 | container.jvmFlags = autoconf_config 57 | } -------------------------------------------------------------------------------- /examples/autoconf/job.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | apiVersion: batch/v1 15 | kind: Job 16 | metadata: 17 | # Unique key of the Job instance 18 | name: hello-autoconfigure-java 19 | spec: 20 | template: 21 | metadata: 22 | name: hello-autoconfigure-java 23 | spec: 24 | containers: 25 | - name: hello-autoconfigure-java 26 | image: gcr.io/%GOOGLE_CLOUD_PROJECT%/hello-autoconfigure-java:latest 27 | env: 28 | - name: NAMESPACE 29 | valueFrom: 30 | fieldRef: 31 | fieldPath: metadata.namespace 32 | - name: CONTAINER_NAME 33 | valueFrom: 34 | fieldRef: 35 | fieldPath: metadata.name 36 | 37 | # Do not restart containers after they exit 38 | restartPolicy: Never 39 | # of retries before marking as failed. 40 | backoffLimit: 4 -------------------------------------------------------------------------------- /examples/autoinstrument/deployment.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | apiVersion: apps/v1 15 | kind: Deployment 16 | metadata: 17 | name: hello-autoinstrument-java 18 | namespace: default 19 | labels: 20 | app: hello-autoinstrument-java 21 | spec: 22 | selector: 23 | matchLabels: 24 | app: hello-autoinstrument-java 25 | template: 26 | metadata: 27 | labels: 28 | app: hello-autoinstrument-java 29 | spec: 30 | containers: 31 | - name: hello-autoinstrument-java 32 | image: us-central1-docker.pkg.dev/%GOOGLE_CLOUD_PROJECT%/opentelemetry-sample-apps/hello-autoinstrument-java:latest 33 | # required for resource detection in GKE environment 34 | env: 35 | - name: GOOGLE_CLOUD_PROJECT 36 | value: %GOOGLE_CLOUD_PROJECT% 37 | - name: POD_NAME 38 | valueFrom: 39 | fieldRef: 40 | fieldPath: metadata.name 41 | - name: NAMESPACE_NAME 42 | valueFrom: 43 | fieldRef: 44 | fieldPath: metadata.namespace 45 | - name: CONTAINER_NAME 46 | value: hello-autoinstrument-java 47 | - name: OTEL_RESOURCE_ATTRIBUTES 48 | value: k8s.pod.name=$(POD_NAME),k8s.namespace.name=$(NAMESPACE_NAME),k8s.container.name=$(CONTAINER_NAME) 49 | -------------------------------------------------------------------------------- /examples/autoinstrument/run_in_cloud-run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright 2023 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | CONTAINER_REGISTRY=opentelemetry-sample-apps 18 | REGISTRY_LOCATION=us-central1 19 | IMAGE_NAME="${REGISTRY_LOCATION}-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/${CONTAINER_REGISTRY}/hello-autoinstrument-java" 20 | 21 | if [[ -z "${GOOGLE_CLOUD_PROJECT}" ]]; then 22 | echo "GOOGLE_CLOUD_PROJECT environment variable not set" 23 | exit 1 24 | fi 25 | 26 | if [[ -z "${GOOGLE_APPLICATION_CREDENTIALS}" ]]; then 27 | echo "GOOGLE_APPLICATION_CREDENTIALS environment variable not set" 28 | exit 1 29 | fi 30 | 31 | if [[ -z "${GOOGLE_CLOUD_RUN_REGION}" ]]; then 32 | echo "GOOGLE_CLOUD_RUN_REGION environment variable not set" 33 | exit 1 34 | fi 35 | 36 | echo "ENVIRONMENT VARIABLES VERIFIED" 37 | 38 | echo "CREATING CLOUD ARTIFACT REPOSITORY" 39 | gcloud artifacts repositories create ${CONTAINER_REGISTRY} --repository-format=docker --location=${REGISTRY_LOCATION} --description="OpenTelemetry auto-instrumentation sample applications" 40 | echo "CREATED ${CONTAINER_REGISTRY} in ${REGISTRY_LOCATION}" 41 | 42 | echo "BUILDING SAMPLE APP IMAGE" 43 | gradle clean jib --image "${IMAGE_NAME}" 44 | 45 | echo "RUNNING SAMPLE APP ON PORT 8080" 46 | # We use --no-cpu-throttling for the sample to ensure that traces can be exported in the background. 47 | # See https://cloud.google.com/sdk/gcloud/reference/run/deploy#--[no-]cpu-throttling for details. 48 | gcloud run deploy hello-autoinstrument-cloud-run \ 49 | --set-env-vars="GOOGLE_CLOUD_PROJECT=${GOOGLE_CLOUD_PROJECT}" \ 50 | --image="${IMAGE_NAME}" \ 51 | --region="${GOOGLE_CLOUD_RUN_REGION}" \ 52 | --no-cpu-throttling 53 | -------------------------------------------------------------------------------- /examples/autoinstrument/run_in_docker.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright 2023 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | if [[ -z "${GOOGLE_CLOUD_PROJECT}" ]]; then 18 | echo "GOOGLE_CLOUD_PROJECT environment variable not set" 19 | exit 1 20 | fi 21 | 22 | if [[ -z "${GOOGLE_APPLICATION_CREDENTIALS}" ]]; then 23 | echo "GOOGLE_APPLICATION_CREDENTIALS environment variable not set" 24 | exit 1 25 | fi 26 | echo "ENVIRONMENT VARIABLES VERIFIED" 27 | 28 | echo "BUILDING SAMPLE APP IMAGE" 29 | gradle clean jibDockerBuild --image "hello-autoinstrument-java-local:latest" 30 | 31 | 32 | echo "RUNNING SAMPLE APP ON PORT 8080" 33 | docker run \ 34 | --rm \ 35 | -e "GOOGLE_CLOUD_PROJECT=${GOOGLE_CLOUD_PROJECT}" \ 36 | -e "GOOGLE_APPLICATION_CREDENTIALS=${GOOGLE_APPLICATION_CREDENTIALS}" \ 37 | -v "${GOOGLE_APPLICATION_CREDENTIALS}:${GOOGLE_APPLICATION_CREDENTIALS}:ro" \ 38 | -p 8080:8080 \ 39 | "hello-autoinstrument-java-local:latest" 40 | -------------------------------------------------------------------------------- /examples/autoinstrument/src/main/java/com/google/example/CloudTraceLogAttacher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.example; 17 | 18 | import ch.qos.logback.classic.spi.ILoggingEvent; 19 | import ch.qos.logback.core.filter.Filter; 20 | import com.google.cloud.ServiceOptions; 21 | import io.opentelemetry.api.trace.Span; 22 | import io.opentelemetry.api.trace.SpanContext; 23 | import io.opentelemetry.context.Context; 24 | 25 | /** This is a "filter" for logback that simple appends opencensus trace context to the MDC. */ 26 | public class CloudTraceLogAttacher extends Filter { 27 | private static final String TRACE_ID = "gcp.trace_id"; 28 | private static final String SPAN_ID = "gcp.span_id"; 29 | private static final String SAMPLED = "gcp.trace_sampled"; 30 | 31 | private final String projectId; 32 | private final String tracePrefix; 33 | 34 | public CloudTraceLogAttacher() { 35 | this.projectId = lookUpProjectId(); 36 | this.tracePrefix = "projects/" + (projectId == null ? "" : projectId) + "/traces/"; 37 | } 38 | 39 | @Override 40 | public ch.qos.logback.core.spi.FilterReply decide( 41 | ch.qos.logback.classic.spi.ILoggingEvent event) { 42 | SpanContext context = Span.fromContext(Context.current()).getSpanContext(); 43 | if (context.isValid()) { 44 | org.slf4j.MDC.put(TRACE_ID, tracePrefix + context.getTraceId()); 45 | org.slf4j.MDC.put(SPAN_ID, context.getSpanId()); 46 | org.slf4j.MDC.put(SAMPLED, Boolean.toString(context.isSampled())); 47 | } 48 | return ch.qos.logback.core.spi.FilterReply.ACCEPT; 49 | } 50 | 51 | private static String lookUpProjectId() { 52 | return ServiceOptions.getDefaultProjectId(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /examples/autoinstrument/src/main/java/com/google/example/GreetingClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.example; 17 | 18 | import org.springframework.cloud.openfeign.FeignClient; 19 | import org.springframework.web.bind.annotation.GetMapping; 20 | 21 | @FeignClient(name = "greetingClient", url = "http://localhost:8080") 22 | interface GreetingClient { 23 | @GetMapping("/greeting") 24 | String greeting(); 25 | } 26 | -------------------------------------------------------------------------------- /examples/autoinstrument/src/main/java/com/google/example/TestMain.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.example; 17 | 18 | import java.io.IOException; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.boot.SpringApplication; 21 | import org.springframework.boot.autoconfigure.SpringBootApplication; 22 | import org.springframework.cloud.openfeign.EnableFeignClients; 23 | import org.springframework.web.bind.annotation.GetMapping; 24 | import org.springframework.web.bind.annotation.RestController; 25 | 26 | @EnableFeignClients 27 | @RestController 28 | @SpringBootApplication 29 | public class TestMain { 30 | @Autowired private GreetingClient greetingClient; 31 | 32 | public static void main(String[] args) throws IOException { 33 | SpringApplication.run(TestMain.class, args); 34 | } 35 | 36 | @GetMapping("/greeting") 37 | public String greeting() { 38 | return "Hello"; 39 | } 40 | 41 | @GetMapping("/") 42 | public String home() { 43 | return greetingClient.greeting() + " World"; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /examples/autoinstrument/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG 2 | spring.application.name=gcp-autoinstrument-spring-demo 3 | spring.main.banner-mode=off 4 | spring.sleuth.sampler.probability=1.0 5 | -------------------------------------------------------------------------------- /examples/autoinstrument/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | {"severity": "%-5p","message": "%logger:%L %m %ex", "sourceLocation": "%logger:%L", "request_id": "%X{request_id}", "logging.googleapis.com/trace": "%X{gcp.trace_id}", "logging.googleapis.com/spanId": "%X{gcp.span_id}", "logging.googleapis.com/trace_sampled" : "%X{gcp.trace_sampled}"}%n 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/.dockerignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### VS Code ### 21 | .vscode/ 22 | 23 | ### Docker ### 24 | Dockerfile 25 | docker-compose*.yaml 26 | otel-collector-config.yaml 27 | cloudbuild-integration.yaml 28 | 29 | integrationtest/ 30 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # Adapted from https://spring.io/guides/topicals/spring-boot-docker/#_multi_stage_build 16 | # syntax=docker/dockerfile:experimental 17 | FROM eclipse-temurin:17-jdk-alpine AS build 18 | WORKDIR /workspace/app 19 | 20 | COPY . /workspace/app 21 | RUN --mount=type=cache,target=/root/.gradle ./gradlew clean build 22 | RUN mkdir -p build/dependency && (cd build/dependency; jar -xf ../libs/*-SNAPSHOT.jar) 23 | 24 | FROM eclipse-temurin:17-jdk-alpine 25 | VOLUME /tmp 26 | ARG DEPENDENCY=/workspace/app/build/dependency 27 | COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib 28 | COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF 29 | COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app 30 | # [START opentelemetry_instrumentation_agent_dockerfile] 31 | RUN wget -O /opentelemetry-javaagent.jar https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/download/v1.31.0/opentelemetry-javaagent.jar 32 | CMD sh -c "java -javaagent:/opentelemetry-javaagent.jar -cp app:app/lib/* com.example.demo.DemoApplication \ 33 | 2>&1 | tee /var/log/app.log" 34 | # [END opentelemetry_instrumentation_agent_dockerfile] 35 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 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 | 17 | plugins { 18 | id 'java' 19 | id 'org.springframework.boot' version '2.7.18' 20 | id 'io.spring.dependency-management' version '1.1.4' 21 | id 'com.diffplug.spotless' version '6.25.0' 22 | } 23 | 24 | group = 'com.example' 25 | version = '0.0.1-SNAPSHOT' 26 | description = 'OpenTelemetry instrumentation quickstart using Spring Boot' 27 | 28 | repositories { 29 | mavenCentral() 30 | } 31 | 32 | spotless { 33 | java { 34 | googleJavaFormat("1.10.0") 35 | } 36 | groovyGradle { 37 | target '*.gradle' // default target of groovyGradle 38 | greclipse() 39 | } 40 | } 41 | 42 | dependencies { 43 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 44 | 45 | // Use log4j2 for logging 46 | // https://docs.spring.io/spring-boot/docs/2.7.18/reference/html/howto.html#howto.logging.log4j 47 | implementation "org.springframework.boot:spring-boot-starter-log4j2" 48 | modules { 49 | module("org.springframework.boot:spring-boot-starter-logging") { 50 | replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback") 51 | } 52 | } 53 | implementation "org.apache.logging.log4j:log4j-layout-template-json" 54 | 55 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 56 | testImplementation 'org.testcontainers:testcontainers:1.19.4' 57 | testImplementation 'com.google.truth:truth:1.4.0' 58 | testImplementation "org.testcontainers:junit-jupiter:1.19.4" 59 | } 60 | 61 | tasks.named('test') { 62 | useJUnitPlatform { 63 | // Individual integration tests are annotated with @Tag('integrationTest') 64 | excludeTags 'integrationTest' 65 | } 66 | } 67 | 68 | tasks.register("integrationTest", Test) { 69 | useJUnitPlatform { 70 | includeTags 'integrationTest' 71 | } 72 | 73 | // Passing -DcomposeOverrideFile=foo.yaml will merge docker-compose.yaml with foo.yaml. 74 | // This is used to set overrides for Cloud Build. 75 | if (System.getProperty('composeOverrideFile')) { 76 | systemProperty 'composeOverrideFile', System.getProperty('composeOverrideFile') 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/cloudbuild-integration.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | steps: 16 | - name: golang:1.23 17 | dir: examples/instrumentation-quickstart/integrationtest 18 | env: 19 | - COMPOSE_OVERRIDE_FILE=../docker-compose.cloudbuild.yaml 20 | # https://github.com/testcontainers/testcontainers-go/issues/2754 21 | - TESTCONTAINERS_RYUK_CONNECTION_TIMEOUT=10m 22 | - TESTCONTAINERS_RYUK_RECONNECTION_TIMEOUT=10m 23 | script: go test -v 24 | 25 | logsBucket: gs://opentelemetry-ops-e2e-cloud-build-logs 26 | options: 27 | machineType: E2_HIGHCPU_8 28 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/cloudbuild-uninstrumented-app.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # Configuration to build the un-instrumented version of this quickstart on 16 | # Google Cloud Build. Also pushes the built image to Google Artifact Registry. 17 | # REGISTRY_LOCATION, GOOGLE_CLOUD_PROJECT, ARTIFACT_REGISTRY environment variables must be 18 | # substituted in this file. 19 | # 20 | # Using gCloud CLI: 21 | # gcloud builds submit --config <(envsubst < cloudbuild-uninstrumented-app.yaml) . 22 | steps: 23 | - name: 'gcr.io/cloud-builders/docker' 24 | env: 25 | - 'DOCKER_BUILDKIT=1' 26 | args: [ 'build', '-t', '${REGISTRY_LOCATION}-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/${ARTIFACT_REGISTRY}/java-quickstart:latest', '-f', 'uninstrumented.Dockerfile', '.' ] 27 | - name: 'gcr.io/cloud-builders/docker' 28 | args: [ 'push', '${REGISTRY_LOCATION}-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/${ARTIFACT_REGISTRY}/java-quickstart:latest' ] 29 | images: ['${REGISTRY_LOCATION}-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/${ARTIFACT_REGISTRY}/java-quickstart:latest'] 30 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/docker-compose.cloudbuild.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # This compose file is only used for integration tests in Cloud Build 16 | 17 | version: "3" 18 | 19 | networks: 20 | # Make containers use default Cloud Build network for ADC 21 | # https://cloud.google.com/build/docs/build-config-file-schema#network 22 | default: 23 | name: cloudbuild 24 | external: true 25 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/docker-compose.creds.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # Use this compose file along with docker-compose.yaml to pass a credentials file from the host 16 | # into the collector container: 17 | # 18 | # ``` 19 | # GOOGLE_CLOUD_PROJECT="otel-quickstart-demos" \ 20 | # GOOGLE_APPLICATION_CREDENTIALS="$HOME/.config/gcloud/application_default_credentials.json" \ 21 | # USERID="$(id -u)" \ 22 | # docker compose -f docker-compose.yaml -f docker-compose.creds.yaml up --abort-on-container-exit 23 | # ``` 24 | 25 | version: "3" 26 | 27 | services: 28 | otelcol: 29 | # If the collector does not have permission to read the mounted volumes, set 30 | # USERID=$(id -u) to run the container as the current user 31 | user: $USERID 32 | volumes: 33 | - ${GOOGLE_APPLICATION_CREDENTIALS?}:${GOOGLE_APPLICATION_CREDENTIALS}:ro 34 | environment: 35 | - GOOGLE_APPLICATION_CREDENTIALS 36 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | version: "3" 16 | 17 | services: 18 | app: 19 | build: . 20 | environment: 21 | - OTEL_EXPORTER_OTLP_ENDPOINT=http://otelcol:4317 22 | - OTEL_SERVICE_NAME=otel-quickstart-spring-boot 23 | - OTEL_METRIC_EXPORT_INTERVAL=5000 24 | - OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=BASE2_EXPONENTIAL_BUCKET_HISTOGRAM 25 | volumes: 26 | - logs:/var/log:rw 27 | ports: 28 | - 8080 29 | depends_on: 30 | - "otelcol" 31 | otelcol: 32 | image: otel/opentelemetry-collector-contrib:0.115.1 33 | volumes: 34 | - ./otel-collector-config.yaml:/etc/otelcol-contrib/config.yaml:ro 35 | - logs:/var/log:ro 36 | environment: 37 | - GOOGLE_CLOUD_PROJECT 38 | - GOOGLE_CLOUD_QUOTA_PROJECT 39 | ports: 40 | # Collector prometheus port. The metrics are checked in tests 41 | - 8888 42 | loadgen: 43 | image: golang:1.21 44 | command: 45 | [ 46 | "go", 47 | "run", 48 | "github.com/rakyll/hey@latest", 49 | "-c=2", 50 | "-q=1", 51 | "-z=10m", 52 | "http://app:8080/multi", 53 | ] 54 | depends_on: 55 | - "app" 56 | volumes: 57 | logs: 58 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoogleCloudPlatform/opentelemetry-operations-java/4a5876da5552cdd5207e0b71011b85327265574b/examples/instrumentation-quickstart/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/integrationtest/quickstart_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 Google LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Tests that docker compose services come up and that metrics, logs, and traces are 16 | // successfully sent from the collector to GCP. See 17 | // https://github.com/GoogleCloudPlatform/opentelemetry-operations-e2e-testing/blob/main/quickstarttest/README.md 18 | // for details 19 | 20 | package integrationtest 21 | 22 | import ( 23 | "testing" 24 | 25 | "github.com/GoogleCloudPlatform/opentelemetry-operations-e2e-testing/quickstarttest" 26 | ) 27 | 28 | func TestApp(t *testing.T) { 29 | quickstarttest.InstrumentationQuickstartTest(t, "..") 30 | } 31 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 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 | 17 | rootProject.name = 'demo' 18 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/src/main/java/com/example/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | 17 | package com.example.demo; 18 | 19 | import org.springframework.boot.SpringApplication; 20 | import org.springframework.boot.autoconfigure.SpringBootApplication; 21 | import org.springframework.context.annotation.Bean; 22 | import org.springframework.web.reactive.function.client.WebClient; 23 | 24 | @SpringBootApplication 25 | public class DemoApplication { 26 | @Bean 27 | public WebClient provideClient() { 28 | return WebClient.create(); 29 | } 30 | 31 | public static void main(String[] args) { 32 | SpringApplication.run(DemoApplication.class, args); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/src/main/java/com/example/demo/MultiController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | 17 | package com.example.demo; 18 | 19 | import java.util.concurrent.ThreadLocalRandom; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.web.bind.annotation.GetMapping; 24 | import org.springframework.web.bind.annotation.RestController; 25 | import org.springframework.web.reactive.function.client.WebClient; 26 | import reactor.core.publisher.Flux; 27 | import reactor.core.publisher.Mono; 28 | 29 | @RestController 30 | public class MultiController { 31 | Logger logger = LoggerFactory.getLogger(getClass()); 32 | 33 | @Autowired private WebClient client; 34 | 35 | // [START opentelemetry_instrumentation_handle_multi] 36 | /** 37 | * handleMulti handles an http request by making 3-7 http requests to the /single endpoint. 38 | * 39 | *

OpenTelemetry instrumentation requires no changes here. It will automatically generate a 40 | * span for the controller body. 41 | */ 42 | @GetMapping("/multi") 43 | public Mono handleMulti() throws Exception { 44 | int subRequests = ThreadLocalRandom.current().nextInt(3, 8); 45 | 46 | // Write a structured log with the request context, which allows the log to 47 | // be linked with the trace for this request. 48 | logger.info("handle /multi request with subRequests={}", subRequests); 49 | 50 | // Make 3-7 http requests to the /single endpoint. 51 | return Flux.range(0, subRequests) 52 | .concatMap( 53 | i -> client.get().uri("http://localhost:8080/single").retrieve().bodyToMono(Void.class)) 54 | .then(Mono.just("ok")); 55 | } 56 | // [END opentelemetry_instrumentation_handle_multi] 57 | } 58 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/src/main/java/com/example/demo/SingleController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | 17 | package com.example.demo; 18 | 19 | import java.util.concurrent.ThreadLocalRandom; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | import org.springframework.web.bind.annotation.GetMapping; 23 | import org.springframework.web.bind.annotation.RestController; 24 | 25 | @RestController 26 | public class SingleController { 27 | Logger logger = LoggerFactory.getLogger(getClass()); 28 | 29 | // [START opentelemetry_instrumentation_handle_single] 30 | /** 31 | * handleSingle handles an http request by sleeping for 100-200 ms. It writes the number of 32 | * milliseconds slept as its response. 33 | * 34 | *

OpenTelemetry instrumentation requires no changes here. It will automatically generate a 35 | * span for the controller body. 36 | */ 37 | @GetMapping("/single") 38 | public String handleSingle() throws InterruptedException { 39 | int sleepMillis = ThreadLocalRandom.current().nextInt(100, 200); 40 | logger.info("Going to sleep for {}", sleepMillis); 41 | Thread.sleep(sleepMillis); 42 | logger.info("Finishing the request"); 43 | return String.format("slept %s\n", sleepMillis); 44 | } 45 | // [END opentelemetry_instrumentation_handle_single] 46 | } 47 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 22 | 23 | 25 | 26 | 28 | 29 | 34 | 39 | 44 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/src/test/java/com/example/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | 17 | package com.example.demo; 18 | 19 | import org.junit.jupiter.api.Test; 20 | import org.springframework.boot.test.context.SpringBootTest; 21 | 22 | @SpringBootTest 23 | public class DemoApplicationTests { 24 | 25 | /** 26 | * Empty test is included by Spring Boot Initializr and ensures that the Spring Boot application 27 | * can start up. This checks that the dependency injection is working correctly and the 28 | * logback.xml config works. 29 | */ 30 | @Test 31 | public void contextLoads() {} 32 | } 33 | -------------------------------------------------------------------------------- /examples/instrumentation-quickstart/uninstrumented.Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright 2025 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | FROM eclipse-temurin:17-jdk-alpine AS build 16 | WORKDIR /workspace/app 17 | 18 | COPY . /workspace/app 19 | RUN --mount=type=cache,target=/root/.gradle ./gradlew clean build 20 | RUN mkdir -p build/dependency && (cd build/dependency; jar -xf ../libs/*-SNAPSHOT.jar) 21 | 22 | FROM eclipse-temurin:17-jdk-alpine 23 | VOLUME /tmp 24 | ARG DEPENDENCY=/workspace/app/build/dependency 25 | COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib 26 | COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF 27 | COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app 28 | 29 | CMD sh -c "java -cp app:app/lib/* com.example.demo.DemoApplication \ 30 | 2>&1 | tee /var/log/app.log" 31 | EXPOSE 8080 32 | -------------------------------------------------------------------------------- /examples/metrics/README.md: -------------------------------------------------------------------------------- 1 | ### Running the example to export metrics to Google Cloud 2 | 3 | You can run this example to generate sample metrics on any Google Cloud project. 4 | 5 | #### Prerequisites 6 | 7 | ##### Get Google Cloud Credentials on your machine 8 | 9 | ```shell 10 | gcloud auth application-default login 11 | ``` 12 | Executing this command will save your application credentials to default path which will depend on the type of machine - 13 | - Linux, macOS: `$HOME/.config/gcloud/application_default_credentials.json` 14 | - Windows: `%APPDATA%\gcloud\application_default_credentials.json` 15 | 16 | ##### Export the retrieved credentials to `GOOGLE_APPLICATION_CREDENTIALS` environment variable. 17 | 18 | ```shell 19 | export GOOGLE_APPLICATION_CREDENTIALS=$HOME/.config/gcloud/application_default_credentials.json 20 | ``` 21 | 22 | ##### Export the Google Cloud Project ID to `GOOGLE_CLOUD_PROJECT` environment variable: 23 | 24 | ```shell 25 | export GOOGLE_CLOUD_PROJECT="my-awesome-gcp-project-id" 26 | ``` 27 | 28 | ### Running the example 29 | 30 | #### Run the example locally 31 | 32 | You can run the example application via gradle. From the project root: 33 | 34 | ```shell 35 | # Running with default exporter config 36 | cd examples/metrics/ && gradle run 37 | 38 | # Running with custom exporter config 39 | cd examples/metrics/ && gradle run --args='--custom-config' 40 | ``` 41 | 42 | #### Run the example as a Cloud Run Job 43 | 44 | You can run the example application as a Google Cloud Run Job. A convenience script has been provided for this. 45 | 46 | First, export your preferred Google cloud region where you want to create and run the job: 47 | 48 | ```shell 49 | # This can be any valid Google Cloud Region 50 | export GOOGLE_CLOUD_RUN_REGION="us-central1" 51 | ``` 52 | 53 | Then, from the project root: 54 | 55 | ```shell 56 | cd examples/metrics/ && ./run_as_cloud-run-job.sh 57 | ``` 58 | 59 | *Note: When using the convenience script, it will create a Google Cloud Artifact Registry named `cloud-run-applications` in your 60 | selected project.* 61 | 62 | You should now see the exported metrics in your Google Cloud project. 63 | -------------------------------------------------------------------------------- /examples/metrics/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | plugins { 17 | id 'java' 18 | id 'application' 19 | id 'com.google.cloud.tools.jib' 20 | } 21 | 22 | // examples are not published, so version can be hardcoded 23 | version = '0.1.0' 24 | 25 | // Set Docker image path here, e.g. using Google Container Registry or Docker Hub 26 | // https://github.com/GoogleContainerTools/jib/tree/master/jib-gradle-plugin#configuration 27 | jib { 28 | from.image = 'gcr.io/distroless/java-debian10:11' 29 | containerizingMode = 'packaged' 30 | } 31 | 32 | mainClassName = 'com.google.cloud.opentelemetry.example.metrics.MetricsExporterExample' 33 | 34 | description = 'Examples for Cloud Monitoring Exporter' 35 | 36 | dependencies { 37 | implementation(libraries.opentelemetry_api) 38 | implementation(libraries.opentelemetry_sdk_metrics) 39 | implementation(libraries.google_cloud_monitoring) 40 | implementation project(':exporter-metrics') 41 | implementation(libraries.opentelemetry_gcp_resources) 42 | // required by resource detection 43 | implementation(libraries.opentelemetry_autoconfigure_spi) 44 | // this helps in debugging as it outputs all export to std out 45 | implementation(libraries.opentelemetry_logging_exporter) 46 | } 47 | -------------------------------------------------------------------------------- /examples/metrics/run_as_cloud-run-job.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright 2023 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | ARTIFACT_REPOSITORY=cloud-run-applications 18 | JOB_NAME=job-metrics-export 19 | 20 | # Verify necessary environment variables are set 21 | echo "${GOOGLE_CLOUD_PROJECT:?${UNSET_WARNING}}" 22 | echo "${GOOGLE_APPLICATION_CREDENTIALS:?${UNSET_WARNING}}" 23 | echo "${GOOGLE_CLOUD_RUN_REGION:?${UNSET_WARNING}}" 24 | 25 | echo "ENVIRONMENT VARIABLES VERIFIED" 26 | 27 | # Safety check to verify if repository already exists. 28 | if gcloud artifacts repositories describe ${ARTIFACT_REPOSITORY} \ 29 | --location="${GOOGLE_CLOUD_RUN_REGION}" 30 | then 31 | echo "Repository ${ARTIFACT_REPOSITORY} already exists." 32 | else 33 | echo "CREATING CLOUD ARTIFACT REPOSITORY" 34 | gcloud artifacts repositories create ${ARTIFACT_REPOSITORY} --repository-format=docker --location=${GOOGLE_CLOUD_RUN_REGION} --description="Sample applications to run on Google Cloud Run" 35 | echo "CREATED ${ARTIFACT_REPOSITORY} in ${GOOGLE_CLOUD_RUN_REGION}" 36 | fi 37 | 38 | echo "BUILDING SAMPLE APP IMAGE" 39 | gradle clean jib --image "${GOOGLE_CLOUD_RUN_REGION}-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/${ARTIFACT_REPOSITORY}/metrics-export-java" 40 | 41 | # Safety check to verify if the job already exists 42 | if gcloud run jobs describe ${JOB_NAME} --region="${GOOGLE_CLOUD_RUN_REGION}" 43 | then 44 | echo "Job ${JOB_NAME} already exists" 45 | else 46 | echo "CREATING A CLOUD RUN JOB TO RUN THE CONTAINER" 47 | gcloud run jobs create job-metrics-export \ 48 | --image="${GOOGLE_CLOUD_RUN_REGION}-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/${ARTIFACT_REPOSITORY}/metrics-export-java" \ 49 | --max-retries=5 \ 50 | --region="${GOOGLE_CLOUD_RUN_REGION}" \ 51 | --project="${GOOGLE_CLOUD_PROJECT}" 52 | fi 53 | 54 | echo "SETTING CLOUD RUN JOB REGION" 55 | gcloud config set run/region "${GOOGLE_CLOUD_RUN_REGION}" 56 | 57 | echo "RUNNING THE CREATED JOB" 58 | gcloud run jobs execute job-metrics-export 59 | -------------------------------------------------------------------------------- /examples/otlp-spring/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 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 | plugins { 17 | id 'java' 18 | id 'application' 19 | id 'com.google.cloud.tools.jib' 20 | } 21 | 22 | description = 'Example showcasing OTLP trace ingest on GCP and Google Auth in a Spring Boot App' 23 | 24 | // examples are not published, so version can be hardcoded 25 | version = '0.1.0' 26 | 27 | repositories { 28 | mavenCentral() 29 | } 30 | 31 | dependencies { 32 | implementation(libraries.opentelemetry_api) 33 | implementation(libraries.opentelemetry_sdk) 34 | implementation(libraries.opentelemetry_otlp_exporter) 35 | implementation(libraries.opentelemetry_sdk_autoconf) 36 | implementation(libraries.opentelemetry_gcp_auth_extension) 37 | implementation(libraries.opentelemetry_gcp_resources) 38 | 39 | implementation(libraries.spring_boot_starter_web) 40 | } 41 | 42 | def autoconf_config = [ 43 | '-Dgoogle.cloud.project=your-gcp-project-id', 44 | '-Dotel.exporter.otlp.endpoint=https://telemetry.googleapis.com', 45 | '-Dotel.traces.exporter=otlp', 46 | '-Dotel.metrics.exporter=none', 47 | '-Dotel.exporter.otlp.protocol=http/protobuf', 48 | '-Dotel.java.global-autoconfigure.enabled=true', 49 | '-Dotel.service.name=spring-otlp-trace-example-service', 50 | ] 51 | 52 | application { 53 | mainClass = "com.google.cloud.opentelemetry.examples.otlpspring.Main" 54 | applicationDefaultJvmArgs = autoconf_config 55 | } 56 | 57 | jib { 58 | from.image = "gcr.io/distroless/java-debian10:11" 59 | containerizingMode = "packaged" 60 | container.jvmFlags = autoconf_config as List 61 | container.ports = ["8080"] 62 | } 63 | 64 | tasks.register('runClient', JavaExec) { 65 | classpath = sourceSets.test.runtimeClasspath 66 | mainClass = 'com.google.cloud.opentelemetry.examples.otlpspring.MainClient' 67 | } 68 | -------------------------------------------------------------------------------- /examples/otlp-spring/k8s/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: telemetry-export 5 | namespace: default 6 | --- 7 | apiVersion: apps/v1 8 | kind: Deployment 9 | metadata: 10 | name: spring-otlp-trace-example 11 | namespace: default 12 | labels: 13 | app: spring-otlp-trace-example 14 | tier: backend 15 | spec: 16 | selector: 17 | matchLabels: 18 | app: spring-otlp-trace-example 19 | tier: backend 20 | template: 21 | metadata: 22 | labels: 23 | app: spring-otlp-trace-example 24 | tier: backend 25 | spec: 26 | serviceAccountName: telemetry-export 27 | containers: 28 | - name: spring-otlp-trace-example 29 | image: us-central1-docker.pkg.dev/%GOOGLE_CLOUD_PROJECT%/otlp-samples/spring-otlp-trace-example:v1 30 | imagePullPolicy: Always 31 | # required for resource detection in GKE environment 32 | env: 33 | - name: NAMESPACE 34 | valueFrom: 35 | fieldRef: 36 | fieldPath: metadata.namespace 37 | - name: CONTAINER_NAME 38 | valueFrom: 39 | fieldRef: 40 | fieldPath: metadata.name 41 | --- 42 | apiVersion: v1 43 | kind: Service 44 | metadata: 45 | name: spring-otlp-service 46 | spec: 47 | selector: 48 | app: spring-otlp-trace-example 49 | tier: backend 50 | ports: 51 | - protocol: TCP 52 | port: 60000 53 | targetPort: 8080 54 | -------------------------------------------------------------------------------- /examples/otlp-spring/src/main/java/com/google/cloud/opentelemetry/examples/otlpspring/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.examples.otlpspring; 17 | 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | import org.springframework.boot.SpringApplication; 21 | import org.springframework.boot.autoconfigure.SpringBootApplication; 22 | 23 | @SpringBootApplication 24 | public class Main { 25 | private static final Logger logger = LoggerFactory.getLogger(Main.class); 26 | 27 | public static void main(String[] args) { 28 | logger.info("Starting OTLP with Spring Boot and Google Auth"); 29 | SpringApplication.run(Main.class, args); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /examples/otlp-spring/src/main/java/com/google/cloud/opentelemetry/examples/otlpspring/configuration/OpenTelemetryConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.examples.otlpspring.configuration; 17 | 18 | import io.opentelemetry.sdk.OpenTelemetrySdk; 19 | import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | import org.springframework.beans.factory.config.ConfigurableBeanFactory; 23 | import org.springframework.context.annotation.Bean; 24 | import org.springframework.context.annotation.Configuration; 25 | import org.springframework.context.annotation.Scope; 26 | 27 | @Configuration 28 | public class OpenTelemetryConfiguration { 29 | private final Logger logger = LoggerFactory.getLogger(OpenTelemetryConfiguration.class); 30 | 31 | @Bean 32 | @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) 33 | public OpenTelemetrySdk getOpenTelemetrySdk() { 34 | logger.info("Initializing Autoconfigured OpenTelemetry SDK"); 35 | AutoConfiguredOpenTelemetrySdk autoConfOTelSdk = AutoConfiguredOpenTelemetrySdk.initialize(); 36 | return autoConfOTelSdk.getOpenTelemetrySdk(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /examples/otlp-spring/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG 2 | spring.application.name=otlp-trace-google-auth 3 | -------------------------------------------------------------------------------- /examples/otlpmetric/README.md: -------------------------------------------------------------------------------- 1 | # OTLP Metric with Google Auth Example 2 | 3 | Run this sample to connect to an endpoint that is protected by GCP authentication. 4 | 5 | First, get GCP credentials on your machine: 6 | 7 | ```shell 8 | gcloud auth application-default login 9 | ``` 10 | Executing this command will save your application credentials to default path which will depend on the type of machine - 11 | - Linux, macOS: `$HOME/.config/gcloud/application_default_credentials.json` 12 | - Windows: `%APPDATA%\gcloud\application_default_credentials.json` 13 | 14 | Next, update [`build.gradle`](build.grade) to set the following: 15 | 16 | ``` 17 | '-Dotel.resource.attributes=gcp.project_id=, 18 | # Optional - if you want to export using gRPC protocol 19 | '-Dotel.exporter.otlp.protocol=grpc', 20 | ``` 21 | 22 | Finally, to run the sample from the project root: 23 | ``` 24 | ./gradlew :examples-otlpmetric:run 25 | ``` 26 | -------------------------------------------------------------------------------- /examples/otlpmetric/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2025 Google LLC 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 | plugins { 17 | id 'java' 18 | id 'application' 19 | } 20 | // examples are not published, so version can be hardcoded 21 | version = '0.1.0' 22 | 23 | mainClassName = 'com.google.cloud.opentelemetry.example.otlpmetric.OTLPMetricExample' 24 | 25 | description = 'Example for OTLP Metric exporter' 26 | 27 | dependencies { 28 | implementation(libraries.opentelemetry_api) 29 | implementation(libraries.opentelemetry_sdk) 30 | implementation(libraries.opentelemetry_otlp_exporter) 31 | implementation(libraries.opentelemetry_sdk_autoconf) 32 | implementation(libraries.opentelemetry_gcp_resources) 33 | implementation(libraries.google_auth) 34 | } 35 | 36 | def autoconf_config = [ 37 | '-Dotel.exporter.otlp.endpoint=https://telemetry.googleapis.com', 38 | '-Dotel.resource.attributes=gcp.project_id=', 39 | '-Dotel.metrics.exporter=otlp', 40 | '-Dotel.logs.exporter=none', 41 | '-Dotel.traces.exporter=none', 42 | '-Dotel.service.name=otlpmetrics-example', 43 | '-Dotel.exporter.otlp.protocol=http/protobuf', 44 | '-Dotel.java.global-autoconfigure.enabled=true', 45 | ] 46 | 47 | application { 48 | mainClassName = 'com.google.cloud.opentelemetry.example.otlpmetric.OTLPMetricExample' 49 | applicationDefaultJvmArgs = autoconf_config 50 | } 51 | -------------------------------------------------------------------------------- /examples/otlpmetrics-function/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 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 | plugins { 17 | id 'java' 18 | id "com.github.johnrengelman.shadow" 19 | } 20 | 21 | import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar 22 | 23 | // examples are not published, so version can be hardcoded 24 | version = '0.1.0' 25 | 26 | repositories { 27 | mavenCentral() 28 | } 29 | 30 | configurations { 31 | invoker 32 | } 33 | 34 | dependencies { 35 | implementation 'com.google.cloud.functions:functions-framework-api:1.0.4' 36 | implementation(libraries.opentelemetry_api) 37 | implementation(libraries.opentelemetry_sdk_metrics) 38 | 39 | // required by resource detection 40 | implementation(libraries.opentelemetry_autoconfigure_spi) 41 | // resource detection module 42 | implementation(libraries.opentelemetry_gcp_resources) 43 | 44 | implementation(libraries.opentelemetry_otlp_exporter) 45 | implementation(libraries.opentelemetry_logging_exporter) 46 | 47 | // For testing functions locally 48 | invoker 'com.google.cloud.functions.invoker:java-function-invoker:1.1.1' 49 | } 50 | 51 | jar { 52 | manifest { 53 | doFirst { 54 | attributes 'Class-Path': files(configurations.runtimeClasspath).asPath 55 | } 56 | } 57 | } 58 | 59 | tasks.named('shadowJar', ShadowJar) { 60 | archivesBaseName = 'hello-world-function' 61 | archiveClassifier = '' 62 | archiveVersion = '' 63 | destinationDirectory.set(file('out/deployment/')) 64 | } 65 | 66 | clean { 67 | doLast { 68 | println "Deleting previous output..." 69 | project.delete(files('out')) 70 | } 71 | } 72 | 73 | // Task only used to test the function locally 74 | tasks.register('runFunction', JavaExec) { 75 | mainClass = 'com.google.cloud.functions.invoker.runner.Invoker' 76 | classpath(configurations.invoker) 77 | inputs.files(configurations.runtimeClasspath, sourceSets.main.output) 78 | args( 79 | '--target', project.findProperty('run.functionTarget'), 80 | '--port', project.findProperty('run.port') ?: 8080 81 | ) 82 | doFirst { 83 | args('--classpath', files(configurations.runtimeClasspath, sourceSets.main.output).asPath) 84 | } 85 | } 86 | 87 | test { 88 | useJUnitPlatform() 89 | } 90 | -------------------------------------------------------------------------------- /examples/otlpmetrics-function/collector-deployment/Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright 2024 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https:#www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | FROM otel/opentelemetry-collector-contrib:0.111.0 16 | 17 | COPY collector-config.yaml /etc/otelcol-contrib/config.yaml 18 | -------------------------------------------------------------------------------- /examples/otlpmetrics-function/collector-deployment/collector-config.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2024 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https:#www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | receivers: 16 | otlp: 17 | protocols: 18 | grpc: 19 | http: 20 | 21 | processors: 22 | resourcedetection: 23 | detectors: [env, gcp] 24 | timeout: 2s 25 | override: false 26 | 27 | exporters: 28 | googlemanagedprometheus: 29 | debug: 30 | verbosity: detailed 31 | sampling_initial: 5 32 | sampling_thereafter: 200 33 | 34 | extensions: 35 | health_check: 36 | 37 | service: 38 | extensions: [health_check] 39 | pipelines: 40 | metrics: 41 | receivers: [otlp] 42 | processors: [resourcedetection] 43 | exporters: [debug, googlemanagedprometheus] 44 | -------------------------------------------------------------------------------- /examples/otlpmetrics-function/src/main/java/com/google/cloud/opentelemetry/examples/otlpmetricsfunction/HelloWorld.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.examples.otlpmetricsfunction; 17 | 18 | import com.google.cloud.functions.HttpFunction; 19 | import com.google.cloud.functions.HttpRequest; 20 | import com.google.cloud.functions.HttpResponse; 21 | import io.opentelemetry.api.metrics.LongCounter; 22 | import java.util.Random; 23 | 24 | public class HelloWorld implements HttpFunction { 25 | private static final OpenTelemetryConfig openTelemetryConfig = OpenTelemetryConfig.getInstance(); 26 | private static final LongCounter counter = 27 | openTelemetryConfig 28 | .getMeterProvider() 29 | .get("sample-function-library") 30 | .counterBuilder("function_counter_gmp") 31 | .setDescription("random counter") 32 | .build(); 33 | private static final Random random = new Random(); 34 | 35 | public HelloWorld() { 36 | super(); 37 | // Register a shutdown hook as soon as the function object is instantiated 38 | Runtime.getRuntime() 39 | .addShutdownHook( 40 | new Thread( 41 | () -> { 42 | System.out.println("Closing OpenTelemetry SDK"); 43 | openTelemetryConfig.closeSdk(); 44 | System.out.println("OpenTelemetry SDK closed"); 45 | })); 46 | } 47 | 48 | @Override 49 | public void service(HttpRequest request, HttpResponse response) throws Exception { 50 | System.out.println("received request: " + request.toString()); 51 | counter.add(random.nextInt(100)); 52 | response.getWriter().write("Hello, World\n"); 53 | System.out.println("Function exited"); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /examples/otlptrace/README.md: -------------------------------------------------------------------------------- 1 | # OTLP Trace with Google Auth Example 2 | 3 | Run this sample to connect to an endpoint that is protected by GCP authentication. 4 | 5 | First, get GCP credentials on your machine: 6 | 7 | ```shell 8 | gcloud auth application-default login 9 | ``` 10 | Executing this command will save your application credentials to default path which will depend on the type of machine - 11 | - Linux, macOS: `$HOME/.config/gcloud/application_default_credentials.json` 12 | - Windows: `%APPDATA%\gcloud\application_default_credentials.json` 13 | 14 | Next, export the `GOOGLE_CLOUD_PROJECT` environment variable: 15 | ```shell 16 | # Use your GCP project ID 17 | export GOOGLE_CLOUD_PROJECT="your-gcp-project-id" 18 | ``` 19 | This environment variable also configures the [OpenTelemetry GCP Auth Extension](https://github.com/open-telemetry/opentelemetry-java-contrib/tree/main/gcp-auth-extension) that facilitates authentication to GCP. 20 | 21 | Finally, to run the sample from the project root: 22 | 23 | ``` 24 | ./gradlew :examples-otlptrace:run 25 | ``` 26 | 27 | Running this sample will generate and export Traces to Google Cloud. 28 | -------------------------------------------------------------------------------- /examples/otlptrace/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 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 | plugins { 17 | id 'java' 18 | id 'application' 19 | } 20 | // examples are not published, so version can be hardcoded 21 | version = '0.1.0' 22 | 23 | description = 'Example showing OTLP exporter being used for traces export to GCP' 24 | 25 | dependencies { 26 | implementation(libraries.opentelemetry_api) 27 | implementation(libraries.opentelemetry_sdk) 28 | implementation(libraries.opentelemetry_otlp_exporter) 29 | implementation(libraries.opentelemetry_sdk_autoconf) 30 | implementation(libraries.opentelemetry_gcp_auth_extension) 31 | implementation(libraries.opentelemetry_gcp_resources) 32 | } 33 | 34 | def autoconf_config = [ 35 | '-Dotel.exporter.otlp.endpoint=https://telemetry.googleapis.com', 36 | '-Dotel.traces.exporter=otlp', 37 | '-Dotel.logs.exporter=none', 38 | '-Dotel.metrics.exporter=none', 39 | '-Dotel.service.name=otlptrace-example', 40 | '-Dotel.exporter.otlp.protocol=http/protobuf', 41 | '-Dotel.java.global-autoconfigure.enabled=true', 42 | ] 43 | 44 | application { 45 | mainClassName = 'com.google.cloud.opentelemetry.example.otlptrace.OTLPTraceExample' 46 | applicationDefaultJvmArgs = autoconf_config 47 | } 48 | -------------------------------------------------------------------------------- /examples/resource/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | plugins { 17 | id 'java' 18 | id 'application' 19 | id 'com.google.cloud.tools.jib' 20 | } 21 | // examples are not published, so version can be hardcoded 22 | version = '0.1.0' 23 | 24 | description = 'Examples for showing resource detection in various GCP environments.' 25 | 26 | dependencies { 27 | implementation(libraries.opentelemetry_api) 28 | // Detects resource attributes from various GCP environments 29 | implementation(libraries.opentelemetry_gcp_resources) 30 | // Provides resources to the autoconfiguration module 31 | implementation(libraries.opentelemetry_sdk_autoconf) 32 | } 33 | 34 | mainClassName = 'com.google.cloud.opentelemetry.example.resource.ResourceExample' 35 | 36 | jib { 37 | from.image = 'gcr.io/distroless/java-debian10:11' 38 | containerizingMode = 'packaged' 39 | } 40 | 41 | def autoconf_config = [ 42 | '-Dotel.traces.exporter=none', 43 | '-Dotel.metrics.exporter=none', 44 | '-Dotel.logs.exporter=none', 45 | '-Dotel.java.global-autoconfigure.enabled=true', 46 | '-Dotel.service.name=example-resource', 47 | ] 48 | 49 | application { 50 | applicationDefaultJvmArgs = autoconf_config 51 | } 52 | -------------------------------------------------------------------------------- /examples/resource/job.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | apiVersion: batch/v1 15 | kind: Job 16 | metadata: 17 | # Unique key of the Job instance 18 | name: hello-resource-java 19 | spec: 20 | template: 21 | metadata: 22 | name: hello-resource-java 23 | labels: 24 | service: hello-resource-java 25 | spec: 26 | containers: 27 | - name: hello-resource-java 28 | image: gcr.io/%GOOGLE_CLOUD_PROJECT%/hello-resource-java:latest 29 | env: 30 | - name: OTEL_TRACES_EXPORTER 31 | value: none 32 | - name: OTEL_METRICS_EXPOERTER 33 | value: none 34 | - name: OTEL_SERVICE_NAME 35 | valueFrom: 36 | fieldRef: 37 | fieldPath: metadata.labels['service'] 38 | - name: POD_NAME 39 | valueFrom: 40 | fieldRef: 41 | fieldPath: metadata.name 42 | - name: NAMESPACE 43 | valueFrom: 44 | fieldRef: 45 | fieldPath: metadata.namespace 46 | - name: CONTAINER_NAME 47 | value: hello-resource-java 48 | # Do not restart containers after they exit 49 | restartPolicy: Never 50 | # of retries before marking as failed. 51 | backoffLimit: 4 -------------------------------------------------------------------------------- /examples/resource/src/main/java/com/google/cloud/opentelemetry/example/resource/ResourceExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.example.resource; 17 | 18 | import io.opentelemetry.contrib.gcp.resource.GCPResourceProvider; 19 | import io.opentelemetry.sdk.OpenTelemetrySdk; 20 | import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; 21 | import io.opentelemetry.sdk.autoconfigure.ResourceConfiguration; 22 | import io.opentelemetry.sdk.resources.Resource; 23 | import io.opentelemetry.sdk.trace.SdkTracerProvider; 24 | 25 | public class ResourceExample { 26 | public static void main(String[] args) { 27 | // Get the autoconfigured OpenTelemetry SDK 28 | OpenTelemetrySdk openTelemetrySdk = 29 | AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk(); 30 | 31 | // Shows the resource attributes detected from the environment variables 32 | // and system properties. 33 | System.out.println("Detecting resource: Environment"); 34 | Resource autoResource = ResourceConfiguration.createEnvironmentResource(); 35 | System.out.println(autoResource.getAttributes() + "\n"); 36 | 37 | // Shows the resource attributes detected by the GCP Resource Provider 38 | System.out.println("Detecting resource: hardcoded"); 39 | GCPResourceProvider resourceProvider = new GCPResourceProvider(); 40 | System.out.println(resourceProvider.getAttributes() + "\n"); 41 | 42 | // Shows the attributes attached to the Resource that was set for TracerProvider 43 | // via the autoconfiguration SPI. 44 | // This works similarly for MeterProvider and LoggerProvider. 45 | System.out.println("Detecting resource: Autoconfigure"); 46 | SdkTracerProvider autoConfTracerProvider = openTelemetrySdk.getSdkTracerProvider(); 47 | System.out.println(autoConfTracerProvider.toString() + "\n"); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /examples/spring-boot-starter/src/main/java/com/google/cloud/opentelemetry/example/springbootstarter/AppController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.example.springbootstarter; 17 | 18 | import org.springframework.web.bind.annotation.GetMapping; 19 | import org.springframework.web.bind.annotation.RestController; 20 | 21 | @RestController 22 | public class AppController { 23 | 24 | private static final String DESCRIPTION_MESSAGE = 25 | "Sample Spring Boot Application instrumented with OpenTelemetry Spring Boot Starter"; 26 | 27 | @GetMapping("/ping") 28 | public String ping() { 29 | return "Hello World!"; 30 | } 31 | 32 | @GetMapping("/") 33 | public String home() { 34 | return DESCRIPTION_MESSAGE; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /examples/spring-boot-starter/src/main/java/com/google/cloud/opentelemetry/example/springbootstarter/SpringBootStarterApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.example.springbootstarter; 17 | 18 | import org.springframework.boot.SpringApplication; 19 | import org.springframework.boot.autoconfigure.SpringBootApplication; 20 | 21 | @SpringBootApplication 22 | public class SpringBootStarterApplication { 23 | 24 | public static void main(String[] args) { 25 | SpringApplication.run(SpringBootStarterApplication.class, args); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /examples/spring-boot-starter/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=spring-boot-native-app 2 | otel.traces.exporter=google_cloud_trace 3 | otel.metrics.exporter=google_cloud_monitoring 4 | otel.logs.exporter=none 5 | otel.resource.attributes.service.name=sample-native-app 6 | otel.resource.attributes.service.namespace=gcp-otel-samples 7 | otel.resource.providers.gcp.enabled=true 8 | -------------------------------------------------------------------------------- /examples/spring-sleuth/README.md: -------------------------------------------------------------------------------- 1 | # Using Spring Sleuth to configure OpenTelemetry for Google Cloud Trace 2 | 3 | This example shows how to export traces to GCP generated from a Spring Boot application. 4 | Spring Cloud Sleuth is used to provide auto-configuration for distributed tracing. 5 | 6 | #### Prerequisites 7 | 8 | ##### Get Google Cloud Credentials on your machine 9 | 10 | ```shell 11 | gcloud auth application-default login 12 | ``` 13 | Executing this command will save your application credentials to default path which will depend on the type of machine - 14 | - Linux, macOS: `$HOME/.config/gcloud/application_default_credentials.json` 15 | - Windows: `%APPDATA%\gcloud\application_default_credentials.json` 16 | 17 | ##### Export the Google Cloud Project ID to `GOOGLE_CLOUD_PROJECT` environment variable: 18 | 19 | ```shell 20 | export GOOGLE_CLOUD_PROJECT="my-awesome-gcp-project-id" 21 | ``` 22 | 23 | #### Run the application 24 | 25 | You can run the example application via gradle. From the project root: 26 | 27 | ##### Build the executable JAR 28 | 29 | ```shell 30 | cd examples/spring-sleuth/ && gradle bootJar 31 | ``` 32 | 33 | ##### Run the executable JAR 34 | 35 | The JAR built from the previous command typically ends up in `build/libs` - 36 | 37 | ```shell 38 | java -jar build/libs/examples-spring-sleuth-0.1.0.jar 39 | ``` 40 | 41 | The application is now running. To generate traces, head to `http://localhost:8080` in your browser. 42 | *You can also try hitting other supported endpoints - `http://localhost:8080/greeting` to generate additional traces.* 43 | 44 | You should now see the exported traces in your Google Cloud project. 45 | -------------------------------------------------------------------------------- /examples/spring-sleuth/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | plugins { 17 | id 'org.springframework.boot' version '2.4.5' 18 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 19 | id 'java' 20 | } 21 | // examples are not published, so version can be hardcoded 22 | version = '0.1.0' 23 | 24 | jar { 25 | manifest { 26 | attributes( 27 | 'Main-Class': 'com.google.cloud.opentelemetry.example.spring.Main' 28 | ) 29 | } 30 | } 31 | 32 | task fatJar(type: Jar) { 33 | manifest.from jar.manifest 34 | archiveClassifier = 'all' 35 | from { 36 | configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } 37 | } { 38 | exclude "META-INF/*.SF" 39 | exclude "META-INF/*.DSA" 40 | exclude "META-INF/*.RSA" 41 | } 42 | with jar 43 | } 44 | 45 | description = 'Example of using Spring to integrate OTel and Cloud Trace' 46 | 47 | // https://spring.io/blog/2021/12/10/log4j2-vulnerability-and-spring-boot 48 | // Remove this once we upgrade to Spring Boot 2.6.2 49 | ext['log4j2.version'] = '2.16.0' 50 | 51 | dependencies { 52 | implementation(libraries.opentelemetry_api) 53 | implementation(libraries.opentelemetry_sdk) 54 | implementation(libraries.google_cloud_trace) 55 | implementation(libraries.spring_boot_starter_web) 56 | implementation(libraries.spring_cloud_starter_openfeign) 57 | implementation(libraries.spring_cloud_sleuth_otel_autoconf) 58 | implementation project(':exporter-trace') 59 | runtimeOnly(libraries.opentelemetry_gcp_resources) 60 | } 61 | -------------------------------------------------------------------------------- /examples/spring-sleuth/src/main/java/com/google/cloud/opentelemetry/example/springsleuth/GreetingClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.example.springsleuth; 17 | 18 | import org.springframework.cloud.openfeign.FeignClient; 19 | import org.springframework.web.bind.annotation.GetMapping; 20 | 21 | @FeignClient(name = "greetingClient", url = "http://localhost:8080") 22 | interface GreetingClient { 23 | @GetMapping("/greeting") 24 | String greeting(); 25 | } 26 | -------------------------------------------------------------------------------- /examples/spring-sleuth/src/main/java/com/google/cloud/opentelemetry/example/springsleuth/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.example.springsleuth; 17 | 18 | import com.google.cloud.opentelemetry.trace.TraceExporter; 19 | import io.opentelemetry.sdk.trace.export.SpanExporter; 20 | import java.io.IOException; 21 | import org.springframework.beans.factory.annotation.Autowired; 22 | import org.springframework.boot.SpringApplication; 23 | import org.springframework.boot.autoconfigure.SpringBootApplication; 24 | import org.springframework.cloud.openfeign.EnableFeignClients; 25 | import org.springframework.context.annotation.Bean; 26 | import org.springframework.web.bind.annotation.GetMapping; 27 | import org.springframework.web.bind.annotation.RestController; 28 | 29 | @EnableFeignClients 30 | @RestController 31 | @SpringBootApplication 32 | public class Main { 33 | @Autowired private GreetingClient greetingClient; 34 | 35 | public static void main(String[] args) throws IOException { 36 | SpringApplication.run(Main.class, args); 37 | } 38 | 39 | @Bean 40 | public SpanExporter googleTraceExporter() throws IOException { 41 | return TraceExporter.createWithDefaultConfiguration(); 42 | } 43 | 44 | @GetMapping("/greeting") 45 | public String greeting() { 46 | return "Hello"; 47 | } 48 | 49 | @GetMapping("/") 50 | public String home() { 51 | return greetingClient.greeting() + " World"; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /examples/spring-sleuth/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG 2 | spring.application.name=gcp-otel-spring-sleuth-demo 3 | spring.main.banner-mode=off 4 | spring.sleuth.sampler.probability=1.0 5 | -------------------------------------------------------------------------------- /examples/spring/README.md: -------------------------------------------------------------------------------- 1 | # Instrumenting Spring Application using OpenTelemetry with Resource Detection 2 | 3 | This example shows how to export metrics and traces to GCP generated from a manually instrumented Spring Boot application. 4 | Opentelemetry Autoconfiguration module is used to configure exporters and resource detection. 5 | 6 | #### Prerequisites 7 | 8 | ##### Get Google Cloud Credentials on your machine 9 | 10 | ```shell 11 | gcloud auth application-default login 12 | ``` 13 | Executing this command will save your application credentials to default path which will depend on the type of machine - 14 | - Linux, macOS: `$HOME/.config/gcloud/application_default_credentials.json` 15 | - Windows: `%APPDATA%\gcloud\application_default_credentials.json` 16 | 17 | ##### Export the Google Cloud Project ID to `GOOGLE_CLOUD_PROJECT` environment variable: 18 | 19 | ```shell 20 | export GOOGLE_CLOUD_PROJECT="my-awesome-gcp-project-id" 21 | ``` 22 | 23 | #### Run the application locally 24 | 25 | You can run the example application via gradle. From the project root: 26 | 27 | ##### Build and run the executable JAR 28 | 29 | ```shell 30 | cd examples/spring && gradle runApp 31 | ``` 32 | 33 | The application is now running. To generate traces, head to `http://localhost:8080` in your browser. 34 | *You can also try hitting other supported endpoints - `http://localhost:8080/greeting` to generate additional traces.* 35 | 36 | You should now see the exported traces in your Google Cloud project. 37 | 38 | #### Run the application in Cloud Run 39 | 40 | To run this example in Google Cloud Run, you need to run the convenience script provided. After following the prerequisites, 41 | 42 | First, export the Google Cloud Region for cloud run to `GOOGLE_CLOUD_RUN_REGION` environment variable: 43 | 44 | ```shell 45 | # This can be any supported Google cloud region 46 | export GOOGLE_CLOUD_RUN_REGION=us-central1 47 | ``` 48 | 49 | Then, from the root of the repository, 50 | ```shell 51 | cd examples/spring && ./run_in_cloud-run.sh 52 | ``` 53 | 54 | This will deploy the containerized application to Cloud Run and create a proxy endpoint on your localhost which you can then call to reach your deployed Cloud Run service. 55 | You should be able to hit the following endpoints from your browser: 56 | 57 | ```text 58 | http://localhost:8080/ 59 | http://localhost:8080/greeting 60 | ``` 61 | 62 | The metrics and traces from this example can be viewed in Google Cloud Console. 63 | 64 | ##### Cleaning up 65 | 66 | Keeping services running in Cloud Run can incur costs. Services deployed on Cloud Run can either 67 | be deleted from the GCP console or you can run the following `gcloud` command: 68 | 69 | ```shell 70 | # Delete the Cloud Run Service 71 | gcloud run services delete spring-java-cloud-run 72 | 73 | # Delete Artifact Registry 74 | gcloud artifacts repositories delete cloud-run-applications --location=$GOOGLE_CLOUD_RUN_REGION 75 | ``` 76 | -------------------------------------------------------------------------------- /examples/spring/run_in_cloud-run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright 2024 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | CONTAINER_REGISTRY=cloud-run-applications 18 | REGISTRY_LOCATION=us-central1 19 | UNSET_WARNING="Environment variable not set, please set the environment variable" 20 | 21 | # Verify necessary environment variables are set 22 | echo "${GOOGLE_CLOUD_PROJECT:?${UNSET_WARNING}}" 23 | echo "${GOOGLE_APPLICATION_CREDENTIALS:?${UNSET_WARNING}}" 24 | echo "${GOOGLE_CLOUD_RUN_REGION:?${UNSET_WARNING}}" 25 | 26 | echo "ENVIRONMENT VARIABLES VERIFIED" 27 | set -x 28 | 29 | echo "CREATING CLOUD ARTIFACT REPOSITORY" 30 | gcloud artifacts repositories create ${CONTAINER_REGISTRY} --repository-format=docker --location=${REGISTRY_LOCATION} --description="Sample applications to run on Google Cloud Run" 31 | echo "CREATED ${CONTAINER_REGISTRY} in ${REGISTRY_LOCATION}" 32 | 33 | echo "BUILDING SAMPLE APP IMAGE" 34 | gradle clean jib --image "${REGISTRY_LOCATION}-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/${CONTAINER_REGISTRY}/spring-java-sample" 35 | 36 | echo "DEPLOYING APPLICATION ON CLOUD RUN" 37 | gcloud run deploy spring-java-cloud-run \ 38 | --image="${REGISTRY_LOCATION}-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/${CONTAINER_REGISTRY}/spring-java-sample" \ 39 | --region="${GOOGLE_CLOUD_RUN_REGION}" \ 40 | --no-allow-unauthenticated \ 41 | --no-cpu-throttling \ 42 | --max-instances=5 \ 43 | --min-instances=3 44 | 45 | echo "ENABLING SAMPLE APP ON PORT 8080 VIA PROXY" 46 | echo "VISIT http://localhost:8080 TO ACCESS THE APPLICATION OR PRESS CTRL+C TO EXIT" 47 | gcloud beta run services proxy spring-java-cloud-run --port=8080 48 | -------------------------------------------------------------------------------- /examples/spring/src/main/java/com/google/cloud/opentelemetry/example/spring/AppController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.example.spring; 17 | 18 | import io.opentelemetry.api.metrics.LongCounter; 19 | import io.opentelemetry.api.metrics.Meter; 20 | import io.opentelemetry.api.trace.Span; 21 | import io.opentelemetry.api.trace.Tracer; 22 | import io.opentelemetry.context.Scope; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.web.bind.annotation.GetMapping; 25 | import org.springframework.web.bind.annotation.RestController; 26 | 27 | @RestController 28 | public class AppController { 29 | private final LongCounter counterGreeting; 30 | private final LongCounter counterHome; 31 | private final Tracer tracer; 32 | 33 | @Autowired 34 | public AppController(Meter meter, Tracer tracer) { 35 | counterGreeting = 36 | meter 37 | .counterBuilder("greeting_counter") 38 | .setDescription("Hit /greeting endpoint") 39 | .setUnit("1") 40 | .build(); 41 | counterHome = 42 | meter 43 | .counterBuilder("home_counter") 44 | .setDescription("Hit root endpoint") 45 | .setUnit("1") 46 | .build(); 47 | this.tracer = tracer; 48 | } 49 | 50 | @GetMapping("/greeting") 51 | public String greeting() { 52 | Span span = tracer.spanBuilder("greeting_call").startSpan(); 53 | try (Scope scope = span.makeCurrent()) { 54 | span.addEvent("Event A"); 55 | span.setAttribute("test_api", true); 56 | counterGreeting.add(1); 57 | } finally { 58 | span.end(); 59 | } 60 | return "Hello World"; 61 | } 62 | 63 | @GetMapping("/") 64 | public String home() { 65 | counterHome.add(1); 66 | return "Welcome to Spring Demo"; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /examples/spring/src/main/java/com/google/cloud/opentelemetry/example/spring/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.example.spring; 17 | 18 | import org.springframework.boot.SpringApplication; 19 | import org.springframework.boot.autoconfigure.SpringBootApplication; 20 | 21 | @SpringBootApplication 22 | public class Main { 23 | public static void main(String[] args) { 24 | SpringApplication.run(Main.class, args); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /examples/spring/src/main/java/com/google/cloud/opentelemetry/example/spring/OpenTelemetryConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.example.spring; 17 | 18 | import io.opentelemetry.api.metrics.Meter; 19 | import io.opentelemetry.api.trace.Tracer; 20 | import io.opentelemetry.sdk.OpenTelemetrySdk; 21 | import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; 22 | import org.springframework.context.annotation.Bean; 23 | import org.springframework.context.annotation.Configuration; 24 | 25 | @Configuration 26 | public class OpenTelemetryConfiguration { 27 | 28 | private static final String INSTRUMENTATION_SCOPE_NAME = "spring-demo"; 29 | private static final String INSTRUMENTATION_VERSION = "semver:1.0.0"; 30 | 31 | @Bean 32 | public OpenTelemetrySdk getOpenTelemetrySdk() { 33 | return AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk(); 34 | } 35 | 36 | @Bean 37 | public Tracer getTracer(OpenTelemetrySdk openTelemetrySdk) { 38 | return openTelemetrySdk 39 | .tracerBuilder(INSTRUMENTATION_SCOPE_NAME) 40 | .setInstrumentationVersion(INSTRUMENTATION_VERSION) 41 | .build(); 42 | } 43 | 44 | @Bean 45 | public Meter getMeter(OpenTelemetrySdk openTelemetrySdk) { 46 | return openTelemetrySdk 47 | .meterBuilder(INSTRUMENTATION_SCOPE_NAME) 48 | .setInstrumentationVersion(INSTRUMENTATION_VERSION) 49 | .build(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /examples/spring/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG 2 | spring.application.name=gcp-otel-spring-demo 3 | -------------------------------------------------------------------------------- /examples/trace/README.md: -------------------------------------------------------------------------------- 1 | ### Running the example to export traces to Google Cloud 2 | 3 | You can run this example to generate sample traces on any Google Cloud project. 4 | 5 | #### Prerequisites 6 | 7 | ##### Get Google Cloud Credentials on your machine 8 | 9 | ```shell 10 | gcloud auth application-default login 11 | ``` 12 | Executing this command will save your application credentials to default path which will depend on the type of machine - 13 | - Linux, macOS: `$HOME/.config/gcloud/application_default_credentials.json` 14 | - Windows: `%APPDATA%\gcloud\application_default_credentials.json` 15 | 16 | ##### Export the Google Cloud Project ID to `GOOGLE_CLOUD_PROJECT` environment variable: 17 | 18 | ```shell 19 | export GOOGLE_CLOUD_PROJECT="my-awesome-gcp-project-id" 20 | ``` 21 | 22 | #### Run the example 23 | 24 | You can run the example application via gradle. From the project root: 25 | 26 | ```shell 27 | cd examples/trace/ && gradle run 28 | ``` 29 | 30 | You should now see the exported traces in your Google Cloud project. -------------------------------------------------------------------------------- /examples/trace/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | plugins { 17 | id 'java' 18 | id 'application' 19 | id 'com.google.cloud.tools.jib' 20 | } 21 | 22 | mainClassName = 'com.google.cloud.opentelemetry.example.trace.TraceExporterExample' 23 | 24 | description = 'Examples for Cloud Trace Exporter' 25 | 26 | dependencies { 27 | implementation(libraries.opentelemetry_api) 28 | implementation(libraries.opentelemetry_sdk) 29 | implementation(libraries.google_cloud_trace) 30 | implementation project(':exporter-trace') 31 | runtimeOnly(libraries.opentelemetry_gcp_resources) 32 | 33 | testImplementation(testLibraries.opentelemetry_sdk_testing) 34 | testImplementation(testLibraries.mockito) 35 | testImplementation(testLibraries.junit5) 36 | testRuntimeOnly(testLibraries.junit5_runtime) 37 | } 38 | 39 | test { 40 | // Required to discover JUnit 5 tests 41 | useJUnitPlatform() 42 | } 43 | 44 | // Set Docker image path here, e.g. using Google Container Registry or Docker Hub 45 | // https://github.com/GoogleContainerTools/jib/tree/master/jib-gradle-plugin#configuration 46 | jib { 47 | from.image = 'gcr.io/distroless/java-debian10:11' 48 | containerizingMode = 'packaged' 49 | } -------------------------------------------------------------------------------- /examples/trace/src/test/java/com/google/cloud/opentelemetry/example/trace/TraceExporterExampleTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.example.trace; 17 | 18 | import static org.junit.jupiter.api.Assertions.assertEquals; 19 | import static org.junit.jupiter.api.Assertions.assertFalse; 20 | 21 | import io.opentelemetry.api.common.AttributeKey; 22 | import io.opentelemetry.sdk.OpenTelemetrySdk; 23 | import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; 24 | import io.opentelemetry.sdk.trace.SdkTracerProvider; 25 | import io.opentelemetry.sdk.trace.data.SpanData; 26 | import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; 27 | import java.util.List; 28 | import org.junit.jupiter.api.AfterEach; 29 | import org.junit.jupiter.api.BeforeEach; 30 | import org.junit.jupiter.api.Test; 31 | 32 | class TraceExporterExampleTest { 33 | 34 | private OpenTelemetrySdk testOTelSdk; 35 | private InMemorySpanExporter testInMemorySpanExporter; 36 | 37 | @BeforeEach 38 | public void setupOTelSdk() { 39 | testInMemorySpanExporter = InMemorySpanExporter.create(); 40 | SdkTracerProvider testTracerProvider = 41 | SdkTracerProvider.builder() 42 | .addSpanProcessor(SimpleSpanProcessor.create(testInMemorySpanExporter)) 43 | .build(); 44 | 45 | testOTelSdk = OpenTelemetrySdk.builder().setTracerProvider(testTracerProvider).build(); 46 | } 47 | 48 | @AfterEach 49 | public void cleanupOTelSdk() { 50 | testOTelSdk.close(); 51 | } 52 | 53 | @Test 54 | public void testMyUseCase() { 55 | TraceExporterExample.myUseCase(testOTelSdk, "test"); 56 | List spanItems = testInMemorySpanExporter.getFinishedSpanItems(); 57 | assertFalse(spanItems.isEmpty()); 58 | 59 | // assert on custom span attributes set by application 60 | spanItems.stream() 61 | .filter(spanData -> spanData.getName().equals("test")) 62 | .map(SpanData::getAttributes) 63 | .forEach( 64 | spanAttributes -> { 65 | assertEquals(true, spanAttributes.get(AttributeKey.booleanKey("test_span"))); 66 | assertEquals(3, spanAttributes.get(AttributeKey.longKey("work_loop"))); 67 | }); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /exporters/auto/gradle.properties: -------------------------------------------------------------------------------- 1 | release.qualifier=alpha 2 | release.enabled=true 3 | -------------------------------------------------------------------------------- /exporters/auto/src/main/java/com/google/cloud/opentelemetry/auto/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.auto; 17 | 18 | public class Constants { 19 | 20 | static final String CLOUD_TRACE_NAME = "google_cloud_trace"; 21 | static final String CLOUD_MONITORING_NAME = "google_cloud_monitoring"; 22 | } 23 | -------------------------------------------------------------------------------- /exporters/auto/src/main/java/com/google/cloud/opentelemetry/auto/GoogleCloudMetricExporterFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.auto; 17 | 18 | import com.google.auto.service.AutoService; 19 | import com.google.cloud.opentelemetry.metric.GoogleCloudMetricExporter; 20 | import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; 21 | import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; 22 | import io.opentelemetry.sdk.metrics.export.MetricExporter; 23 | 24 | @AutoService(ConfigurableMetricExporterProvider.class) 25 | public class GoogleCloudMetricExporterFactory implements ConfigurableMetricExporterProvider { 26 | @Override 27 | public MetricExporter createExporter(ConfigProperties config) { 28 | return GoogleCloudMetricExporter.createWithDefaultConfiguration(); 29 | } 30 | 31 | @Override 32 | public String getName() { 33 | return Constants.CLOUD_MONITORING_NAME; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /exporters/auto/src/main/java/com/google/cloud/opentelemetry/auto/GoogleCloudSpanExporterFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.auto; 17 | 18 | import com.google.auto.service.AutoService; 19 | import com.google.cloud.opentelemetry.trace.TraceExporter; 20 | import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; 21 | import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; 22 | import io.opentelemetry.sdk.trace.export.SpanExporter; 23 | 24 | @AutoService(ConfigurableSpanExporterProvider.class) 25 | public class GoogleCloudSpanExporterFactory implements ConfigurableSpanExporterProvider { 26 | 27 | @Override 28 | public SpanExporter createExporter(ConfigProperties config) { 29 | return TraceExporter.createWithDefaultConfiguration(); 30 | } 31 | 32 | @Override 33 | public String getName() { 34 | return Constants.CLOUD_TRACE_NAME; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /exporters/metrics/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | description = 'Cloud Monitoring Exporter for OpenTelemetry' 17 | 18 | dependencies { 19 | api(libraries.auto_value_annotations) 20 | api(libraries.slf4j) 21 | api(libraries.opentelemetry_api) 22 | api(libraries.google_cloud_core) 23 | api(libraries.google_cloud_monitoring) 24 | api(libraries.opentelemetry_sdk_metrics) 25 | annotationProcessor(libraries.auto_value) 26 | implementation(platform(libraries.google_cloud_bom)) 27 | implementation(platform(libraries.opentelemetry_bom)) 28 | implementation(project(':shared-resourcemapping')) 29 | implementation(libraries.opentelemetry_semconv) 30 | implementation(libraries.opentelemetry_semconv_incubating) 31 | testImplementation(testLibraries.junit) 32 | testImplementation(testLibraries.mockito) 33 | testImplementation(testLibraries.slf4j_simple) 34 | testImplementation(testLibraries.test_containers) 35 | testImplementation(testLibraries.opentelemetry_sdk_testing) 36 | } 37 | 38 | test.dependsOn ':shared-resourcemapping:shadowJar' 39 | -------------------------------------------------------------------------------- /exporters/metrics/gradle.properties: -------------------------------------------------------------------------------- 1 | release.enabled=true 2 | -------------------------------------------------------------------------------- /exporters/metrics/src/main/java/com/google/cloud/opentelemetry/metric/CloudMetricClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.metric; 17 | 18 | import com.google.api.MetricDescriptor; 19 | import com.google.monitoring.v3.CreateMetricDescriptorRequest; 20 | import com.google.monitoring.v3.ProjectName; 21 | import com.google.monitoring.v3.TimeSeries; 22 | import java.util.List; 23 | 24 | /** Wrapper interface for writing to Google Cloud Monitoring. */ 25 | public interface CloudMetricClient { 26 | /** 27 | * Construct a metric descriptor. 28 | * 29 | *

This informs Cloud Monitoring of label descriptions, metric descriptions, units, etc. 30 | */ 31 | MetricDescriptor createMetricDescriptor(CreateMetricDescriptorRequest request); 32 | 33 | /** 34 | * Send a time series to Cloud Monitoring. 35 | * 36 | * @param name The name of the project where we write the time series. 37 | * @param timeSeries The list of time series to write. 38 | *

Note: This can only take one point at per time series. 39 | */ 40 | void createTimeSeries(ProjectName name, List timeSeries); 41 | 42 | /** 43 | * Send a service time series to Cloud Monitoring. A service time series is a time series for a 44 | * metric from a Google Cloud service. This method should not be used for sending custom metrics. 45 | * 46 | * @param name The name of the project where we write the time series. 47 | * @param timeSeries The list of time series to write. 48 | *

Note: This can only take one point at per time series. 49 | */ 50 | void createServiceTimeSeries(ProjectName name, List timeSeries); 51 | 52 | /** Shutdown this client, cleaning up any resources. */ 53 | void shutdown(); 54 | } 55 | -------------------------------------------------------------------------------- /exporters/metrics/src/main/java/com/google/cloud/opentelemetry/metric/CloudMetricClientImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.metric; 17 | 18 | import com.google.api.MetricDescriptor; 19 | import com.google.cloud.monitoring.v3.MetricServiceClient; 20 | import com.google.monitoring.v3.CreateMetricDescriptorRequest; 21 | import com.google.monitoring.v3.ProjectName; 22 | import com.google.monitoring.v3.TimeSeries; 23 | import java.util.List; 24 | 25 | /** Directly talks to Cloud Monitoring. */ 26 | public final class CloudMetricClientImpl implements CloudMetricClient { 27 | private final MetricServiceClient metricServiceClient; 28 | 29 | public CloudMetricClientImpl(MetricServiceClient metricServiceClient) { 30 | this.metricServiceClient = metricServiceClient; 31 | } 32 | 33 | @Override 34 | public MetricDescriptor createMetricDescriptor(CreateMetricDescriptorRequest request) { 35 | return this.metricServiceClient.createMetricDescriptor(request); 36 | } 37 | 38 | @Override 39 | public void createTimeSeries(ProjectName name, List timeSeries) { 40 | this.metricServiceClient.createTimeSeries(name, timeSeries); 41 | } 42 | 43 | @Override 44 | public void createServiceTimeSeries(ProjectName name, List timeSeries) { 45 | this.metricServiceClient.createServiceTimeSeries(name, timeSeries); 46 | } 47 | 48 | @Override 49 | public void shutdown() { 50 | this.metricServiceClient.shutdown(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /exporters/metrics/src/main/java/com/google/cloud/opentelemetry/metric/MetricTimeSeriesBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.metric; 17 | 18 | import com.google.api.MetricDescriptor; 19 | import com.google.monitoring.v3.TimeSeries; 20 | import io.opentelemetry.sdk.metrics.data.DoublePointData; 21 | import io.opentelemetry.sdk.metrics.data.HistogramPointData; 22 | import io.opentelemetry.sdk.metrics.data.LongPointData; 23 | import io.opentelemetry.sdk.metrics.data.MetricData; 24 | import java.util.Collection; 25 | import java.util.List; 26 | 27 | /** An interface that denotes how we build our API calls from metric data. */ 28 | public interface MetricTimeSeriesBuilder { 29 | /** Records a LongPoint of the given metric. */ 30 | void recordPoint(MetricData metric, LongPointData point); 31 | /** Records a DoublePoint of the given metric. */ 32 | void recordPoint(MetricData metric, DoublePointData point); 33 | /** Records a DoubleHistogramPointData for the given metric. */ 34 | void recordPoint(MetricData metric, HistogramPointData point); 35 | 36 | /** The set of descriptors associated with the current time series. */ 37 | Collection getDescriptors(); 38 | /** The set (unique by metric+label) of time series that were built. */ 39 | List getTimeSeries(); 40 | } 41 | -------------------------------------------------------------------------------- /exporters/metrics/src/main/java/com/google/cloud/opentelemetry/metric/MetricWithLabels.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.metric; 17 | 18 | import io.opentelemetry.api.common.Attributes; 19 | import java.util.Objects; 20 | 21 | class MetricWithLabels { 22 | private final String metricType; 23 | private final Attributes attributes; 24 | 25 | MetricWithLabels(String metricType, Attributes attributes) { 26 | this.metricType = metricType; 27 | this.attributes = attributes; 28 | } 29 | 30 | @Override 31 | public boolean equals(Object o) { 32 | if (this == o) { 33 | return true; 34 | } 35 | if (o == null || getClass() != o.getClass()) { 36 | return false; 37 | } 38 | MetricWithLabels that = (MetricWithLabels) o; 39 | return Objects.equals(metricType, that.metricType) 40 | && Objects.equals(attributes, that.attributes); 41 | } 42 | 43 | @Override 44 | public int hashCode() { 45 | return Objects.hash(metricType, attributes); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /exporters/metrics/src/main/java/com/google/cloud/opentelemetry/metric/MonitoredResourceDescription.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.metric; 17 | 18 | import java.util.Collections; 19 | import java.util.Set; 20 | import javax.annotation.concurrent.Immutable; 21 | 22 | /** 23 | * This class holds the mapping between Google Cloud's monitored resource type and the labels for 24 | * identifying the given monitored resource type. 25 | */ 26 | @Immutable 27 | public final class MonitoredResourceDescription { 28 | private final String mrType; 29 | private final Set mrLabels; 30 | 31 | /** 32 | * Public constructor. 33 | * 34 | * @param mrType The monitored resource type for which the mapping is being specified. 35 | * @param mrLabels A set of labels which uniquely identify a given monitored resource. 36 | */ 37 | public MonitoredResourceDescription(String mrType, Set mrLabels) { 38 | this.mrType = mrType; 39 | this.mrLabels = Collections.unmodifiableSet(mrLabels); 40 | } 41 | 42 | /** 43 | * Returns the set of labels used to identify the monitored resource represented in this mapping. 44 | * 45 | * @return Immutable set of labels that map to the specified monitored resource type. 46 | */ 47 | public Set getMonitoredResourceLabels() { 48 | return mrLabels; 49 | } 50 | 51 | /** 52 | * The type of the monitored resource for which mapping is defined. 53 | * 54 | * @return The type of the monitored resource. 55 | */ 56 | public String getMonitoredResourceType() { 57 | return mrType; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /exporters/metrics/src/main/java/com/google/cloud/opentelemetry/metric/NoopMetricExporter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.metric; 17 | 18 | import io.opentelemetry.sdk.common.CompletableResultCode; 19 | import io.opentelemetry.sdk.metrics.InstrumentType; 20 | import io.opentelemetry.sdk.metrics.data.AggregationTemporality; 21 | import io.opentelemetry.sdk.metrics.data.MetricData; 22 | import io.opentelemetry.sdk.metrics.export.MetricExporter; 23 | import java.util.Collection; 24 | import javax.annotation.Nonnull; 25 | 26 | /** A noop implementation of {@link MetricExporter}. */ 27 | final class NoopMetricExporter implements MetricExporter { 28 | @Override 29 | public CompletableResultCode export(@Nonnull Collection metrics) { 30 | return CompletableResultCode.ofSuccess(); 31 | } 32 | 33 | @Override 34 | public CompletableResultCode flush() { 35 | return CompletableResultCode.ofSuccess(); 36 | } 37 | 38 | @Override 39 | public CompletableResultCode shutdown() { 40 | return CompletableResultCode.ofSuccess(); 41 | } 42 | 43 | @Override 44 | public AggregationTemporality getAggregationTemporality(@Nonnull InstrumentType instrumentType) { 45 | return AggregationTemporality.CUMULATIVE; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /exporters/metrics/src/test/java/com/google/cloud/opentelemetry/metric/MockServerStartupException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.metric; 17 | 18 | public class MockServerStartupException extends RuntimeException { 19 | public MockServerStartupException(String message, Throwable cause) { 20 | super(message, cause); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /exporters/trace/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | description = 'Cloud Trace Exporter for OpenTelemetry' 17 | 18 | dependencies { 19 | api(libraries.auto_value_annotations) 20 | api(libraries.slf4j) 21 | api(libraries.opentelemetry_api) 22 | api(libraries.opentelemetry_sdk) 23 | api(libraries.google_cloud_core) 24 | api(libraries.google_cloud_trace) 25 | api(libraries.google_cloud_trace_grpc) 26 | annotationProcessor(libraries.auto_value) 27 | implementation platform(libraries.google_cloud_bom) 28 | implementation platform(libraries.opentelemetry_bom) 29 | implementation(libraries.opentelemetry_semconv) 30 | implementation(libraries.opentelemetry_semconv_incubating) 31 | implementation(project(':shared-resourcemapping')) 32 | testImplementation(testLibraries.junit) 33 | testImplementation(testLibraries.opentelemetry_sdk_testing) 34 | testImplementation(testLibraries.test_containers) 35 | testImplementation(testLibraries.mockito) 36 | testAnnotationProcessor(libraries.auto_value) 37 | } 38 | 39 | // Configure a version.properties file that writes important versions. 40 | ext.propertiesDir = "build/generated/properties/com/google/cloud/opentelemetry/trace" 41 | sourceSets { 42 | main { 43 | output.dir("build/generated/properties", builtBy: 'generateVersionResource') 44 | } 45 | } 46 | task generateVersionResource { 47 | doLast { 48 | def folder = file(propertiesDir) 49 | folder.mkdirs() 50 | def propertiesFile = new File(folder.getAbsolutePath(), "version.properties") 51 | propertiesFile.write("exporter.version=${project.version}") 52 | } 53 | } 54 | 55 | test.dependsOn ':shared-resourcemapping:shadowJar' 56 | -------------------------------------------------------------------------------- /exporters/trace/gradle.properties: -------------------------------------------------------------------------------- 1 | release.enabled=true 2 | -------------------------------------------------------------------------------- /exporters/trace/src/main/java/com/google/cloud/opentelemetry/trace/CloudTraceClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.trace; 17 | 18 | import com.google.devtools.cloudtrace.v2.ProjectName; 19 | import com.google.devtools.cloudtrace.v2.Span; 20 | import java.util.List; 21 | 22 | public interface CloudTraceClient { 23 | void batchWriteSpans(ProjectName name, List spans); 24 | 25 | void shutdown(); 26 | } 27 | -------------------------------------------------------------------------------- /exporters/trace/src/main/java/com/google/cloud/opentelemetry/trace/CloudTraceClientImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.trace; 17 | 18 | import com.google.cloud.trace.v2.TraceServiceClient; 19 | import com.google.devtools.cloudtrace.v2.ProjectName; 20 | import com.google.devtools.cloudtrace.v2.Span; 21 | import java.util.List; 22 | 23 | public class CloudTraceClientImpl implements CloudTraceClient { 24 | private final TraceServiceClient traceServiceClient; 25 | 26 | public CloudTraceClientImpl(TraceServiceClient traceServiceClient) { 27 | this.traceServiceClient = traceServiceClient; 28 | } 29 | 30 | public final void batchWriteSpans(ProjectName name, List spans) { 31 | this.traceServiceClient.batchWriteSpans(name, spans); 32 | } 33 | 34 | public final void shutdown() { 35 | this.traceServiceClient.shutdown(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /exporters/trace/src/main/java/com/google/cloud/opentelemetry/trace/NoopSpanExporter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.trace; 17 | 18 | import io.opentelemetry.sdk.common.CompletableResultCode; 19 | import io.opentelemetry.sdk.trace.data.SpanData; 20 | import io.opentelemetry.sdk.trace.export.SpanExporter; 21 | import java.util.Collection; 22 | import javax.annotation.Nonnull; 23 | 24 | /** A noop implementation of a {@link SpanExporter}. */ 25 | final class NoopSpanExporter implements SpanExporter { 26 | 27 | NoopSpanExporter() { 28 | // prevent explicit public call to default constructor 29 | } 30 | 31 | /** 32 | * Noop implementation for exporting spans. 33 | * 34 | * @param spans The {@link Collection} of {@link SpanData} that need to be exported. 35 | * @return a success result code indicated via {@link CompletableResultCode#ofSuccess()}. 36 | */ 37 | @Override 38 | public CompletableResultCode export(@Nonnull Collection spans) { 39 | return CompletableResultCode.ofSuccess(); 40 | } 41 | 42 | /** 43 | * Noop implementation for flushing current spans. 44 | * 45 | * @return a success result code indicated via {@link CompletableResultCode#ofSuccess()}. 46 | */ 47 | @Override 48 | public CompletableResultCode flush() { 49 | return CompletableResultCode.ofSuccess(); 50 | } 51 | 52 | /** 53 | * Noop implementation for shutting down the current exporter. 54 | * 55 | * @return a success result code indicated via {@link CompletableResultCode#ofSuccess()}. 56 | */ 57 | @Override 58 | public CompletableResultCode shutdown() { 59 | return CompletableResultCode.ofSuccess(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /exporters/trace/src/main/java/com/google/cloud/opentelemetry/trace/TraceVersions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.trace; 17 | 18 | import static io.opentelemetry.semconv.TelemetryAttributes.TELEMETRY_SDK_VERSION; 19 | 20 | import io.opentelemetry.sdk.resources.Resource; 21 | import java.util.Properties; 22 | import javax.annotation.Nullable; 23 | 24 | /** Helper to grab version numbers from builds. */ 25 | public class TraceVersions { 26 | 27 | public static final String SDK_VERSION = readSdkVersion(); 28 | public static final String EXPORTER_VERSION = readVersion(); 29 | 30 | @Nullable 31 | private static String readSdkVersion() { 32 | return Resource.getDefault().getAttributes().get(TELEMETRY_SDK_VERSION); 33 | } 34 | 35 | @Nullable 36 | private static String readVersion() { 37 | Properties properties = new Properties(); 38 | try { 39 | properties.load( 40 | TraceVersions.class.getResourceAsStream( 41 | "/com/google/cloud/opentelemetry/trace/version.properties")); 42 | } catch (Exception e) { 43 | // we left the attribute empty 44 | return "unknown"; 45 | } 46 | String result = properties.getProperty("exporter.version"); 47 | if (result != null && result.endsWith("-SNAPSHOT")) { 48 | // Lame hack: Mock server doesn't allow interesting version strings. 49 | return result.substring(0, result.length() - 9); 50 | } 51 | return result; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /exporters/trace/src/test/java/com/google/cloud/opentelemetry/trace/MockCloudTraceClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.trace; 17 | 18 | import com.google.devtools.cloudtrace.v2.BatchWriteSpansRequest; 19 | import com.google.devtools.cloudtrace.v2.ProjectName; 20 | import com.google.devtools.cloudtrace.v2.Span; 21 | import com.google.devtools.cloudtrace.v2.TraceServiceGrpc; 22 | import io.grpc.Channel; 23 | import io.grpc.ManagedChannelBuilder; 24 | import java.util.List; 25 | 26 | // A simplified version of TraceServiceClient, used ONLY for testing purposes. 27 | class MockCloudTraceClient implements CloudTraceClient { 28 | 29 | private final TraceServiceGrpc.TraceServiceBlockingStub blockingStub; 30 | 31 | MockCloudTraceClient(String host, int port) { 32 | this(ManagedChannelBuilder.forAddress(host, port).usePlaintext()); 33 | } 34 | 35 | private MockCloudTraceClient(ManagedChannelBuilder channelBuilder) { 36 | Channel channel = channelBuilder.build(); 37 | blockingStub = TraceServiceGrpc.newBlockingStub(channel); 38 | } 39 | 40 | public final void batchWriteSpans(ProjectName name, List spans) { 41 | BatchWriteSpansRequest request = 42 | BatchWriteSpansRequest.newBuilder().setName(name.toString()).addAllSpans(spans).build(); 43 | blockingStub.batchWriteSpans(request); 44 | } 45 | 46 | // Empty because not being tested 47 | public final void shutdown() {} 48 | } 49 | -------------------------------------------------------------------------------- /exporters/trace/src/test/java/com/google/cloud/opentelemetry/trace/MockServerStartupException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.trace; 17 | 18 | public class MockServerStartupException extends RuntimeException { 19 | public MockServerStartupException(String message, Throwable cause) { 20 | super(message, cause); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /exporters/trace/src/test/java/com/google/cloud/opentelemetry/trace/TraceVersionsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.trace; 17 | 18 | import static org.junit.Assert.assertNotEquals; 19 | import static org.junit.Assert.assertNotNull; 20 | 21 | import org.junit.Test; 22 | import org.junit.runner.RunWith; 23 | import org.junit.runners.JUnit4; 24 | 25 | @RunWith(JUnit4.class) 26 | public class TraceVersionsTest { 27 | 28 | @Test 29 | public void findsExporterVersion() { 30 | assertNotNull(TraceVersions.EXPORTER_VERSION); 31 | assertNotEquals("unknown", TraceVersions.EXPORTER_VERSION); 32 | } 33 | 34 | @Test 35 | public void findsSdkVersion() { 36 | assertNotNull(TraceVersions.SDK_VERSION); 37 | assertNotEquals("unknown", TraceVersions.SDK_VERSION); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoogleCloudPlatform/opentelemetry-operations-java/4a5876da5552cdd5207e0b71011b85327265574b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /propagators/README.md: -------------------------------------------------------------------------------- 1 | # Propagators 2 | 3 | This directory contains various TextMapPropagator extensions for the OpenTelemetry SDK. -------------------------------------------------------------------------------- /propagators/gcp/README.md: -------------------------------------------------------------------------------- 1 | # Google X-Cloud-Trace-Context propagtors 2 | 3 | [![Maven Central][maven-image]][maven-url] 4 | 5 | *NOTE: While OpenTelemetry SDK is stable, the Autoconfigure SDK extension is still Alpha in OpenTelemetry, and some features are not guaranteed to work across versions.* 6 | 7 | This module allows attaching trace context with Google Cloud's [X-Cloud-Trace-Context header](https://cloud.google.com/trace/docs/setup#force-trace). 8 | 9 | 10 | ## Setup 11 | 12 | The preferred mechanism is to use the [SDK autoconfigure extension](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure). 13 | 14 | - Add a runtime dependency from your java project to this library. 15 | - You can now use `oneway-gcp` and `gcp` as viable propagation strings in [the `otel.propagators` flag](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure#propagator) 16 | - When using the autoinstrumentation agent, you also need to pas our propagators to the autoinstrumentation "extension" classpath. This can be done through the `otel.javaagent.extensions` flag. 17 | ``` 18 | -Dotel.javaagent.extensions=/path/to/downloaded/gcp-propagator.jar 19 | ``` 20 | For a complete example see [here](https://github.com/GoogleCloudPlatform/opentelemetry-operations-java/blob/main/examples/autoinstrument/build.gradle#L63). 21 | 22 | ## Manual Configuration 23 | 24 | Instead of configuring with the SDK autoconfigure extension, you can instead directly register this propagator as 25 | follows: 26 | 27 | ```java 28 | public class MyMain { 29 | public static void main(String[] args) { 30 | ContextPropagators propagators = ContextPropagators.create( 31 | TextMapPropagator.composite( 32 | W3CTraceContextPropagator.getInstance(), 33 | new XCloudTraceContextPropagator(/*oneway=*/true))); 34 | OpenTelemetrySdk sdk = OpenTelemetrySdk.builder() 35 | .setPropagators(propagators) 36 | // Other setup 37 | .build(); 38 | } 39 | } 40 | ``` 41 | 42 | [maven-image]: https://img.shields.io/maven-central/v/com.google.cloud.opentelemetry/propagators-gcp?color=dark-green 43 | [maven-url]: https://maven-badges.herokuapp.com/maven-central/com.google.cloud.opentelemetry/propagators-gcp -------------------------------------------------------------------------------- /propagators/gcp/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | description = 'Google Cloud Trace Context propogators' 17 | 18 | dependencies { 19 | api(libraries.auto_service_annotations) 20 | annotationProcessor(libraries.auto_service) 21 | implementation(libraries.opentelemetry_api) 22 | implementation(libraries.opentelemetry_autoconfigure_spi) 23 | implementation platform(libraries.opentelemetry_bom) 24 | testImplementation(testLibraries.assertj) 25 | testImplementation(testLibraries.junit) 26 | testImplementation(testLibraries.opentelemetry_sdk_testing) 27 | testImplementation(libraries.opentelemetry_sdk_autoconf) 28 | } 29 | -------------------------------------------------------------------------------- /propagators/gcp/gradle.properties: -------------------------------------------------------------------------------- 1 | release.qualifier=alpha 2 | release.enabled=true 3 | -------------------------------------------------------------------------------- /propagators/gcp/src/main/java/com/google/cloud/opentelemetry/propagators/OneWayXCloudTraceConfigurablePropagatorProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.propagators; 17 | 18 | import com.google.auto.service.AutoService; 19 | import io.opentelemetry.context.propagation.TextMapPropagator; 20 | import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; 21 | import io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider; 22 | 23 | /** 24 | * Autoconfigurable propagator for OpenTelemetry Java SDK that only attaches to existing 25 | * X-Cloud-Trace-Context traces and does not create downstream ones. 26 | * 27 | *

Note: This is the preferred mechanism of propagation as X-Cloud-Trace-Context sampling flag 28 | * behaves subtly different from expectations in both w3c traceparent *and* opentelemetry 29 | * propagation. 30 | */ 31 | @AutoService(ConfigurablePropagatorProvider.class) 32 | public class OneWayXCloudTraceConfigurablePropagatorProvider 33 | implements ConfigurablePropagatorProvider { 34 | @Override 35 | public TextMapPropagator getPropagator(ConfigProperties config) { 36 | return new XCloudTraceContextPropagator(true); 37 | } 38 | 39 | @Override 40 | public String getName() { 41 | return "oneway-gcp"; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /propagators/gcp/src/main/java/com/google/cloud/opentelemetry/propagators/XCloudTraceConfigurablePropagatorProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.propagators; 17 | 18 | import com.google.auto.service.AutoService; 19 | import io.opentelemetry.context.propagation.TextMapPropagator; 20 | import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; 21 | import io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider; 22 | 23 | /** 24 | * Autoconfigurable propagator for OpenTelemetry Java SDK that will make use of 25 | * X-Cloud-Trace-Context header. 26 | * 27 | *

Note: This is *NOT* the recommended propagation as X-Cloud-Trace-Context because the sampling 28 | * flag behaves subtly different from expectations in both w3c traceparent *and* opentelemetry 29 | * propagation. 30 | * 31 | * @see OneWayXCloudTraceConfigurablePropagatorProvider 32 | */ 33 | @AutoService(ConfigurablePropagatorProvider.class) 34 | public class XCloudTraceConfigurablePropagatorProvider implements ConfigurablePropagatorProvider { 35 | @Override 36 | public TextMapPropagator getPropagator(ConfigProperties config) { 37 | return new XCloudTraceContextPropagator(false); 38 | } 39 | 40 | @Override 41 | public String getName() { 42 | return "gcp"; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /shared/resourcemapping/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 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 | plugins { 17 | id "maven-publish" 18 | id "com.github.johnrengelman.shadow" 19 | } 20 | 21 | 22 | description = 'Resource helper utilites for GCP within OpenTelemetry' 23 | 24 | dependencies { 25 | api(libraries.auto_value_annotations) 26 | api(libraries.opentelemetry_api) 27 | api(libraries.opentelemetry_sdk_common) 28 | annotationProcessor(libraries.auto_value) 29 | implementation(libraries.opentelemetry_semconv) 30 | implementation(libraries.opentelemetry_semconv_incubating) 31 | implementation platform(libraries.opentelemetry_bom) 32 | testImplementation(testLibraries.junit5) 33 | testImplementation(testLibraries.junit5_params) 34 | testRuntimeOnly(testLibraries.junit5_runtime) 35 | testImplementation(libraries.opentelemetry_semconv) 36 | } 37 | 38 | shadowJar{ 39 | archiveClassifier.set('') 40 | relocate 'io.opentelemetry.semconv', 'com.google.cloud.opentelemetry.shadow.semconv' 41 | dependencies { 42 | exclude(dependency(libraries.opentelemetry_api)) 43 | exclude(dependency(libraries.auto_value_annotations)) 44 | exclude(dependency(libraries.opentelemetry_sdk_common)) 45 | exclude(dependency(libraries.opentelemetry_context)) 46 | } 47 | mergeServiceFiles() 48 | } 49 | 50 | publishing { 51 | publications { 52 | maven(MavenPublication) { publication -> 53 | from project.shadow.component(publication) 54 | artifact sourcesJar 55 | artifact javadocJar 56 | components.java.withVariantsFromConfiguration(configurations.runtimeElements) { 57 | skip() 58 | } 59 | } 60 | } 61 | } 62 | 63 | test { 64 | // required for discovering JUnit 5 tests 65 | useJUnitPlatform() 66 | } 67 | 68 | // This is to fix the explicit dependency error which comes when publishing via the `candidate` task 69 | publishMavenPublicationToMavenRepository.dependsOn jar 70 | signMavenPublication.dependsOn jar 71 | -------------------------------------------------------------------------------- /shared/resourcemapping/gradle.properties: -------------------------------------------------------------------------------- 1 | release.enabled=true 2 | shadowed=true -------------------------------------------------------------------------------- /shared/resourcemapping/src/main/java/com/google/cloud/opentelemetry/resource/GcpResource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.resource; 17 | 18 | import com.google.auto.value.AutoValue; 19 | 20 | /** 21 | * A representation of GCP resource types. 22 | * 23 | *

Unlike pure OpenTelemetry, GCP adds a "type" to a raw bundle of labels. 24 | */ 25 | @AutoValue 26 | public abstract class GcpResource { 27 | /** The type of resource, e.g. gce_instance. */ 28 | public abstract String getResourceType(); 29 | /** The labels associated with the resource. */ 30 | public abstract ResourceLabels getResourceLabels(); 31 | 32 | static Builder builder() { 33 | return new AutoValue_GcpResource.Builder(); 34 | } 35 | 36 | @AutoValue.Builder 37 | abstract static class Builder { 38 | abstract Builder setResourceType(String value); 39 | 40 | abstract ResourceLabels.Builder resourceLabelsBuilder(); 41 | 42 | final Builder addResourceLabels(String key, String value) { 43 | resourceLabelsBuilder().put(key, value); 44 | return this; 45 | } 46 | 47 | abstract GcpResource build(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /shared/resourcemapping/src/main/java/com/google/cloud/opentelemetry/resource/ResourceLabels.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.cloud.opentelemetry.resource; 17 | 18 | import com.google.auto.value.AutoValue; 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | /** 23 | * A storage of key-value pairs. 24 | * 25 | *

This is a workaround to get AutoValue/AutoBuilder convenience without a full dependency on 26 | * Guice for collections. 27 | */ 28 | @AutoValue 29 | public abstract class ResourceLabels { 30 | public abstract Map getLabels(); 31 | 32 | static Builder builder() { 33 | return new Builder(); 34 | } 35 | 36 | Builder toBuilder() { 37 | return new Builder(this); 38 | } 39 | 40 | static final class Builder { 41 | private Map labels; 42 | 43 | public Builder() { 44 | this.labels = new HashMap<>(); 45 | } 46 | 47 | Builder(ResourceLabels labels) { 48 | this.labels = new HashMap<>(labels.getLabels()); 49 | } 50 | 51 | public Builder put(String key, String value) { 52 | this.labels.put(key, value); 53 | return this; 54 | } 55 | 56 | public ResourceLabels build() { 57 | return new AutoValue_ResourceLabels(labels); 58 | } 59 | } 60 | } 61 | --------------------------------------------------------------------------------