-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Add OS-level resource metric collection to flow run subprocesses #21071
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
desertaxle
merged 9 commits into
main
from
alexs/oss-7694-add-os-level-resource-metric-collection-to-flow-run
Mar 11, 2026
Merged
Changes from 6 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
0d19cbe
Add OS-level resource metric collection to flow run subprocesses
desertaxle ffcd656
Fix CI failures: add telemetry to SUPPORTED_SETTINGS, fix test mocks …
desertaxle 92fcbb9
Merge branch 'main' into alexs/oss-7694-add-os-level-resource-metric-…
desertaxle d9540d8
Pass API key as auth header on OTLP metric exports
desertaxle 219e28a
Set 5s timeout on OTLP metric exporter
desertaxle 3453cf9
Address review feedback: credential scoping, shutdown timeout, valida…
desertaxle 2e81408
Address review: setup error safety, OTEL_EXPORTER_OTLP_ENDPOINT suppo…
desertaxle b742918
Fix credential leak: never send API key to user-specified OTLP endpoints
desertaxle bdf7702
Strip trailing slash from Cloud API URL before appending metrics path
desertaxle File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| from typing import ClassVar | ||
|
|
||
| from pydantic import Field | ||
| from pydantic_settings import SettingsConfigDict | ||
|
|
||
| from prefect.settings.base import PrefectBaseSettings, build_settings_config | ||
|
|
||
|
|
||
| class TelemetrySettings(PrefectBaseSettings): | ||
| """ | ||
| Settings for configuring Prefect telemetry | ||
| """ | ||
|
|
||
| model_config: ClassVar[SettingsConfigDict] = build_settings_config(("telemetry",)) | ||
|
|
||
| enable_resource_metrics: bool = Field( | ||
| default=True, | ||
| description="Whether to enable OS-level resource metric collection in flow run subprocesses.", | ||
| ) | ||
|
|
||
| resource_metrics_interval_seconds: int = Field( | ||
| default=10, | ||
| ge=1, | ||
| description="Interval in seconds between resource metric collections.", | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| import os | ||
| from contextlib import contextmanager | ||
| from typing import TYPE_CHECKING, Generator, Optional | ||
|
|
||
| from prefect.logging.loggers import get_logger | ||
|
|
||
| if TYPE_CHECKING: | ||
| from prefect.client.schemas.objects import FlowRun | ||
| from prefect.flows import Flow | ||
|
|
||
| logger: logging.Logger = get_logger("prefect.telemetry.metrics") | ||
|
|
||
|
|
||
| def _resolve_metrics_endpoint( | ||
| settings: object, | ||
| ) -> tuple[Optional[str], bool]: | ||
| """Resolve the OTLP metrics endpoint. | ||
|
|
||
| Returns: | ||
| A tuple of (endpoint_url, is_cloud_endpoint). The boolean indicates | ||
| whether the endpoint was auto-derived from a Cloud API URL, which | ||
| determines whether the API key should be sent as an auth header. | ||
|
|
||
| Priority: | ||
| 1. OTEL_EXPORTER_OTLP_METRICS_ENDPOINT env var (user override) | ||
| 2. Auto-derived from Cloud API URL: {api_url}/telemetry/v1/metrics | ||
| 3. None if neither available | ||
| """ | ||
| explicit = os.environ.get("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT") | ||
| if explicit: | ||
| return explicit, False | ||
|
|
||
| api_url = settings.api.url # type: ignore[union-attr] | ||
| if api_url and settings.connected_to_cloud: # type: ignore[union-attr] | ||
| return f"{api_url}/telemetry/v1/metrics", True | ||
|
|
||
| return None, False | ||
|
|
||
|
|
||
| @contextmanager | ||
| def RunMetrics( | ||
| flow_run: FlowRun, | ||
| flow: Flow, | ||
| ) -> Generator[None, None, None]: | ||
| """Context manager that collects OS-level resource metrics during flow run execution. | ||
|
|
||
| Starts an OpenTelemetry MeterProvider with SystemMetricsInstrumentor, filtered to | ||
| process CPU and memory metrics. Exports via OTLP HTTP. | ||
|
|
||
| Becomes a no-op if: | ||
| - Resource metrics are disabled in settings | ||
| - No OTLP endpoint is available | ||
| - The opentelemetry-instrumentation-system-metrics package is not installed | ||
| """ | ||
| import prefect.settings | ||
|
|
||
| settings = prefect.settings.get_current_settings() | ||
|
|
||
| if not settings.telemetry.enable_resource_metrics: | ||
| yield | ||
| return | ||
|
|
||
| endpoint, is_cloud_endpoint = _resolve_metrics_endpoint(settings) | ||
| if not endpoint: | ||
| yield | ||
| return | ||
|
|
||
| try: | ||
| from opentelemetry.exporter.otlp.proto.http.metric_exporter import ( | ||
| OTLPMetricExporter, | ||
| ) | ||
| from opentelemetry.instrumentation.system_metrics import ( | ||
| SystemMetricsInstrumentor, | ||
| ) | ||
| from opentelemetry.sdk.metrics import MeterProvider | ||
| from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader | ||
| from opentelemetry.sdk.resources import Resource | ||
| except ImportError: | ||
| logger.debug( | ||
| "opentelemetry instrumentation packages not available, " | ||
| "skipping resource metric collection" | ||
| ) | ||
| yield | ||
| return | ||
|
|
||
| resource_attributes: dict[str, str] = { | ||
| "prefect.flow-run.id": str(flow_run.id), | ||
| "prefect.flow.name": flow.name, | ||
| } | ||
| if flow_run.deployment_id: | ||
| resource_attributes["prefect.deployment.id"] = str(flow_run.deployment_id) | ||
| if flow_run.work_pool_name: | ||
| resource_attributes["prefect.work-pool.name"] = flow_run.work_pool_name | ||
|
|
||
| resource = Resource.create(resource_attributes) | ||
|
|
||
| headers: dict[str, str] = {} | ||
| if is_cloud_endpoint: | ||
| api_key = settings.api.key | ||
| if api_key: | ||
| headers["Authorization"] = f"Bearer {api_key.get_secret_value()}" | ||
|
|
||
| exporter = OTLPMetricExporter( | ||
| endpoint=endpoint, | ||
| headers=headers, | ||
| timeout=5, | ||
desertaxle marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ) | ||
| export_interval_millis = settings.telemetry.resource_metrics_interval_seconds * 1000 | ||
| reader = PeriodicExportingMetricReader( | ||
| exporter, | ||
| export_interval_millis=export_interval_millis, | ||
| export_timeout_millis=5000, | ||
| ) | ||
| meter_provider = MeterProvider(resource=resource, metric_readers=[reader]) | ||
|
|
||
| instrumentor = SystemMetricsInstrumentor( | ||
| config={ | ||
| "process.cpu.utilization": None, | ||
| "process.memory.usage": None, | ||
| "process.memory.virtual": None, | ||
| }, | ||
| ) | ||
| instrumentor.instrument(meter_provider=meter_provider) | ||
|
|
||
| try: | ||
| yield | ||
| finally: | ||
| try: | ||
| instrumentor.uninstrument() | ||
| except Exception: | ||
| logger.debug("Error uninstrumenting system metrics", exc_info=True) | ||
| try: | ||
| meter_provider.shutdown() | ||
| except Exception: | ||
| logger.debug("Error shutting down meter provider", exc_info=True) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
😮💨