-
Notifications
You must be signed in to change notification settings - Fork 39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add metrics exporter #33
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
27f155c
Add metrics exporter
zoercai e799662
Add metrics exporter
zoercai edc832b
Add gcp monitored resource mapping
zoercai 2d8c461
Add gcp monitored resource mapping
zoercai 95c1a81
Add gcp monitored resource mapping
zoercai 16328e6
Refactor
zoercai 4b1126f
Fix MetricConfiguration AutoValue
zoercai 2a78e0c
Refactor & fix
zoercai 3c931d0
Add deadline and fix logging
zoercai 1b64ec0
Review changes
zoercai 711ed05
Correct loggers
zoercai bbb7273
More review changes
zoercai b43572c
Review changes: remove unique identifiers and GCP resource mapping
zoercai 2f99cb7
Still need resource
zoercai b22af4f
Review changes
zoercai fa190d0
Review changes
zoercai ba54f38
Review changes
zoercai 857f362
Review changes
zoercai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
description = 'Cloud Monitoring Exporter for OpenTelemetry' | ||
|
||
dependencies { | ||
api(libraries.auto_value_annotations) | ||
api(libraries.slf4j) | ||
annotationProcessor(libraries.auto_value) | ||
api(libraries.opentelemetry_api) | ||
api(libraries.opentelemetry_sdk) | ||
api(libraries.google_cloud_core) | ||
api(libraries.google_cloud_monitoring) | ||
testImplementation(testLibraries.junit) | ||
testImplementation(testLibraries.slf4j_simple) | ||
} |
104 changes: 104 additions & 0 deletions
104
...ters/metrics/src/main/java/com.google.cloud.opentelemetry.metric/MetricConfiguration.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
package com.google.cloud.opentelemetry.metric; | ||
|
||
import static java.time.Duration.ZERO; | ||
|
||
import com.google.auth.Credentials; | ||
import com.google.auto.value.AutoValue; | ||
import com.google.cloud.ServiceOptions; | ||
import com.google.cloud.monitoring.v3.stub.MetricServiceStub; | ||
import com.google.common.base.Preconditions; | ||
import com.google.common.base.Strings; | ||
import java.time.Duration; | ||
import javax.annotation.Nullable; | ||
import javax.annotation.concurrent.Immutable; | ||
|
||
/** | ||
* Configurations for {@link MetricExporter}. | ||
*/ | ||
@AutoValue | ||
@Immutable | ||
public abstract class MetricConfiguration { | ||
|
||
private static final String DEFAULT_PROJECT_ID = | ||
Strings.nullToEmpty(ServiceOptions.getDefaultProjectId()); | ||
private static final Duration DEFAULT_DEADLINE = Duration.ofSeconds(10, 0); | ||
|
||
MetricConfiguration() { | ||
} | ||
|
||
/** | ||
* Returns the {@link Credentials}. | ||
* | ||
* @return the {@code Credentials}. | ||
*/ | ||
@Nullable | ||
public abstract Credentials getCredentials(); | ||
|
||
/** | ||
* Returns the cloud project id. | ||
* | ||
* @return the cloud project id. | ||
*/ | ||
public abstract String getProjectId(); | ||
|
||
/** | ||
* Returns a MetricsServiceStub instance used to make RPC calls. | ||
* | ||
* @return the metrics service stub. | ||
*/ | ||
@Nullable | ||
public abstract MetricServiceStub getMetricServiceStub(); | ||
|
||
/** | ||
* Returns the deadline for exporting to Cloud Monitoring backend. | ||
* | ||
* <p>Default value is 10 seconds. | ||
* | ||
* @return the export deadline. | ||
*/ | ||
public abstract Duration getDeadline(); | ||
|
||
public static Builder builder() { | ||
return new AutoValue_MetricConfiguration.Builder() | ||
.setProjectId(DEFAULT_PROJECT_ID) | ||
.setDeadline(DEFAULT_DEADLINE); | ||
} | ||
|
||
/** | ||
* Builder for {@link MetricConfiguration}. | ||
*/ | ||
@AutoValue.Builder | ||
public abstract static class Builder { | ||
|
||
Builder() { | ||
} | ||
|
||
abstract String getProjectId(); | ||
|
||
abstract Duration getDeadline(); | ||
|
||
public abstract Builder setProjectId(String projectId); | ||
|
||
public abstract Builder setCredentials(Credentials newCredentials); | ||
|
||
public abstract Builder setMetricServiceStub(MetricServiceStub newMetricServiceStub); | ||
|
||
public abstract Builder setDeadline(Duration deadline); | ||
|
||
abstract MetricConfiguration autoBuild(); | ||
|
||
/** | ||
* Builds a {@link MetricConfiguration}. | ||
* | ||
* @return a {@code MetricsConfiguration}. | ||
*/ | ||
public MetricConfiguration build() { | ||
Preconditions.checkArgument( | ||
!Strings.isNullOrEmpty(getProjectId()), | ||
"Cannot find a project ID from either configurations or application default."); | ||
Preconditions.checkArgument(getDeadline().compareTo(ZERO) > 0, "Deadline must be positive."); | ||
return autoBuild(); | ||
} | ||
} | ||
|
||
} |
201 changes: 201 additions & 0 deletions
201
exporters/metrics/src/main/java/com.google.cloud.opentelemetry.metric/MetricExporter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,201 @@ | ||
package com.google.cloud.opentelemetry.metric; | ||
|
||
import static com.google.api.client.util.Preconditions.checkNotNull; | ||
import static com.google.cloud.opentelemetry.metric.MetricTranslator.mapMetric; | ||
import static com.google.cloud.opentelemetry.metric.MetricTranslator.mapMetricDescriptor; | ||
import static com.google.cloud.opentelemetry.metric.MetricTranslator.mapPoint; | ||
|
||
import com.google.api.Metric; | ||
import com.google.api.MetricDescriptor; | ||
import com.google.api.MonitoredResource; | ||
import com.google.api.gax.core.FixedCredentialsProvider; | ||
import com.google.auth.Credentials; | ||
import com.google.auth.oauth2.GoogleCredentials; | ||
import com.google.cloud.monitoring.v3.MetricServiceClient; | ||
import com.google.cloud.monitoring.v3.MetricServiceSettings; | ||
import com.google.cloud.monitoring.v3.stub.MetricServiceStub; | ||
import com.google.common.collect.Lists; | ||
import com.google.monitoring.v3.CreateMetricDescriptorRequest; | ||
import com.google.monitoring.v3.Point; | ||
import com.google.monitoring.v3.ProjectName; | ||
import com.google.monitoring.v3.TimeSeries; | ||
import io.opentelemetry.common.Labels; | ||
import io.opentelemetry.sdk.metrics.data.MetricData; | ||
import java.io.IOException; | ||
import java.time.Duration; | ||
import java.time.Instant; | ||
import java.util.ArrayList; | ||
import java.util.Collection; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.Objects; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
public class MetricExporter implements io.opentelemetry.sdk.metrics.export.MetricExporter { | ||
|
||
private static final String PROJECT_NAME_PREFIX = "projects/"; | ||
private static final long WRITE_INTERVAL_SECOND = 12; | ||
private static final int MAX_BATCH_SIZE = 200; | ||
private static final long NANO_PER_SECOND = (long) 1e9; | ||
|
||
private static final Logger logger = LoggerFactory.getLogger(MetricExporter.class); | ||
|
||
private final MetricServiceClient metricServiceClient; | ||
private final String projectId; | ||
private final Instant exporterStartTime; | ||
private final Map<MetricWithLabels, Long> lastUpdatedTime = new HashMap<>(); | ||
|
||
MetricExporter( | ||
String projectId, | ||
MetricServiceClient client | ||
) { | ||
this.projectId = projectId; | ||
this.metricServiceClient = client; | ||
this.exporterStartTime = Instant.now(); | ||
} | ||
|
||
public static MetricExporter createWithDefaultConfiguration() throws IOException { | ||
MetricConfiguration configuration = MetricConfiguration.builder().build(); | ||
return MetricExporter.createWithConfiguration(configuration); | ||
} | ||
|
||
public static MetricExporter createWithConfiguration(MetricConfiguration configuration) | ||
throws IOException { | ||
String projectId = configuration.getProjectId(); | ||
MetricServiceStub stub = configuration.getMetricServiceStub(); | ||
|
||
if (stub == null) { | ||
Credentials credentials = | ||
configuration.getCredentials() == null | ||
? GoogleCredentials.getApplicationDefault() | ||
: configuration.getCredentials(); | ||
|
||
return MetricExporter.createWithCredentials( | ||
projectId, credentials, configuration.getDeadline()); | ||
} | ||
return MetricExporter.createWithClient( | ||
projectId, MetricServiceClient.create(stub)); | ||
} | ||
|
||
private static MetricExporter createWithClient( | ||
String projectId, | ||
MetricServiceClient metricServiceClient) { | ||
return new MetricExporter(projectId, metricServiceClient); | ||
} | ||
|
||
private static MetricExporter createWithCredentials( | ||
String projectId, | ||
Credentials credentials, | ||
Duration deadline) throws IOException { | ||
MetricServiceSettings.Builder builder = | ||
MetricServiceSettings.newBuilder() | ||
.setCredentialsProvider( | ||
FixedCredentialsProvider.create(checkNotNull(credentials, "Credentials not provided."))); | ||
builder.createMetricDescriptorSettings() | ||
.setSimpleTimeoutNoRetries(org.threeten.bp.Duration.ofMillis(deadline.toMillis())); | ||
return new MetricExporter(projectId, MetricServiceClient.create(builder.build())); | ||
} | ||
|
||
@Override | ||
public ResultCode export(Collection<MetricData> metrics) { | ||
List<TimeSeries> allTimesSeries = new ArrayList<>(); | ||
|
||
for (MetricData metricData : metrics) { | ||
MetricDescriptor descriptor = mapMetricDescriptor(metricData); | ||
if (descriptor == null) { | ||
continue; | ||
} | ||
metricServiceClient.createMetricDescriptor( | ||
CreateMetricDescriptorRequest.newBuilder().setName(PROJECT_NAME_PREFIX + projectId) | ||
.setMetricDescriptor(descriptor) | ||
.build()); | ||
|
||
MetricWithLabels updateKey = new MetricWithLabels(descriptor.getType(), | ||
metricData.getDescriptor().getConstantLabels()); | ||
|
||
// We are expecting one point per MetricData | ||
if (metricData.getPoints().size() != 1) { | ||
logger.error("There should be exactly one point in each metricData, found {}", | ||
metricData.getPoints().size()); | ||
continue; | ||
} | ||
MetricData.Point metricPoint = metricData.getPoints().iterator().next(); | ||
|
||
// Cloud Monitoring API allows, for any combination of labels and | ||
// metric name, one update per WRITE_INTERVAL seconds | ||
long pointCollectionTime = metricPoint.getEpochNanos(); | ||
if (lastUpdatedTime.containsKey(updateKey) | ||
&& pointCollectionTime <= lastUpdatedTime.get(updateKey) / NANO_PER_SECOND + WRITE_INTERVAL_SECOND) { | ||
continue; | ||
} | ||
|
||
Metric metric = mapMetric(metricData, descriptor.getType()); | ||
Point point = mapPoint(metricData, metricPoint, updateKey, lastUpdatedTime); | ||
if (point == null) { | ||
continue; | ||
} | ||
|
||
allTimesSeries.add(TimeSeries.newBuilder() | ||
.setMetric(metric) | ||
.addPoints(point) | ||
.setResource(MonitoredResource.newBuilder().build()) | ||
.setMetricKind(descriptor.getMetricKind()) | ||
.build()); | ||
} | ||
createTimeSeriesBatch(metricServiceClient, ProjectName.of(projectId), allTimesSeries); | ||
return ResultCode.SUCCESS; | ||
} | ||
|
||
private static void createTimeSeriesBatch(MetricServiceClient metricServiceClient, ProjectName projectName, | ||
List<TimeSeries> allTimesSeries) { | ||
List<List<TimeSeries>> batches = Lists.partition(allTimesSeries, MAX_BATCH_SIZE); | ||
zoercai marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for (List<TimeSeries> timeSeries : batches) { | ||
metricServiceClient.createTimeSeries(projectName, new ArrayList<>(timeSeries)); | ||
} | ||
aabmass marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
/** | ||
* The exporter does not batch metrics, so this method will immediately return with success. | ||
* | ||
* @return always Success | ||
*/ | ||
@Override | ||
public ResultCode flush() { | ||
return ResultCode.SUCCESS; | ||
} | ||
|
||
@Override | ||
public void shutdown() { | ||
metricServiceClient.shutdown(); | ||
} | ||
|
||
static class MetricWithLabels { | ||
|
||
private final String metricType; | ||
private final Labels labels; | ||
|
||
MetricWithLabels(String metricType, Labels labels) { | ||
this.metricType = metricType; | ||
this.labels = labels; | ||
} | ||
|
||
@Override | ||
public boolean equals(Object o) { | ||
if (this == o) { | ||
return true; | ||
} | ||
if (o == null || getClass() != o.getClass()) { | ||
return false; | ||
} | ||
MetricWithLabels that = (MetricWithLabels) o; | ||
return Objects.equals(metricType, that.metricType) && Objects.equals(labels, that.labels); | ||
} | ||
|
||
@Override | ||
public int hashCode() { | ||
return Objects.hash(metricType, labels); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We are using
{googleCloudVersion}
for both core and trace dependencies above, but not for Cloud Monitoring client? Might be worth checking if we should also use separate versioning for core and tracing?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah I used a separate version for cloud monitoring because the 1.0.2 version didn't have much and didn't work. I've added a separate
cloudTracingVersion
for tracing, kept it to 1.0.2 for this PR though.