zuozhiw commented on code in PR #5375:
URL: https://github.com/apache/texera/pull/5375#discussion_r3576052492


##########
common/observability/src/main/scala/org/apache/texera/observability/OtelInit.scala:
##########
@@ -0,0 +1,392 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.observability
+
+import com.typesafe.scalalogging.LazyLogging
+import io.opentelemetry.api.{GlobalOpenTelemetry, OpenTelemetry}
+import io.opentelemetry.api.common.{AttributeKey, Attributes}
+import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter
+import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter
+import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter
+import io.opentelemetry.sdk.OpenTelemetrySdk
+import io.opentelemetry.sdk.logs.SdkLoggerProvider
+import io.opentelemetry.sdk.logs.`export`.{BatchLogRecordProcessor, 
LogRecordExporter}
+import io.opentelemetry.sdk.metrics.SdkMeterProvider
+import io.opentelemetry.sdk.metrics.`export`.{MetricExporter, 
PeriodicMetricReader}
+import io.opentelemetry.sdk.resources.Resource
+import io.opentelemetry.sdk.trace.SdkTracerProvider
+import io.opentelemetry.sdk.trace.`export`.{BatchSpanProcessor, SpanExporter}
+
+import java.net.URI
+import java.time.Duration
+import scala.util.{Failure, Success, Try}
+
+/**
+  * Bootstraps the OpenTelemetry SDK for a Texera service.
+  *
+  * Enabled by default; set OTEL_SDK_DISABLED=true to turn it off. Reads
+  * OTEL_* env vars, validates the endpoint against an allowlist, builds
+  * tracer/log/metric providers, and attaches a Logback appender.
+  * Returns None when disabled or misconfigured; never throws.
+  */
+object OtelInit extends LazyLogging {
+
+  /** Resource attribute keys accepted from OTEL_RESOURCE_ATTRIBUTES;
+    *  applied to every record this JVM emits. Others are dropped.
+    */
+  private[observability] val AllowedResourceKeys: Set[String] = Set(

Review Comment:
   Same comment as the mdc key allow list, in my experience adding new 
attributes are fairly common.



##########
common/observability/src/main/scala/org/apache/texera/observability/LogSanitizer.scala:
##########
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.observability
+
+import scala.jdk.CollectionConverters._
+
+/**
+  * Pure functions that sanitize log bodies and MDC before export:
+  * strip control characters, redact secrets, cap body size, and
+  * filter MDC to an allowlist.
+  */
+object LogSanitizer {
+
+  /** Per-record body byte cap. */
+  val MaxBodyBytes: Int = 16 * 1024
+
+  /** Suffix appended to truncated bodies. */
+  val TruncatedMarker: String = "...[truncated]"
+
+  /** C0 control characters except TAB (0x09), plus DEL (0x7F). */
+  private val C0ControlRegex = "[\\x00-\\x08\\x0A-\\x1F\\x7F]".r
+
+  /** Secret patterns, redacted from bodies. Most specific first. */
+  private val SecretPatterns: Seq[scala.util.matching.Regex] = Seq(
+    // Bearer token
+    """(?i)Bearer\s+[A-Za-z0-9._\-/+=]{8,}""".r,
+    // password=... or password: ...
+    """(?i)password\s*[=:]\s*[^\s,;"']+""".r,
+    // AWS access key ID
+    """AKIA[0-9A-Z]{16}""".r,
+    // labelled AWS secret access key
+    """(?i)aws_secret_access_key\s*[=:]\s*[A-Za-z0-9/+=]{20,}""".r
+  )
+
+  /** MDC keys forwarded to OTel log attributes. Default-deny: the MDC is a
+    *  process-wide map that any library on the classpath may write to, so
+    *  only keys Texera's own instrumentation sets are exported. The list is
+    *  the correlation IDs needed to join a log line to its trace and to the
+    *  workflow/execution/user it belongs to; all are low-cardinality,
+    *  non-sensitive identifiers (no names, emails, or payloads).
+    *
+    *  Everything else is dropped. Today that is chiefly the keys Pekko's
+    *  SLF4J bridge injects (`sourceThread`, `pekkoSource`, `pekkoAddress`,
+    *  `pekkoTimestamp`, `sourceActorSystem`), which are redundant with the
+    *  log body and would bloat every exported record; it also future-proofs
+    *  against third-party or user code leaking arbitrary MDC values.
+    */
+  val AllowedMdcKeys: Set[String] = Set(

Review Comment:
   I feel this allow list is very restrictive, this means that if we want to 
add new kv pairs we have to edit this list, and in my experience adding new kv 
pairs to logs is kind of common as we develop more things. What's the goal of 
enforcing such a strict allow list? If it's for dropping fields from the noisy 
libraries are there better ways to do it?



##########
common/observability/src/main/scala/org/apache/texera/observability/OtelInit.scala:
##########
@@ -0,0 +1,392 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.observability
+
+import com.typesafe.scalalogging.LazyLogging
+import io.opentelemetry.api.{GlobalOpenTelemetry, OpenTelemetry}
+import io.opentelemetry.api.common.{AttributeKey, Attributes}
+import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter
+import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter
+import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter
+import io.opentelemetry.sdk.OpenTelemetrySdk
+import io.opentelemetry.sdk.logs.SdkLoggerProvider
+import io.opentelemetry.sdk.logs.`export`.{BatchLogRecordProcessor, 
LogRecordExporter}
+import io.opentelemetry.sdk.metrics.SdkMeterProvider
+import io.opentelemetry.sdk.metrics.`export`.{MetricExporter, 
PeriodicMetricReader}
+import io.opentelemetry.sdk.resources.Resource
+import io.opentelemetry.sdk.trace.SdkTracerProvider
+import io.opentelemetry.sdk.trace.`export`.{BatchSpanProcessor, SpanExporter}
+
+import java.net.URI
+import java.time.Duration
+import scala.util.{Failure, Success, Try}
+
+/**
+  * Bootstraps the OpenTelemetry SDK for a Texera service.
+  *
+  * Enabled by default; set OTEL_SDK_DISABLED=true to turn it off. Reads
+  * OTEL_* env vars, validates the endpoint against an allowlist, builds
+  * tracer/log/metric providers, and attaches a Logback appender.
+  * Returns None when disabled or misconfigured; never throws.
+  */
+object OtelInit extends LazyLogging {
+
+  /** Resource attribute keys accepted from OTEL_RESOURCE_ATTRIBUTES;
+    *  applied to every record this JVM emits. Others are dropped.
+    */
+  private[observability] val AllowedResourceKeys: Set[String] = Set(
+    "service.name",
+    "service.version",
+    "deployment.environment",
+    "texera.computing_unit.id",
+    "texera.workflow.id",
+    "texera.execution.id"
+  )
+
+  /** Endpoint schemes we accept. */
+  private[observability] val AllowedSchemes: Set[String] = Set("http", 
"https", "grpc")
+
+  /** Hosts we accept for the OTLP endpoint by default. */
+  private[observability] val DefaultAllowedHosts: Set[String] = Set(
+    "localhost",
+    "127.0.0.1",
+    "::1",
+    "[::1]"
+  )
+
+  /** Default endpoint. 127.0.0.1 (not "localhost") to force IPv4 so a
+    *  natively-run service reaches the collector on dual-stack hosts.
+    */
+  private val DefaultEndpoint = "http://127.0.0.1:4317";
+
+  /** Metric export interval bounds; out-of-range values clamp to the
+    *  default (see clampIntervalMs).
+    */
+  private[observability] val MinMetricIntervalMs: Long = 1000L
+  private[observability] val MaxMetricIntervalMs: Long = 10L * 60L * 1000L
+  private[observability] val DefaultMetricIntervalMs: Long = 60L * 1000L

Review Comment:
   I think 60s metric scraping frequency might be a bit slow. I would suggest 
30s to make the resolution higher. I know this doubles the points, but we can 
try it and see if the metric backend of our choice can keep up. I think the 
runtime overhead is negligible.



##########
common/observability/src/main/scala/org/apache/texera/observability/TexeraOtelLogAppender.scala:
##########
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.observability
+
+import ch.qos.logback.classic.Level
+import ch.qos.logback.classic.spi.{ILoggingEvent, IThrowableProxy, 
ThrowableProxyUtil}
+import ch.qos.logback.core.UnsynchronizedAppenderBase
+import io.opentelemetry.api.OpenTelemetry
+import io.opentelemetry.api.common.AttributeKey
+import io.opentelemetry.api.logs.{Logger, Severity}
+import io.opentelemetry.api.trace.Span
+import io.opentelemetry.context.Context
+
+import java.util.concurrent.TimeUnit
+
+/**
+  * Logback appender that sanitizes each event via [[LogSanitizer]] and
+  * emits it as an OTel LogRecord. [[append]] is a no-op until [[bind]]
+  * is called and after [[stop]].
+  */
+class TexeraOtelLogAppender extends UnsynchronizedAppenderBase[ILoggingEvent] {
+
+  // @volatile so a late bind() is visible to appender threads.
+  @volatile private var otelLogger: Option[Logger] = None
+
+  def bind(otel: OpenTelemetry): Unit = {
+    otelLogger = Some(otel.getLogsBridge.get("texera.logback"))
+  }
+
+  override def stop(): Unit = {
+    otelLogger = None
+    super.stop()
+  }
+
+  override def append(event: ILoggingEvent): Unit = {

Review Comment:
   Is this the dependency that is injected to everywhere when we want to log 
things? 
   If so, what's the public interface we expose to our developers? This append 
doesn't look like a very friendly interface. What are some popular apis? Eg I 
would imagine an easy to use api would be logger.INFO("message", k1, v1, k2, 
v2, ...) we can expose common levels such as debug info warn error. Also how 
does the MDC interface works with this? I'm not too familiar with javas MDC 
approach, so I would like to see how would a normal program use our logger 
interface.



-- 
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]

Reply via email to