Skip to content

Commit c671829

Browse files
authored
Update otlpmetrics sample (#410)
* Udpate otlptrace example documentation * Defer adding quota project header to auth library * Add code to show token dynamic refresh * Fix stylecheck
1 parent 517521b commit c671829

File tree

5 files changed

+33
-43
lines changed

5 files changed

+33
-43
lines changed

examples/otlpmetric/README.md

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,15 @@ Executing this command will save your application credentials to default path wh
1111
- Linux, macOS: `$HOME/.config/gcloud/application_default_credentials.json`
1212
- Windows: `%APPDATA%\gcloud\application_default_credentials.json`
1313

14-
Next, set your endpoint with the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable:
15-
16-
```shell
17-
export OTEL_EXPORTER_OTLP_ENDPOINT="http://your-endpoint:port"
18-
```
19-
2014
Next, update [`build.gradle`](build.grade) to set the following:
2115

2216
```
2317
'-Dotel.resource.attributes=gcp.project_id=<YOUR_PROJECT_ID>,
24-
'-Dotel.exporter.otlp.headers=X-Goog-User-Project=<YOUR_QUOTA_PROJECT>',
2518
# Optional - if you want to export using gRPC protocol
2619
'-Dotel.exporter.otlp.protocol=grpc',
2720
```
2821

2922
Finally, to run the sample from the project root:
30-
3123
```
32-
cd examples/otlpmetric && gradle run
24+
./gradlew :examples-otlpmetric:run
3325
```

examples/otlpmetric/build.gradle

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,19 +29,22 @@ dependencies {
2929
implementation(libraries.opentelemetry_sdk)
3030
implementation(libraries.opentelemetry_otlp_exporter)
3131
implementation(libraries.opentelemetry_sdk_autoconf)
32+
implementation(libraries.opentelemetry_gcp_resources)
3233
implementation(libraries.google_auth)
3334
}
3435

35-
// Provide headers from env variable
36-
// export OTEL_EXPORTER_OTLP_ENDPOINT="http://path/to/yourendpoint:port"
3736
def autoconf_config = [
38-
'-Dotel.resource.attributes=gcp.project_id=<YOUR_PROJECT>',
39-
'-Dotel.exporter.otlp.headers=X-Goog-User-Project=<YOUR_QUOTA_PROJECT>',
37+
'-Dotel.exporter.otlp.endpoint=https://telemetry.googleapis.com',
38+
'-Dotel.resource.attributes=gcp.project_id=<YOUR_PROJECT_ID>',
4039
'-Dotel.metrics.exporter=otlp',
40+
'-Dotel.logs.exporter=none',
41+
'-Dotel.traces.exporter=none',
42+
'-Dotel.service.name=otlpmetrics-example',
4143
'-Dotel.exporter.otlp.protocol=http/protobuf',
4244
'-Dotel.java.global-autoconfigure.enabled=true',
4345
]
4446

4547
application {
48+
mainClassName = 'com.google.cloud.opentelemetry.example.otlpmetric.OTLPMetricExample'
4649
applicationDefaultJvmArgs = autoconf_config
4750
}

examples/otlpmetric/src/main/java/com/google/cloud/opentelemetry/example/otlpmetric/OTLPMetricExample.java

Lines changed: 23 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,14 @@
1818
import com.google.auth.oauth2.GoogleCredentials;
1919
import io.opentelemetry.api.metrics.LongCounter;
2020
import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter;
21-
import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder;
2221
import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter;
23-
import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder;
2422
import io.opentelemetry.sdk.OpenTelemetrySdk;
2523
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
2624
import io.opentelemetry.sdk.common.CompletableResultCode;
2725
import io.opentelemetry.sdk.metrics.export.MetricExporter;
2826
import java.io.IOException;
27+
import java.util.HashMap;
28+
import java.util.Map;
2929
import java.util.Random;
3030
import java.util.concurrent.TimeUnit;
3131

@@ -49,39 +49,35 @@ private static OpenTelemetrySdk setupMetricExporter() throws IOException {
4949
}
5050

5151
// Modifies the metric exporter initially auto-configured using environment variables
52-
// Note: This adds static authorization headers which are set only at initialization time.
53-
// This will stop working after the token expires, since the token is not refreshed.
52+
// This will invoke the header supplier function to compute the headers, which takes care of the
53+
// refresh.
5454
private static MetricExporter addAuthorizationHeaders(
5555
MetricExporter exporter, GoogleCredentials credentials) {
5656
if (exporter instanceof OtlpHttpMetricExporter) {
57-
try {
58-
credentials.refreshIfExpired();
59-
OtlpHttpMetricExporterBuilder builder =
60-
((OtlpHttpMetricExporter) exporter)
61-
.toBuilder()
62-
.addHeader(
63-
"Authorization", "Bearer " + credentials.getAccessToken().getTokenValue());
64-
65-
return builder.build();
66-
} catch (IOException e) {
67-
System.out.println("error:" + e.getMessage());
68-
}
57+
return ((OtlpHttpMetricExporter) exporter)
58+
.toBuilder().setHeaders(() -> getRequiredHeaderMap(credentials)).build();
6959
} else if (exporter instanceof OtlpGrpcMetricExporter) {
70-
try {
71-
credentials.refreshIfExpired();
72-
OtlpGrpcMetricExporterBuilder builder =
73-
((OtlpGrpcMetricExporter) exporter)
74-
.toBuilder()
75-
.addHeader(
76-
"Authorization", "Bearer " + credentials.getAccessToken().getTokenValue());
77-
return builder.build();
78-
} catch (IOException e) {
79-
throw new RuntimeException(e);
80-
}
60+
return ((OtlpGrpcMetricExporter) exporter)
61+
.toBuilder().setHeaders(() -> getRequiredHeaderMap(credentials)).build();
8162
}
8263
return exporter;
8364
}
8465

66+
private static Map<String, String> getRequiredHeaderMap(GoogleCredentials credentials) {
67+
Map<String, String> gcpHeaders = new HashMap<>();
68+
try {
69+
credentials.refreshIfExpired();
70+
} catch (IOException e) {
71+
throw new RuntimeException(e);
72+
}
73+
gcpHeaders.put("Authorization", "Bearer " + credentials.getAccessToken().getTokenValue());
74+
String configuredQuotaProjectId = credentials.getQuotaProjectId();
75+
if (configuredQuotaProjectId != null && !configuredQuotaProjectId.isEmpty()) {
76+
gcpHeaders.put("x-goog-user-project", configuredQuotaProjectId);
77+
}
78+
return gcpHeaders;
79+
}
80+
8581
private static void myUseCase() {
8682
LongCounter counter =
8783
openTelemetrySdk
@@ -110,7 +106,6 @@ public static void main(String[] args) throws IOException {
110106

111107
// Application-specific logic
112108
myUseCase();
113-
myUseCase();
114109

115110
// Flush all buffered metrics
116111
CompletableResultCode completableResultCode = openTelemetrySdk.getSdkMeterProvider().shutdown();

examples/otlptrace/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,12 @@ Next, export the `GOOGLE_CLOUD_PROJECT` environment variable:
1616
# Use your GCP project ID
1717
export GOOGLE_CLOUD_PROJECT="your-gcp-project-id"
1818
```
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.
1920

2021
Finally, to run the sample from the project root:
2122

2223
```
23-
cd examples/otlptrace && gradle run
24+
./gradlew :examples-otlptrace:run
2425
```
2526

2627
Running this sample will generate and export Traces to Google Cloud.

examples/otlptrace/build.gradle

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ dependencies {
3131
implementation(libraries.opentelemetry_gcp_resources)
3232
}
3333

34-
// Provide headers from env variable
3534
def autoconf_config = [
3635
'-Dotel.exporter.otlp.endpoint=https://telemetry.googleapis.com',
3736
'-Dotel.traces.exporter=otlp',

0 commit comments

Comments
 (0)