Copilot commented on code in PR #5245:
URL: https://github.com/apache/solr/pull/5245#discussion_r4696723947


##########
solr/core/src/java/org/apache/solr/metrics/otel/MetricExporterFactory.java:
##########
@@ -17,24 +17,78 @@
 package org.apache.solr.metrics.otel;
 
 import io.opentelemetry.sdk.metrics.export.MetricExporter;
+import java.util.Locale;
 import org.apache.solr.common.util.EnvUtils;
 
+/**
+ * Configuration of Solr's OTLP metric exporter. Each setting is resolved from 
its Solr-specific
+ * property first, then from the equivalent standard OpenTelemetry environment 
variable (or {@code
+ * otel.*} system property), then from a default.
+ */
 public interface MetricExporterFactory {
 
-  Boolean OTLP_EXPORTER_ENABLED =
-      
Boolean.parseBoolean(EnvUtils.getProperty("solr.metrics.otlpExporterEnabled", 
"false"));
+  Boolean OTLP_EXPORTER_ENABLED = resolveEnabled();
 
-  String OTLP_EXPORTER_PROTOCOL = 
EnvUtils.getProperty("solr.metrics.otlpExporterProtocol", "http");
+  String OTLP_EXPORTER_PROTOCOL = resolveProtocol();
 
-  int OTLP_EXPORTER_INTERVAL =
-      
Integer.parseInt(EnvUtils.getProperty("solr.metrics.otlpExporterInterval", 
"60000"));
+  int OTLP_EXPORTER_INTERVAL = resolveInterval();
 
   String OTLP_EXPORTER_GRPC_ENDPOINT =
-      EnvUtils.getProperty("solr.metrics.otlpGrpcExporterEndpoint", 
"http://localhost:4317";);
+      resolveEndpoint("solr.metrics.otlpGrpcExporterEndpoint", false);
 
   String OTLP_EXPORTER_HTTP_ENDPOINT =
-      EnvUtils.getProperty(
-          "solr.metrics.otlpHttpExporterEndpoint", 
"http://localhost:4318/v1/metrics";);
+      resolveEndpoint("solr.metrics.otlpHttpExporterEndpoint", true);
 
   MetricExporter getExporter();
+
+  /**
+   * Also enabled by {@code OTEL_METRICS_EXPORTER} naming {@code otlp}, the 
only one Solr exports,
+   * but only while the Solr property is unset, so an explicit {@code false} 
still disables export.
+   */
+  private static boolean resolveEnabled() {
+    String solrEnabled = 
EnvUtils.getProperty("solr.metrics.otlpExporterEnabled");
+    if (solrEnabled != null) return Boolean.parseBoolean(solrEnabled);
+    String configured = otelConfig("OTEL_METRICS_EXPORTER");
+    return configured != null && configured.contains("otlp");
+  }
+
+  private static String resolveProtocol() {
+    String solrProtocol = 
EnvUtils.getProperty("solr.metrics.otlpExporterProtocol");
+    if (solrProtocol != null) return solrProtocol;
+    String otelProtocol = otelConfig("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL");
+    if (otelProtocol == null) otelProtocol = 
otelConfig("OTEL_EXPORTER_OTLP_PROTOCOL");
+    if (otelProtocol == null) return "http";
+    // The OTEL spec spells the HTTP transports http/protobuf and http/json
+    return otelProtocol.startsWith("http") ? "http" : otelProtocol;
+  }
+
+  private static int resolveInterval() {
+    String solrInterval = 
EnvUtils.getProperty("solr.metrics.otlpExporterInterval");
+    if (solrInterval != null) return Integer.parseInt(solrInterval);
+    String otelInterval = otelConfig("OTEL_METRIC_EXPORT_INTERVAL");
+    return otelInterval != null ? Integer.parseInt(otelInterval) : 60000;

Review Comment:
   An empty `OTEL_METRIC_EXPORT_INTERVAL` is treated as unset by the SDK, but 
this parses it and throws `NumberFormatException`. Because every interface 
field is initialized when `loadMetricExporter()` reads `OTLP_EXPORTER_ENABLED`, 
this prevents Solr from starting even when 
`solr.metrics.otlpExporterEnabled=false`. Treat an empty interval as absent 
before parsing so an otherwise valid tracing environment cannot break metrics 
initialization.



##########
solr/core/src/java/org/apache/solr/core/OpenTelemetryConfigurator.java:
##########
@@ -145,6 +180,146 @@ protected OpenTelemetry createOpenTelemetry() {
     return getOpenTelemetrySdk();
   }
 
+  /**
+   * The resource the configurator resolved for the OpenTelemetry it created, 
or {@code null} to let
+   * Solr derive one from the standard {@code OTEL_*} configuration. 
Overriding this is what keeps
+   * traces and metrics on an identical resource, including attributes 
contributed by {@code
+   * ResourceProvider} implementations that only the SDK knows about.
+   */
+  protected Resource getResource() {
+    return null;
+  }
+
+  /**
+   * Resource attributes describing this node, for any signal Solr exports 
itself. Reflects {@code
+   * OTEL_SERVICE_NAME} and {@code OTEL_RESOURCE_ATTRIBUTES} (or their {@code 
otel.*} system
+   * property equivalents), with Solr supplying {@code service.name}, {@code 
service.instance.id}
+   * and {@code host.name} where they are not configured.
+   */
+  public static Resource getTelemetryResource() {
+    return telemetryResource;
+  }
+
+  private static void adoptConfiguredResource(OpenTelemetryConfigurator 
configurator) {
+    Resource configured = configurator.getResource();
+    if (configured != null) {
+      telemetryResource = withSolrDefaults(configured);
+    }
+  }
+
+  /**
+   * Builds the resource from the standard OTEL configuration, for when no 
configurator supplies
+   * one: no {@code opentelemetry} module, or a Java agent owning tracing.
+   */
+  private static Resource resourceFromConfig(Map<String, String> env) {
+    AttributesBuilder attrs = Attributes.builder();
+    parseResourceAttributes(getConfig("OTEL_RESOURCE_ATTRIBUTES", 
env)).forEach(attrs::put);

Review Comment:
   Without the module, or when a Java agent owns tracing, 
`OTEL_RESOURCE_ATTRIBUTES=service.instance.id=node%3A8983` becomes the literal 
`node%3A8983` in metrics rather than `node:8983`, so trace and metric 
identities differ. Decode values when constructing the fallback Resource using 
the [SDK's percent-decoding 
semantics](https://github.com/open-telemetry/opentelemetry-java/blob/70276b77c0a5eb5d5b9b39b3e9ba3a28b44b593a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResource.java#L96-L105),
 preserving literal plus signs and malformed percent sequences. Keep the shared 
parser's output encoded so republishing `otel.resource.attributes` does not 
turn encoded commas into attribute separators.



##########
solr/modules/opentelemetry/src/java/org/apache/solr/opentelemetry/OtelTracerConfigurator.java:
##########
@@ -57,33 +59,54 @@ public void init(NamedList<?> args) {
   public OpenTelemetry createOpenTelemetry() {
     // deliberately build() and not initialize(); the latter sets 
GlobalOpenTelemetry, which is
     // OpenTelemetryConfigurator's job
-    return 
AutoConfiguredOpenTelemetrySdk.builder().build().getOpenTelemetrySdk();
+    return AutoConfiguredOpenTelemetrySdk.builder()
+        // Solr owns the meter providers, and honours OTEL_METRICS_EXPORTER in 
its own OTLP exporter
+        .addPropertiesCustomizer(
+            config -> Map.of("otel.metrics.exporter", "none", 
"otel.logs.exporter", "none"))
+        // Hand the resolved resource back to Solr so its metrics carry the 
same one as these traces
+        .addResourceCustomizer(
+            (resource, config) -> {
+              this.resource = resource;
+              return resource;
+            })

Review Comment:
   When an operator installs an `AutoConfigurationCustomizerProvider` that adds 
a resource customizer, this callback captures an intermediate resource: the 
[SDK registers those customizers later during 
build](https://github.com/open-telemetry/opentelemetry-java/blob/70276b77c0a5eb5d5b9b39b3e9ba3a28b44b593a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkBuilder.java#L462-L468)
 and runs them in registration order. Traces therefore receive the later 
changes while metrics can retain different service or instance IDs. Capture the 
resource after all resource customizers have run, and add a regression test 
with an operator-provided customizer.



##########
solr/core/src/java/org/apache/solr/metrics/otel/MetricExporterFactory.java:
##########
@@ -17,24 +17,78 @@
 package org.apache.solr.metrics.otel;
 
 import io.opentelemetry.sdk.metrics.export.MetricExporter;
+import java.util.Locale;
 import org.apache.solr.common.util.EnvUtils;
 
+/**
+ * Configuration of Solr's OTLP metric exporter. Each setting is resolved from 
its Solr-specific
+ * property first, then from the equivalent standard OpenTelemetry environment 
variable (or {@code
+ * otel.*} system property), then from a default.
+ */
 public interface MetricExporterFactory {
 
-  Boolean OTLP_EXPORTER_ENABLED =
-      
Boolean.parseBoolean(EnvUtils.getProperty("solr.metrics.otlpExporterEnabled", 
"false"));
+  Boolean OTLP_EXPORTER_ENABLED = resolveEnabled();
 
-  String OTLP_EXPORTER_PROTOCOL = 
EnvUtils.getProperty("solr.metrics.otlpExporterProtocol", "http");
+  String OTLP_EXPORTER_PROTOCOL = resolveProtocol();
 
-  int OTLP_EXPORTER_INTERVAL =
-      
Integer.parseInt(EnvUtils.getProperty("solr.metrics.otlpExporterInterval", 
"60000"));
+  int OTLP_EXPORTER_INTERVAL = resolveInterval();
 
   String OTLP_EXPORTER_GRPC_ENDPOINT =
-      EnvUtils.getProperty("solr.metrics.otlpGrpcExporterEndpoint", 
"http://localhost:4317";);
+      resolveEndpoint("solr.metrics.otlpGrpcExporterEndpoint", false);
 
   String OTLP_EXPORTER_HTTP_ENDPOINT =
-      EnvUtils.getProperty(
-          "solr.metrics.otlpHttpExporterEndpoint", 
"http://localhost:4318/v1/metrics";);
+      resolveEndpoint("solr.metrics.otlpHttpExporterEndpoint", true);
 
   MetricExporter getExporter();
+
+  /**
+   * Also enabled by {@code OTEL_METRICS_EXPORTER} naming {@code otlp}, the 
only one Solr exports,
+   * but only while the Solr property is unset, so an explicit {@code false} 
still disables export.
+   */
+  private static boolean resolveEnabled() {
+    String solrEnabled = 
EnvUtils.getProperty("solr.metrics.otlpExporterEnabled");
+    if (solrEnabled != null) return Boolean.parseBoolean(solrEnabled);
+    String configured = otelConfig("OTEL_METRICS_EXPORTER");
+    return configured != null && configured.contains("otlp");
+  }
+
+  private static String resolveProtocol() {
+    String solrProtocol = 
EnvUtils.getProperty("solr.metrics.otlpExporterProtocol");
+    if (solrProtocol != null) return solrProtocol;
+    String otelProtocol = otelConfig("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL");
+    if (otelProtocol == null) otelProtocol = 
otelConfig("OTEL_EXPORTER_OTLP_PROTOCOL");
+    if (otelProtocol == null) return "http";
+    // The OTEL spec spells the HTTP transports http/protobuf and http/json
+    return otelProtocol.startsWith("http") ? "http" : otelProtocol;

Review Comment:
   `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http/json` is collapsed to `http`, but 
`OtlpExporterFactory` builds the default protobuf exporter, so a JSON-only 
receiver rejects the metrics. Normalize only `http/protobuf` to `http`, leaving 
unsupported encodings to the factory's existing warning-and-disable branch, and 
update `MetricExporterFactoryTest.testProtocol` accordingly. Supporting JSON 
instead would require explicitly enabling the [SDK builder's separate JSON 
mode](https://github.com/open-telemetry/opentelemetry-java/blob/70276b77c0a5eb5d5b9b39b3e9ba3a28b44b593a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterBuilder.java#L365-L371).



##########
solr/core/src/java/org/apache/solr/core/OpenTelemetryConfigurator.java:
##########
@@ -145,6 +180,146 @@ protected OpenTelemetry createOpenTelemetry() {
     return getOpenTelemetrySdk();
   }
 
+  /**
+   * The resource the configurator resolved for the OpenTelemetry it created, 
or {@code null} to let
+   * Solr derive one from the standard {@code OTEL_*} configuration. 
Overriding this is what keeps
+   * traces and metrics on an identical resource, including attributes 
contributed by {@code
+   * ResourceProvider} implementations that only the SDK knows about.
+   */
+  protected Resource getResource() {
+    return null;
+  }
+
+  /**
+   * Resource attributes describing this node, for any signal Solr exports 
itself. Reflects {@code
+   * OTEL_SERVICE_NAME} and {@code OTEL_RESOURCE_ATTRIBUTES} (or their {@code 
otel.*} system
+   * property equivalents), with Solr supplying {@code service.name}, {@code 
service.instance.id}
+   * and {@code host.name} where they are not configured.
+   */
+  public static Resource getTelemetryResource() {
+    return telemetryResource;
+  }
+
+  private static void adoptConfiguredResource(OpenTelemetryConfigurator 
configurator) {
+    Resource configured = configurator.getResource();
+    if (configured != null) {
+      telemetryResource = withSolrDefaults(configured);
+    }
+  }
+
+  /**
+   * Builds the resource from the standard OTEL configuration, for when no 
configurator supplies
+   * one: no {@code opentelemetry} module, or a Java agent owning tracing.
+   */
+  private static Resource resourceFromConfig(Map<String, String> env) {
+    AttributesBuilder attrs = Attributes.builder();
+    parseResourceAttributes(getConfig("OTEL_RESOURCE_ATTRIBUTES", 
env)).forEach(attrs::put);
+    // OTEL_SERVICE_NAME wins over a service.name given among the resource 
attributes, per spec.
+    String serviceName = getConfig("OTEL_SERVICE_NAME", env);
+    if (serviceName != null) {
+      attrs.put(SERVICE_NAME, serviceName);
+    }
+    return 
withSolrDefaults(Resource.getDefault().merge(Resource.create(attrs.build())));
+  }
+
+  /** Fills in Solr's node identity and service name for whatever the 
configuration left unset. */
+  private static Resource withSolrDefaults(Resource base) {
+    String serviceName = base.getAttribute(SERVICE_NAME);
+    Resource resource = nodeDefaults.merge(base);
+    if (serviceName == null || UNKNOWN_SERVICE.equals(serviceName)) {
+      resource = resource.merge(Resource.create(Attributes.of(SERVICE_NAME, 
"solr")));
+    }
+    return resource;
+  }
+
+  /** {@code host.name} and {@code service.instance.id} as Solr knows them. */
+  private static Map<String, String> nodeDefaultAttributes(NodeConfig cfg) {
+    Map<String, String> attrs = new LinkedHashMap<>();
+    String host = nodeHost(cfg);
+    String port = nodePort(cfg);
+    if (host != null) {
+      attrs.put(HOST_NAME.getKey(), host);
+      if (port != null) {
+        attrs.put(SERVICE_INSTANCE_ID.getKey(), host + ":" + port);
+      }
+    }
+    return attrs;
+  }
+
+  private static Resource toResource(Map<String, String> attrs) {
+    AttributesBuilder builder = Attributes.builder();
+    attrs.forEach(builder::put);
+    return Resource.create(builder.build());
+  }
+
+  /**
+   * Merges Solr's defaults into {@code otel.resource.attributes}, below the 
environment, a system
+   * property and {@code <tracerConfig>} init args, in that order of 
precedence.
+   */
+  private static void setDefaultResourceAttributes(
+      Map<String, String> nodeAttrs, NodeConfig cfg, Map<String, String> env) {
+    Map<String, String> attrs = new LinkedHashMap<>(nodeAttrs);
+    // The property set below would shadow the configurator's own init args, 
so fold them in here.
+    attrs.putAll(parseResourceAttributes(tracerConfigResourceAttributes(cfg)));
+    attrs.putAll(parseResourceAttributes(getConfig("OTEL_RESOURCE_ATTRIBUTES", 
env)));
+    if (attrs.isEmpty()) return;
+    EnvUtils.setProperty(
+        "otel.resource.attributes",
+        attrs.entrySet().stream()
+            .map(e -> e.getKey() + "=" + e.getValue())
+            .collect(Collectors.joining(",")));
+  }
+
+  /** {@code otel.resource.attributes} as supplied through {@code 
<tracerConfig>}, or null. */
+  private static String tracerConfigResourceAttributes(NodeConfig cfg) {
+    PluginInfo info = (cfg != null) ? cfg.getTracerConfiguratorPluginInfo() : 
null;
+    if (info == null || !info.isEnabled() || info.initArgs == null) return 
null;
+    for (Map.Entry<String, Object> arg : info.initArgs) {
+      if (arg.getValue() != null
+          && 
"otel.resource.attributes".equals(envNameToSyspropName(arg.getKey()))) {
+        return arg.getValue().toString();
+      }
+    }
+    return null;
+  }
+
+  /**
+   * Parses the comma separated {@code key=value} form of {@code 
OTEL_RESOURCE_ATTRIBUTES}, skipping
+   * entries that lack a value.
+   */
+  protected static Map<String, String> parseResourceAttributes(String 
commaSeparated) {
+    Map<String, String> parsed = new LinkedHashMap<>();
+    if (commaSeparated == null) return parsed;
+    for (String entry : commaSeparated.split(",")) {
+      int eq = entry.indexOf('=');
+      if (eq > 0) {
+        parsed.put(entry.substring(0, eq).strip(), entry.substring(eq + 
1).strip());

Review Comment:
   Empty values are retained here although the SDK ignores them, so 
`OTEL_RESOURCE_ATTRIBUTES=service.instance.id=` replaces the generated node ID 
with an empty string in fallback metrics. Likewise, `service.name=` suppresses 
the module's service-name default even though the SDK later drops that 
attribute. Skip blank keys and values before merging them into the defaults.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to