|
| 1 | +/* |
| 2 | + * Copyright 2026 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.datastore; |
| 18 | + |
| 19 | +// [START datastore_client_side_metrics] |
| 20 | +import com.google.cloud.datastore.Datastore; |
| 21 | +import com.google.cloud.datastore.DatastoreOpenTelemetryOptions; |
| 22 | +import com.google.cloud.datastore.DatastoreOptions; |
| 23 | +import com.google.cloud.datastore.Entity; |
| 24 | +import com.google.cloud.datastore.Key; |
| 25 | +import com.google.cloud.datastore.Transaction; |
| 26 | + |
| 27 | +import java.util.UUID; |
| 28 | + |
| 29 | +/** |
| 30 | + * Demonstrates default client-side metrics for the Datastore Java client library using a |
| 31 | + * transaction flow. |
| 32 | + * |
| 33 | + * <p>Usage: DatastoreMetricsSample <projectId> <databaseId> |
| 34 | + * |
| 35 | + * <p>Client-side metrics are automatically exported to Google Cloud Monitoring under the {@code |
| 36 | + * custom.googleapis.com/internal/client} metric prefix, using the {@code |
| 37 | + * firestore.googleapis.com/Database} monitored resource. The {@code service} metric label is set to |
| 38 | + * {@code datastore.googleapis.com} to distinguish Datastore traffic from Firestore. |
| 39 | + * |
| 40 | + * <p>No configuration is required to enable metrics — they are on by default. To disable them, set |
| 41 | + * {@link DatastoreOpenTelemetryOptions#setExportBuiltinMetricsToGoogleCloudMonitoring(boolean)} to |
| 42 | + * {@code false}, or set the environment variable {@code DATASTORE_ENABLE_METRICS=false}. |
| 43 | + * |
| 44 | + * <p>Metrics recorded by this sample: |
| 45 | + * |
| 46 | + * <ul> |
| 47 | + * <li>{@code transaction_latency} — end-to-end latency of the transaction including retries. |
| 48 | + * <li>{@code transaction_attempt_count} — number of commit attempts for the transaction. |
| 49 | + * </ul> |
| 50 | + * |
| 51 | + * <p>To verify metrics in Cloud Monitoring after running this sample, navigate to: |
| 52 | + * <b>Cloud Console → Monitoring → Metrics Explorer</b> and filter by: |
| 53 | + * |
| 54 | + * <pre> |
| 55 | + * Metric : custom.googleapis.com/internal/client/transaction_latency |
| 56 | + * Resource: firestore.googleapis.com/Database |
| 57 | + * Label : service = datastore.googleapis.com |
| 58 | + * </pre> |
| 59 | + */ |
| 60 | +public class DatastoreMetricsSample { |
| 61 | + |
| 62 | + public static void main(String[] args) throws Exception { |
| 63 | + if (args.length != 2) { |
| 64 | + System.err.println("Usage: DatastoreMetricsSample <projectId> <databaseId>"); |
| 65 | + System.exit(1); |
| 66 | + } |
| 67 | + String projectId = args[0]; |
| 68 | + String databaseId = args[1]; |
| 69 | + String kind = "Kind-" + UUID.randomUUID().toString().substring(0, 8); |
| 70 | + |
| 71 | + runSample(projectId, databaseId, kind); |
| 72 | + } |
| 73 | + |
| 74 | + static void runSample(String projectId, String databaseId, String kind) throws Exception { |
| 75 | + // [START datastore_client_side_metrics_default] |
| 76 | + // Built-in metrics are exported to Cloud Monitoring by default. |
| 77 | + // No additional configuration is required. |
| 78 | + DatastoreOptions options = |
| 79 | + DatastoreOptions.newBuilder().setProjectId(projectId).setDatabaseId(databaseId).build(); |
| 80 | + // [END datastore_client_side_metrics_default] |
| 81 | + |
| 82 | + try (Datastore datastore = options.getService()) { |
| 83 | + System.out.printf( |
| 84 | + "Connected to project=%s database=%s%n", projectId, databaseId); |
| 85 | + System.out.println( |
| 86 | + "Built-in metrics are enabled by default and will be exported to" |
| 87 | + + " Google Cloud Monitoring under custom.googleapis.com/internal/client/*"); |
| 88 | + |
| 89 | + runTransactionFlow(datastore, kind); |
| 90 | + |
| 91 | + // The periodic metric reader flushes accumulated metrics to Cloud Monitoring on a fixed |
| 92 | + // interval (default: 60 seconds). A final flush also runs when the JVM shuts down via the |
| 93 | + // registered shutdown hook. |
| 94 | + System.out.println( |
| 95 | + "\nTransaction flow complete. Metrics will be flushed to Cloud Monitoring."); |
| 96 | + System.out.println( |
| 97 | + "Check Cloud Monitoring > Metrics Explorer for:" |
| 98 | + + " custom.googleapis.com/internal/client/transaction_latency"); |
| 99 | + |
| 100 | + // Give some time for the periodic metric reader to flush metrics to Cloud Monitoring. |
| 101 | + System.out.println("Waiting 5 seconds for metrics to flush..."); |
| 102 | + Thread.sleep(5000); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Runs a full transaction flow: writes an entity, reads it back within a transaction, updates it, |
| 108 | + * then deletes it. This exercises the read-modify-write pattern that records both {@code |
| 109 | + * transaction_latency} and {@code transaction_attempt_count} metrics. |
| 110 | + */ |
| 111 | + static void runTransactionFlow(Datastore datastore, String kind) { |
| 112 | + Key key = datastore.newKeyFactory().setKind(kind).newKey("metrics-sample-entity"); |
| 113 | + |
| 114 | + // Step 1: Insert the entity outside any transaction to establish a baseline. |
| 115 | + Entity initial = Entity.newBuilder(key).set("status", "created").set("value", 0L).build(); |
| 116 | + datastore.put(initial); |
| 117 | + System.out.printf("Inserted entity: kind=%s key=%s%n", kind, key.getName()); |
| 118 | + |
| 119 | + // Step 2: Read-modify-write inside a transaction. |
| 120 | + // This is the core pattern that generates transaction_latency and |
| 121 | + // transaction_attempt_count metrics. |
| 122 | + Entity updated = |
| 123 | + datastore.runInTransaction( |
| 124 | + transaction -> { |
| 125 | + Entity current = transaction.get(key); |
| 126 | + Entity modified = |
| 127 | + Entity.newBuilder(current) |
| 128 | + .set("status", "updated") |
| 129 | + .set("value", current.getLong("value") + 1) |
| 130 | + .build(); |
| 131 | + transaction.put(modified); |
| 132 | + return modified; |
| 133 | + }); |
| 134 | + System.out.printf( |
| 135 | + "Transaction committed: status=%s value=%d%n", |
| 136 | + updated.getString("status"), updated.getLong("value")); |
| 137 | + System.out.println( |
| 138 | + " → transaction_latency and transaction_attempt_count metrics recorded."); |
| 139 | + |
| 140 | + // Step 3: Clean up. |
| 141 | + datastore.delete(key); |
| 142 | + System.out.printf("Deleted entity: kind=%s key=%s%n", kind, key.getName()); |
| 143 | + } |
| 144 | +} |
| 145 | +// [END datastore_client_side_metrics] |
0 commit comments