|
| 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 | +package com.google.cloud.spanner; |
| 18 | + |
| 19 | +import static com.google.cloud.opentelemetry.detection.GCPPlatformDetector.SupportedPlatform.GOOGLE_KUBERNETES_ENGINE; |
| 20 | +import static com.google.cloud.spanner.BuiltInMetricsConstant.CLIENT_NAME_KEY; |
| 21 | +import static com.google.cloud.spanner.BuiltInMetricsConstant.CLIENT_UID_KEY; |
| 22 | +import static com.google.cloud.spanner.BuiltInMetricsConstant.INSTANCE_CONFIG_ID_KEY; |
| 23 | +import static com.google.cloud.spanner.BuiltInMetricsConstant.LOCATION_ID_KEY; |
| 24 | +import static com.google.cloud.spanner.BuiltInMetricsConstant.PROJECT_ID_KEY; |
| 25 | + |
| 26 | +import com.google.auth.Credentials; |
| 27 | +import com.google.cloud.opentelemetry.detection.AttributeKeys; |
| 28 | +import com.google.cloud.opentelemetry.detection.DetectedPlatform; |
| 29 | +import com.google.cloud.opentelemetry.detection.GCPPlatformDetector; |
| 30 | +import io.opentelemetry.api.OpenTelemetry; |
| 31 | +import io.opentelemetry.sdk.OpenTelemetrySdk; |
| 32 | +import io.opentelemetry.sdk.metrics.SdkMeterProvider; |
| 33 | +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; |
| 34 | +import java.io.IOException; |
| 35 | +import java.lang.management.ManagementFactory; |
| 36 | +import java.lang.reflect.Method; |
| 37 | +import java.net.InetAddress; |
| 38 | +import java.net.UnknownHostException; |
| 39 | +import java.util.HashMap; |
| 40 | +import java.util.Map; |
| 41 | +import java.util.UUID; |
| 42 | +import java.util.logging.Level; |
| 43 | +import java.util.logging.Logger; |
| 44 | +import javax.annotation.Nullable; |
| 45 | + |
| 46 | +final class BuiltInOpenTelemetryMetricsProvider { |
| 47 | + |
| 48 | + static BuiltInOpenTelemetryMetricsProvider INSTANCE = new BuiltInOpenTelemetryMetricsProvider(); |
| 49 | + |
| 50 | + private static final Logger logger = |
| 51 | + Logger.getLogger(BuiltInOpenTelemetryMetricsProvider.class.getName()); |
| 52 | + |
| 53 | + private static String taskId; |
| 54 | + |
| 55 | + private OpenTelemetry openTelemetry; |
| 56 | + |
| 57 | + private BuiltInOpenTelemetryMetricsProvider() {} |
| 58 | + |
| 59 | + OpenTelemetry getOrCreateOpenTelemetry(String projectId, @Nullable Credentials credentials) { |
| 60 | + try { |
| 61 | + if (this.openTelemetry == null) { |
| 62 | + SdkMeterProviderBuilder sdkMeterProviderBuilder = SdkMeterProvider.builder(); |
| 63 | + BuiltInOpenTelemetryMetricsView.registerBuiltinMetrics( |
| 64 | + SpannerCloudMonitoringExporter.create(projectId, credentials), sdkMeterProviderBuilder); |
| 65 | + this.openTelemetry = |
| 66 | + OpenTelemetrySdk.builder().setMeterProvider(sdkMeterProviderBuilder.build()).build(); |
| 67 | + } |
| 68 | + return this.openTelemetry; |
| 69 | + } catch (IOException ex) { |
| 70 | + logger.log( |
| 71 | + Level.WARNING, |
| 72 | + "Unable to get OpenTelemetry object for client side metrics, will skip exporting client side metrics", |
| 73 | + ex); |
| 74 | + return null; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + Map<String, String> createClientAttributes(String projectId, String client_name) { |
| 79 | + Map<String, String> clientAttributes = new HashMap<>(); |
| 80 | + clientAttributes.put(LOCATION_ID_KEY.getKey(), detectClientLocation()); |
| 81 | + clientAttributes.put(PROJECT_ID_KEY.getKey(), projectId); |
| 82 | + // TODO: Replace this with real value. |
| 83 | + clientAttributes.put(INSTANCE_CONFIG_ID_KEY.getKey(), "unknown"); |
| 84 | + clientAttributes.put(CLIENT_NAME_KEY.getKey(), client_name); |
| 85 | + clientAttributes.put(CLIENT_UID_KEY.getKey(), getDefaultTaskValue()); |
| 86 | + return clientAttributes; |
| 87 | + } |
| 88 | + |
| 89 | + static String detectClientLocation() { |
| 90 | + GCPPlatformDetector detector = GCPPlatformDetector.DEFAULT_INSTANCE; |
| 91 | + DetectedPlatform detectedPlatform = detector.detectPlatform(); |
| 92 | + // All platform except GKE uses "cloud_region" for region attribute. |
| 93 | + String region = detectedPlatform.getAttributes().get("cloud_region"); |
| 94 | + if (detectedPlatform.getSupportedPlatform() == GOOGLE_KUBERNETES_ENGINE) { |
| 95 | + region = detectedPlatform.getAttributes().get(AttributeKeys.GKE_LOCATION_TYPE_REGION); |
| 96 | + } |
| 97 | + return region == null ? "global" : region; |
| 98 | + } |
| 99 | + |
| 100 | + /** |
| 101 | + * Generates a unique identifier for the Client_uid metric field. The identifier is composed of a |
| 102 | + * UUID, the process ID (PID), and the hostname. |
| 103 | + * |
| 104 | + * <p>For Java 9 and later, the PID is obtained using the ProcessHandle API. For Java 8, the PID |
| 105 | + * is extracted from ManagementFactory.getRuntimeMXBean().getName(). |
| 106 | + * |
| 107 | + * @return A unique identifier string in the format UUID@PID@hostname |
| 108 | + */ |
| 109 | + private static String getDefaultTaskValue() { |
| 110 | + if (taskId == null) { |
| 111 | + String identifier = UUID.randomUUID().toString(); |
| 112 | + String pid = getProcessId(); |
| 113 | + |
| 114 | + try { |
| 115 | + String hostname = InetAddress.getLocalHost().getHostName(); |
| 116 | + taskId = identifier + "@" + pid + "@" + hostname; |
| 117 | + } catch (UnknownHostException e) { |
| 118 | + logger.log(Level.INFO, "Unable to get the hostname.", e); |
| 119 | + taskId = identifier + "@" + pid + "@localhost"; |
| 120 | + } |
| 121 | + } |
| 122 | + return taskId; |
| 123 | + } |
| 124 | + |
| 125 | + private static String getProcessId() { |
| 126 | + try { |
| 127 | + // Check if Java 9+ and ProcessHandle class is available |
| 128 | + Class<?> processHandleClass = Class.forName("java.lang.ProcessHandle"); |
| 129 | + Method currentMethod = processHandleClass.getMethod("current"); |
| 130 | + Object processHandleInstance = currentMethod.invoke(null); |
| 131 | + Method pidMethod = processHandleClass.getMethod("pid"); |
| 132 | + long pid = (long) pidMethod.invoke(processHandleInstance); |
| 133 | + return Long.toString(pid); |
| 134 | + } catch (Exception e) { |
| 135 | + // Fallback to Java 8 method |
| 136 | + final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); |
| 137 | + if (jvmName != null && jvmName.contains("@")) { |
| 138 | + return jvmName.split("@")[0]; |
| 139 | + } else { |
| 140 | + return "unknown"; |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | +} |
0 commit comments