Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,18 @@
import logging
import os
import uuid
from collections.abc import Mapping
from collections.abc import Callable, Mapping
from typing import Any

import structlog
from genkit_otel import GenAiInstrumentation
from google.auth import default as google_auth_default
from google.auth.credentials import Credentials as GoogleCredentials
from google.auth.exceptions import DefaultCredentialsError
from google.cloud.logging_v2.services.logging_service_v2 import LoggingServiceV2Client
from google.cloud.monitoring_v3 import MetricServiceClient
from google.cloud.trace_v2 import TraceServiceClient
from google.oauth2.service_account import Credentials as ServiceAccountCredentials
from opentelemetry import _logs, metrics, trace as trace_api
from opentelemetry.exporter.cloud_logging import CloudLoggingExporter # ty: ignore[deprecated]
from opentelemetry.exporter.cloud_monitoring import CloudMonitoringMetricsExporter
Expand Down Expand Up @@ -183,12 +188,48 @@ def resolve_project(
return env_value

# Check credentials for project_id
if credentials and 'project_id' in credentials:
return credentials['project_id']
if credentials and isinstance(credentials, Mapping):
project_id = credentials.get('project_id')
if project_id:
return str(project_id)

return None


# Keys google-auth needs to build service-account credentials from a dict.
_SERVICE_ACCOUNT_REQUIRED_FIELDS = ('client_email', 'private_key', 'token_uri')


def _load_service_account_credentials(info: dict[str, Any]) -> GoogleCredentials:
"""Build service-account credentials from ``credentials=``, or raise INVALID_ARGUMENT.

Messages name fields and types, never values: the argument may hold a private key.
"""
if not isinstance(info, Mapping):
raise GenkitError(
status='INVALID_ARGUMENT',
message=f'credentials= must be a service account key dict, got {type(info).__name__}',
)
missing = [field for field in _SERVICE_ACCOUNT_REQUIRED_FIELDS if not info.get(field)]
if missing:
raise GenkitError(
status='INVALID_ARGUMENT',
message=f'credentials= is not a service account key; missing {", ".join(missing)}',
)
try:
return ServiceAccountCredentials.from_service_account_info(dict(info))
except Exception as e:
# google-auth and cryptography errors are dropped (from None) so no part of
# the key can reach a log line through the exception chain.
raise GenkitError(
status='INVALID_ARGUMENT',
message=(
f'credentials= could not be loaded as a service account key ({type(e).__name__}); '
'check that private_key is the PEM key from the downloaded JSON key file'
),
) from None


def _adc_project_id() -> str | None:
"""Project on Application Default Credentials, or None when ADC has none.

Expand Down Expand Up @@ -226,7 +267,8 @@ def __init__(

Args:
project: GCP project ID.
credentials: Optional credentials dict.
credentials: Optional service-account key dict. Parsed here, so a
bad key raises ``INVALID_ARGUMENT`` before anything is installed.
sampler: Trace sampler.
force_dev_export: Check to force export in dev environment.
disable_metrics: If True, metrics are not exported.
Expand All @@ -235,6 +277,7 @@ def __init__(
metric_export_timeout_ms: Export timeout in ms.
"""
self.credentials = credentials
self._google_credentials = _load_service_account_credentials(credentials) if credentials is not None else None
self.sampler = sampler
self.force_dev_export = force_dev_export
self.disable_metrics = disable_metrics
Expand Down Expand Up @@ -266,17 +309,20 @@ def __init__(

self.metric_export_timeout_ms = metric_export_timeout_ms or self.metric_export_interval_ms

def _build_exporter_kwargs(self) -> dict[str, Any]:
"""Build kwargs for the OTel Cloud exporters, which take ``project_id``.
def _build_exporter_kwargs(self, client_cls: Callable[..., object]) -> dict[str, Any]:
"""Build kwargs for an OTel Cloud exporter, which takes ``project_id`` and ``client``.

The exporters have no ``credentials`` argument, so explicit credentials
ride on a ``client_cls(credentials=...)`` instance instead.

Returns:
A dict with project_id and/or credentials if available, empty dict otherwise.
A dict with project_id and client if available, empty dict otherwise.
"""
kwargs: dict[str, Any] = {}
if self.project:
kwargs['project_id'] = self.project
if self.credentials:
kwargs['credentials'] = self.credentials
if self._google_credentials is not None:
kwargs['client'] = client_cls(credentials=self._google_credentials)
return kwargs

def initialize(self) -> None:
Expand Down Expand Up @@ -319,11 +365,11 @@ def _configure_logging(self) -> None:
"""Stamp Cloud Logging trace correlation fields on structlog events."""
try:
current_config = structlog.get_config()
processors = list(current_config.get('processors', []))

# Early return if already configured
if any(getattr(p, '__name__', '') == '_genkit_inject_trace_context' for p in processors):
return
processors = [
p
for p in current_config.get('processors', [])
if getattr(p, '__name__', '') != '_genkit_inject_trace_context'
]

# Define processor function that captures self
def _genkit_inject_trace_context(
Expand All @@ -333,8 +379,11 @@ def _genkit_inject_trace_context(
) -> Mapping[str, Any]:
return self._inject_trace_context(logger_instance, method_name, event_dict)

# Append processor to chain
processors.append(_genkit_inject_trace_context)
# structlog hands the last processor's return value to the logger, so the
# last one is the renderer (JSONRenderer, ConsoleRenderer, or stdlib's
# ProcessorFormatter.wrap_for_formatter). It turns the event dict into a
# str, bytes, or tuple, so fields added after it are dropped.
processors.insert(max(len(processors) - 1, 0), _genkit_inject_trace_context)
structlog.configure(processors=processors)
logger.debug('Configured structlog for GCP trace correlation')

Expand All @@ -344,8 +393,7 @@ def _genkit_inject_trace_context(
def _configure_tracing(self) -> None:
try:
if not self.disable_traces:
exporter_kwargs = self._build_exporter_kwargs()
base_exporter = GenkitGCPExporter(**exporter_kwargs) if exporter_kwargs else GenkitGCPExporter()
base_exporter = GenkitGCPExporter(**self._build_exporter_kwargs(TraceServiceClient))

trace_exporter = GcpAdjustingTraceExporter(
exporter=base_exporter,
Expand All @@ -362,7 +410,7 @@ def _configure_tracing(self) -> None:
def _configure_otel_logs(self) -> None:
try:
exporter = CloudLoggingExporter( # ty: ignore[deprecated]
project_id=self.project,
**self._build_exporter_kwargs(LoggingServiceV2Client),
default_log_name='genkit',
)
_hang_exporter_on_process_logger(exporter=exporter)
Expand Down Expand Up @@ -401,8 +449,9 @@ def _configure_metrics(self) -> None:
finally:
detector_logger.setLevel(original_level)

exporter_kwargs = self._build_exporter_kwargs()
cloud_monitoring_exporter = CloudMonitoringMetricsExporter(**exporter_kwargs)
cloud_monitoring_exporter = CloudMonitoringMetricsExporter(
**self._build_exporter_kwargs(MetricServiceClient)
)

metrics_exporter = GenkitMetricExporter(
exporter=cloud_monitoring_exporter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
MetricsData,
)

from ._constants import METRIC_START_TIME_ADJUSTMENT_NS
from ._constants import METRIC_START_TIME_ADJUSTMENT_NS, MIN_SPAN_DURATION_NS


class GenkitMetricExporter(MetricExporter):
Expand All @@ -49,7 +49,7 @@ class GenkitMetricExporter(MetricExporter):
overlap in the start/end times that the Metric reader sends -- the end_time
of the previous export becomes the start_time of the current export.

This wrapper adds a microsecond to start times to ensure discrete export
This wrapper adds a millisecond to start times to ensure discrete export
timeframes and prevent data being overwritten.
"""

Expand All @@ -67,16 +67,24 @@ def __init__(
self._exporter = exporter
self._error_handler = error_handler

# Cloud Monitoring converts DELTA to CUMULATIVE; we send DELTA.
# Cloud Monitoring converts DELTA to CUMULATIVE; we send DELTA for counters
# and histograms. Up/down counters are written as GAUGE points, which carry
# the current value, so they stay CUMULATIVE: as DELTA, a queue that goes
# 5 -> 6 would chart as 5 then 1.
delta = AggregationTemporality.DELTA
self._preferred_temporality = {
cumulative = AggregationTemporality.CUMULATIVE
preferred_temporality = {
Counter: delta,
UpDownCounter: delta,
UpDownCounter: cumulative,
Histogram: delta,
ObservableCounter: delta,
ObservableUpDownCounter: delta,
ObservableUpDownCounter: cumulative,
ObservableGauge: delta,
}
super().__init__(
preferred_temporality=preferred_temporality,
preferred_aggregation=getattr(exporter, '_preferred_aggregation', None),
)

def export(
self,
Expand Down Expand Up @@ -108,23 +116,28 @@ def export(
raise

def _modify_start_times(self, metrics_data: MetricsData) -> None:
"""Add 1ms to start times to prevent overlap.
"""Add 1ms to DELTA start times to prevent overlap without inverting short intervals.

Args:
metrics_data: The metrics data to modify in-place.
"""
for resource_metrics in metrics_data.resource_metrics:
for scope_metrics in resource_metrics.scope_metrics:
for metric in scope_metrics.metrics:
if getattr(metric.data, 'aggregation_temporality', None) != AggregationTemporality.DELTA:
continue
for data_point in metric.data.data_points:
# Add 1 millisecond to start time
if hasattr(data_point, 'start_time_unix_nano'):
adjusted_start = data_point.start_time_unix_nano + METRIC_START_TIME_ADJUSTMENT_NS
# Modifying frozen dataclass via workaround
object.__setattr__(
data_point,
'start_time_unix_nano',
data_point.start_time_unix_nano + METRIC_START_TIME_ADJUSTMENT_NS,
)
object.__setattr__(data_point, 'start_time_unix_nano', adjusted_start)
# On a sub-1ms flush/shutdown, Cloud Monitoring still requires end_time > start_time.
if hasattr(data_point, 'time_unix_nano') and data_point.time_unix_nano <= adjusted_start:
object.__setattr__(
data_point,
'time_unix_nano',
adjusted_start + MIN_SPAN_DURATION_NS,
)

def force_flush(self, timeout_millis: float = 10_000) -> bool:
"""Delegate force flush to wrapped exporter.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,11 @@ def enable_google_cloud_telemetry(
Application Default Credentials project, in that order. Required
when using external credentials (e.g., Workload Identity
Federation).
credentials: Service account credentials dict for authenticating with
Google Cloud. Primarily for use outside of GCP. On GCP, credentials
are typically inferred via Application Default Credentials (ADC).
credentials: Service account key dict (the parsed JSON key file) for
authenticating with Google Cloud. Primarily for use outside of GCP.
On GCP, credentials are typically inferred via Application Default
Credentials (ADC). A dict that is not a usable service account key
raises ``INVALID_ARGUMENT``; the message names fields, never values.
sampler: Sampler used when this helper creates the process tracer.
Pass ``ALWAYS_ON``, ``ALWAYS_OFF``, or ``TraceIdRatioBased(0.1)``
from ``opentelemetry.sdk.trace.sampling``. With no ``sampler=``,
Expand Down Expand Up @@ -199,8 +201,7 @@ def enable_google_cloud_telemetry(
)
# Before the flag is set, so a rejected call can be fixed and retried.
_reject_unusable_cloud_setup(sampler=sampler, disable_traces=disable_traces)
_enable_google_cloud_telemetry_already_called = True

# Also before the flag: GcpTelemetry parses credentials= and raises on a bad key.
manager = GcpTelemetry(
project=project,
credentials=credentials,
Expand All @@ -211,5 +212,6 @@ def enable_google_cloud_telemetry(
metric_export_interval_ms=metric_export_interval_ms,
metric_export_timeout_ms=metric_export_timeout_ms,
)
_enable_google_cloud_telemetry_already_called = True

manager.initialize()
Loading
Loading