Skip to content
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

Implemented get_name in StatsLogger, updated Otel and StatsD #43340

Open
wants to merge 56 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
594d185
Implemented get_name in StatsLogger, updated Otel and StatsD
ArshiaZr Oct 24, 2024
490ad5d
Refactor StatsLogger base class and update SafeOtelLogger and SafeSta…
ArshiaZr Oct 29, 2024
ed8ae52
Merge branch 'main' into main
ArshiaZr Oct 29, 2024
e0a6233
Refactor metric name validation to preserve Allow/Block list compatib…
ArshiaZr Oct 29, 2024
6d14631
Merge branch 'main' of https://github.com/ArshiaZr/airflow
ArshiaZr Oct 29, 2024
981405d
Merge branch 'main' into main
ArshiaZr Oct 29, 2024
8a243ec
Merge branch 'main' into main
ArshiaZr Oct 30, 2024
459fa28
Refactored and deleted unnecessary parts of the code
ArshiaZr Oct 31, 2024
a6246bf
Merge branch 'main' into main
ArshiaZr Oct 31, 2024
dcbe5b4
Categorized the test cases accordingly and named them properly
ArshiaZr Oct 31, 2024
a6b01ad
Merge branch 'main' of https://github.com/ArshiaZr/airflow
ArshiaZr Oct 31, 2024
0dbab73
Refactor tag handling in DogStatsdLogger
ArshiaZr Nov 3, 2024
cecf8d5
Implemented inheritance for SafeDogStatsdLogger
ArshiaZr Nov 4, 2024
f06adfc
Merge branch 'main' into main
ArshiaZr Nov 5, 2024
8940606
Merge branch 'main' into main
ferruzzi Nov 5, 2024
ed094ad
refactor: remove redundant checks, lift OTel length restriction, and …
ArshiaZr Nov 14, 2024
f998467
Removed BACK_COMPAT_METRIC_NAMES as it's not beeing used anymore
ArshiaZr Nov 26, 2024
e9f5900
Capped otel metric name to 256 chars. Made test cases for otel_logger…
ArshiaZr Nov 26, 2024
5b134ab
Merge remote-tracking branch 'upstream/main'
ArshiaZr Nov 26, 2024
570ac74
Merge branch 'main' into main
ArshiaZr Nov 27, 2024
af4d42f
Implemented get_name in StatsLogger, updated Otel and StatsD
ArshiaZr Oct 24, 2024
02223ce
Refactor StatsLogger base class and update SafeOtelLogger and SafeSta…
ArshiaZr Oct 29, 2024
eb9acec
Refactor metric name validation to preserve Allow/Block list compatib…
ArshiaZr Oct 29, 2024
3fa9c7d
Refactored and deleted unnecessary parts of the code
ArshiaZr Oct 31, 2024
d77808e
Categorized the test cases accordingly and named them properly
ArshiaZr Oct 31, 2024
63e3b51
Refactor tag handling in DogStatsdLogger
ArshiaZr Nov 3, 2024
3e87d20
Implemented inheritance for SafeDogStatsdLogger
ArshiaZr Nov 4, 2024
911f245
refactor: remove redundant checks, lift OTel length restriction, and …
ArshiaZr Nov 14, 2024
868f555
Removed BACK_COMPAT_METRIC_NAMES as it's not beeing used anymore
ArshiaZr Nov 26, 2024
134ef18
Capped otel metric name to 256 chars. Made test cases for otel_logger…
ArshiaZr Nov 26, 2024
b421756
Fix failing ruff check on main (#44399)
potiuk Nov 26, 2024
e5a5ed8
Fix formatting for backport failure message. (#44392)
potiuk Nov 26, 2024
8555660
Remove Pydantic 2.10.0/2.10.1 workaround (#44400)
potiuk Nov 26, 2024
b1caf81
Remove reference to hatch and add uv usage (#44401)
perry2of5 Nov 26, 2024
c12e233
AIP-84 Migrate Trigger Dag Run endpoint to FastAPI (#43875)
rawwar Nov 27, 2024
a291adc
Also check NEW_SESSION imports in pre-commit (#44388)
uranusjr Nov 27, 2024
91199a8
add basic system tests for OpenLineage (#43643)
mobuchowski Nov 27, 2024
33bc3fc
Add DAG arguments to asset decorator (#44384)
uranusjr Nov 27, 2024
40b6600
add openblock labs to INTHEWILD (#44365)
melotik Nov 27, 2024
01f2bfb
Add 'airflow assets list' (#44387)
uranusjr Nov 27, 2024
112b7ad
Delete `dag_version` table when downgrading the DB from the versioned…
ephraimbuddy Nov 27, 2024
59b5979
Allow 'dag_version' table to be deleted by db clean command (#44389)
ephraimbuddy Nov 27, 2024
f7fac36
docs(newsfragment): add template for significant newsfragments (#44378)
Lee-W Nov 27, 2024
4c5f0b6
AIP-84 Refactor SortParm (#44345)
jason810496 Nov 27, 2024
18bca07
Move external task sensor to standard provider (#44288)
kunaljubce Nov 27, 2024
fb928e5
Add note about why we still have `black` config settings (#44415)
ashb Nov 27, 2024
f11f1b0
chore: unify handling of gcs paths (#44410)
kacpermuda Nov 27, 2024
0d2e840
AIP-72: Add support for fetching XComs in Supervisor (#44408)
kaxil Nov 27, 2024
1088f14
AIP-72: Improve Supervisor and Task Instance State Validation (#44405)
kaxil Nov 27, 2024
5500372
Move OpenAPI tests to breeze container (#44326)
gopidesupavan Nov 27, 2024
d9f4167
Update providers metadata 2024-11-27 (#44418)
eladkal Nov 27, 2024
0ea46d4
feat: add OpenLineage support for transfer operators between gcs and …
kacpermuda Nov 27, 2024
2e195a6
AIP-84 Refactor test cases with `datetime_zulu_format` (#44323)
jason810496 Nov 27, 2024
a8bf66c
Fixing rendering of code block for newsfragment command (#44419)
amoghrajesh Nov 27, 2024
1c0adb2
Merge branch 'main' of https://github.com/ArshiaZr/airflow
ArshiaZr Nov 27, 2024
84a98bc
Merge branch 'main' into main
shahar1 Jan 10, 2025
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
34 changes: 17 additions & 17 deletions airflow/metrics/base_stats_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
from airflow.typing_compat import Protocol

if TYPE_CHECKING:
from opentelemetry.util.types import Attributes

from airflow.metrics.protocols import DeltaType, TimerProtocol


Expand All @@ -31,55 +33,53 @@ class StatsLogger(Protocol):

instance: StatsLogger | NoStatsLogger | None = None

@classmethod
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we removing @classmethod from all of these? Seems unusual to remove the decorator but leave the cls parameter.

Copy link
Contributor

@shahar1 shahar1 Nov 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd be happy for an explanation about the necessity of removing @classmethod - won't it break the functionality that we have in dag_processing/manager.py? For example:

https://github.com/apache/airflow/blob/1c0adb21f6cb5efa24270913444f189776835747/airflow/dag_processing/manager.py#L290C45-L290C46

def incr(
cls,
stat: str,
self,
metric_name: str,
shahar1 marked this conversation as resolved.
Show resolved Hide resolved
count: int = 1,
rate: int | float = 1,
*,
tags: dict[str, Any] | None = None,
) -> None:
"""Increment stat."""
"""Increment metric_name."""

@classmethod
def decr(
cls,
stat: str,
self,
metric_name: str,
count: int = 1,
rate: int | float = 1,
*,
tags: dict[str, Any] | None = None,
) -> None:
"""Decrement stat."""
"""Decrement metric_name."""

@classmethod
def gauge(
cls,
stat: str,
self,
metric_name: str,
value: float,
rate: int | float = 1,
delta: bool = False,
*,
tags: dict[str, Any] | None = None,
) -> None:
"""Gauge stat."""
"""Gauge metric_name."""

@classmethod
def timing(
cls,
stat: str,
self,
metric_name: str,
dt: DeltaType | None,
*,
tags: dict[str, Any] | None = None,
) -> None:
"""Stats timing."""

@classmethod
def timer(cls, *args, **kwargs) -> TimerProtocol:
def timer(self, *args, **kwargs) -> TimerProtocol:
"""Timer metric that can be cancelled."""
raise NotImplementedError()

def get_name(self, metric_name: str, tags: Attributes | None = None) -> str:
raise NotImplementedError()


class NoStatsLogger:
"""If no StatsLogger is configured, NoStatsLogger is used as a fallback."""
Expand Down
56 changes: 38 additions & 18 deletions airflow/metrics/otel_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
from opentelemetry.sdk.resources import HOST_NAME, SERVICE_NAME, Resource

from airflow.configuration import conf
from airflow.exceptions import AirflowProviderDeprecationWarning
from airflow.exceptions import AirflowProviderDeprecationWarning, InvalidStatsNameException
from airflow.metrics.base_stats_logger import StatsLogger
from airflow.metrics.protocols import Timer
from airflow.metrics.validators import (
OTEL_NAME_MAX_LENGTH,
Expand Down Expand Up @@ -173,7 +174,7 @@ def stop(self, send: bool = True) -> None:
)


class SafeOtelLogger:
class SafeOtelLogger(StatsLogger):
"""Otel Logger."""

def __init__(
Expand All @@ -190,15 +191,15 @@ def __init__(

def incr(
self,
stat: str,
metric_name: str,
count: int = 1,
rate: float = 1,
tags: Attributes = None,
):
"""
Increment stat by count.

:param stat: The name of the stat to increment.
:param metric_name: The name of the metric to increment.
:param count: A positive integer to add to the current value of stat.
:param rate: value between 0 and 1 that represents the sample rate at
which the metric is going to be emitted.
Expand All @@ -209,22 +210,23 @@ def incr(
if count < 0:
raise ValueError("count must be a positive value.")

if self.metrics_validator.test(stat) and name_is_otel_safe(self.prefix, stat):
counter = self.metrics_map.get_counter(full_name(prefix=self.prefix, name=stat), attributes=tags)
if self.metrics_validator.test(metric_name):
full_metric_name = self.get_name(metric_name, tags)
counter = self.metrics_map.get_counter(full_metric_name, attributes=tags)
counter.add(count, attributes=tags)
return counter

def decr(
self,
stat: str,
metric_name: str,
count: int = 1,
rate: float = 1,
tags: Attributes = None,
):
"""
Decrement stat by count.

:param stat: The name of the stat to decrement.
:param metric_name: The name of the metric to decrement.
:param count: A positive integer to subtract from current value of stat.
:param rate: value between 0 and 1 that represents the sample rate at
which the metric is going to be emitted.
Expand All @@ -235,14 +237,15 @@ def decr(
if count < 0:
raise ValueError("count must be a positive value.")

if self.metrics_validator.test(stat) and name_is_otel_safe(self.prefix, stat):
counter = self.metrics_map.get_counter(full_name(prefix=self.prefix, name=stat))
if self.metrics_validator.test(metric_name):
full_metric_name = self.get_name(metric_name, tags)
counter = self.metrics_map.get_counter(full_metric_name)
counter.add(-count, attributes=tags)
return counter

def gauge(
self,
stat: str,
metric_name: str,
value: int | float,
rate: float = 1,
delta: bool = False,
Expand All @@ -253,7 +256,7 @@ def gauge(
"""
Record a new value for a Gauge.

:param stat: The name of the stat to update.
:param metric_name: The name of the metric to update.
:param value: The new value of stat, either a float or an int.
:param rate: value between 0 and 1 that represents the sample rate at
which the metric is going to be emitted.
Expand All @@ -271,24 +274,29 @@ def gauge(
full_name(prefix=self.prefix, name=back_compat_name), value, delta, tags
)

if self.metrics_validator.test(stat):
self.metrics_map.set_gauge_value(full_name(prefix=self.prefix, name=stat), value, delta, tags)
if self.metrics_validator.test(metric_name):
full_metric_name = self.get_name(metric_name, tags)
self.metrics_map.set_gauge_value(full_metric_name, value, delta, tags)

def timing(
self,
stat: str,
dt: DeltaType,
metric_name: str,
dt: DeltaType | None,
*,
tags: Attributes = None,
) -> None:
"""OTel does not have a native timer, stored as a Gauge whose value is number of seconds elapsed."""
if self.metrics_validator.test(stat) and name_is_otel_safe(self.prefix, stat):
if dt is None:
log.warning("The duration (dt) cannot be None. Skipping timing update.")
return
ArshiaZr marked this conversation as resolved.
Show resolved Hide resolved
if self.metrics_validator.test(metric_name):
full_metric_name = self.get_name(metric_name, tags)
if isinstance(dt, datetime.timedelta):
if metrics_consistency_on:
dt = dt.total_seconds() * 1000.0
else:
dt = dt.total_seconds()
self.metrics_map.set_gauge_value(full_name(prefix=self.prefix, name=stat), float(dt), False, tags)
self.metrics_map.set_gauge_value(full_metric_name, float(dt), False, tags)

def timer(
self,
Expand All @@ -300,6 +308,18 @@ def timer(
"""Timer context manager returns the duration and can be cancelled."""
return _OtelTimer(self, stat, tags)

def get_name(self, metric_name: str, tags: Attributes | None = None) -> str:
ArshiaZr marked this conversation as resolved.
Show resolved Hide resolved
"""Generate an OTel-safe metric name with the prefix and delimiter."""
if not metric_name:
raise InvalidStatsNameException("The stat name cannot be None or an empty string.")

base_metric_name = metric_name
ArshiaZr marked this conversation as resolved.
Show resolved Hide resolved

if not name_is_otel_safe(self.prefix, base_metric_name):
raise ValueError(f"Metric name `{base_metric_name}` is not OTel-safe.")

return full_name(name=base_metric_name, prefix=self.prefix)


class MetricsMap:
"""Stores Otel Instruments."""
Expand Down
Loading