ashb commented on code in PR #64523: URL: https://github.com/apache/airflow/pull/64523#discussion_r3388829461
########## airflow-core/src/airflow/api_fastapi/common/http_metrics.py: ########## Review Comment: Did you look at something like https://pypi.org/project/prometheus-fastapi-instrumentator/? ########## airflow-core/src/airflow/api_fastapi/common/http_paths.py: ########## Review Comment: I don't get why this was moved into it's own file? It's only used in a single place. ########## airflow-core/src/airflow/observability/metrics/stats_utils.py: ########## @@ -23,6 +23,16 @@ from airflow.configuration import conf +def is_metrics_enabled() -> bool: + return any( + ( + conf.getboolean("metrics", "statsd_datadog_enabled", fallback=False), Review Comment: ```suggestion ``` Don't need this, that only works if `statsd_on` is true. ########## airflow-core/src/airflow/config_templates/config.yml: ########## @@ -1152,6 +1152,18 @@ metrics: type: string example: ~ default: "True" + api_path_prefix_to_surface: + description: | + JSON mapping of HTTP path prefixes to API surface names used for the ``api_surface`` tag + on API metrics. Requests that do not match a configured prefix emit metrics without the + ``api_surface`` tag. + + Add prefixes to identify additional routes, such as the Execution API or routes registered + by plugins. When prefixes overlap, the most specific prefix is used. + version_added: 3.3.0 + type: string + example: '{"/api/v2": "public", "/ui": "ui", "/execution": "execution", "/my-plugin": "plugin"}' Review Comment: Why should the tags for this be user configurable? This feels like they are something we as Airflow maintainers would decide, and this isn't something a user is every going to want to configure. ########## airflow-core/src/airflow/api_fastapi/common/http_metrics.py: ########## Review Comment: If not using this, it is probably worth using the same names for the metrics. ########## airflow-core/src/airflow/api_fastapi/common/http_metrics.py: ########## @@ -0,0 +1,194 @@ +# 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. +"""HTTP API metrics middleware.""" + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING + +import structlog + +from airflow._shared.observability.metrics.stats import Stats +from airflow.configuration import conf +from airflow.exceptions import AirflowConfigException + +if TYPE_CHECKING: + from starlette.types import ASGIApp, Message, Receive, Scope, Send + +logger = structlog.get_logger(logger_name="http.metrics") + +_DEFAULT_API_PATH_PREFIX_TO_SURFACE = { + "/api/v2": "public", + "/ui": "ui", +} +_ROUTE_PATHS_BY_ROUTER_ID: dict[int, dict[object, str]] = {} + + +def _get_api_path_prefix_to_surface() -> tuple[tuple[str, str], ...]: + path_prefix_to_surface = conf.getjson( + "metrics", + "api_path_prefix_to_surface", + fallback=_DEFAULT_API_PATH_PREFIX_TO_SURFACE, + ) + if not isinstance(path_prefix_to_surface, dict): + raise AirflowConfigException("[metrics] api_path_prefix_to_surface must be a JSON object") Review Comment: This likely belongs inside `validate_config` in airflow/configuration.py, not here. ########## airflow-core/src/airflow/api_fastapi/common/http_metrics.py: ########## @@ -0,0 +1,194 @@ +# 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. +"""HTTP API metrics middleware.""" + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING + +import structlog + +from airflow._shared.observability.metrics.stats import Stats +from airflow.configuration import conf +from airflow.exceptions import AirflowConfigException + +if TYPE_CHECKING: + from starlette.types import ASGIApp, Message, Receive, Scope, Send + +logger = structlog.get_logger(logger_name="http.metrics") + +_DEFAULT_API_PATH_PREFIX_TO_SURFACE = { + "/api/v2": "public", + "/ui": "ui", +} +_ROUTE_PATHS_BY_ROUTER_ID: dict[int, dict[object, str]] = {} + + +def _get_api_path_prefix_to_surface() -> tuple[tuple[str, str], ...]: + path_prefix_to_surface = conf.getjson( + "metrics", + "api_path_prefix_to_surface", + fallback=_DEFAULT_API_PATH_PREFIX_TO_SURFACE, + ) + if not isinstance(path_prefix_to_surface, dict): + raise AirflowConfigException("[metrics] api_path_prefix_to_surface must be a JSON object") + + for prefix, surface in path_prefix_to_surface.items(): + if ( + not isinstance(prefix, str) + or not prefix.startswith("/") + or (prefix != "/" and prefix.endswith("/")) + ): + raise AirflowConfigException( + "[metrics] api_path_prefix_to_surface keys must be path prefixes that start with '/' " + "and do not end with '/'" + ) + if not isinstance(surface, str) or not surface: + raise AirflowConfigException( + "[metrics] api_path_prefix_to_surface values must be non-empty surface names" + ) + + return tuple(sorted(path_prefix_to_surface.items(), key=lambda item: len(item[0]), reverse=True)) + + +def _get_api_surface(path: str, path_prefix_to_surface: tuple[tuple[str, str], ...]) -> str | None: + for prefix, surface in path_prefix_to_surface: + if path.startswith(prefix): + return surface + return None + + +def _get_status_family(status_code: int) -> str: + return f"{status_code // 100}xx" + + +def _get_route_tag(scope: Scope) -> str: + route = scope.get("route") + route_path = getattr(route, "path", None) + if isinstance(route_path, str) and route_path: + return route_path + + router = scope.get("router") + endpoint = scope.get("endpoint") + if router is not None and endpoint is not None: + route_paths = _ROUTE_PATHS_BY_ROUTER_ID.get(id(router)) + if route_paths is None: + route_paths = { + candidate_endpoint: candidate_route_path + for candidate_route in getattr(router, "routes", ()) + for candidate_endpoint, candidate_route_path in [ + ( + getattr(candidate_route, "endpoint", None), + getattr(candidate_route, "path", None), + ) + ] + if candidate_endpoint is not None + and isinstance(candidate_route_path, str) + and candidate_route_path + } + _ROUTE_PATHS_BY_ROUTER_ID[id(router)] = route_paths + + endpoint_route_path = route_paths.get(endpoint) + if isinstance(endpoint_route_path, str) and endpoint_route_path: + return endpoint_route_path + + return "unmatched" Review Comment: Unless I'm missing something, we do this on every single request. That seems massively wasteful ########## airflow-core/tests/unit/api_fastapi/common/test_http_access_log.py: ########## @@ -55,12 +52,24 @@ async def homepage(request): raise RuntimeError("boom") return PlainTextResponse("ok") + async def api_item(request): + return PlainTextResponse("ok") + + async def ui_item(request): + return PlainTextResponse("ok") + + async def api_fail(request): + raise RuntimeError("boom") + Review Comment: New test cases, but nothing exercising them/changed about the assertions is a code smell. -- 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]
