From 44c1e7f3213bbd0610917d20613b4fd79a842592 Mon Sep 17 00:00:00 2001 From: Siegfried Weber Date: Tue, 24 Nov 2026 15:00:24 +0000 Subject: [PATCH] chore: Remove Airflow 2.9.3 from the docs and tests (#900) * chore: Remove Airflow 2.9.3 from the docs and tests * docs: Fix the formatting * tests: Fix linter warnings and remove unused files * test(opa): Fix comments and remove dead code * tests: Fix the ruff findings --- CHANGELOG.md | 2 + .../pages/getting_started/first_steps.adoc | 3 +- docs/modules/airflow/pages/index.adoc | 5 +- .../pages/usage-guide/mounting-dags.adoc | 1 - .../pages/usage-guide/reverse-proxy.adoc | 25 +-- .../airflow/partials/supported-versions.adoc | 1 - tests/templates/kuttl/commons/health.py | 26 ++- tests/templates/kuttl/commons/metrics.py | 68 +------- .../kuttl/external-access/45-assert.yaml.j2 | 13 -- .../templates/kuttl/logging/51-assert.yaml.j2 | 7 +- .../kuttl/logging/test_log_aggregation.py | 1 + .../kuttl/mount-dags-gitsync/dag_metrics.py | 20 ++- .../oidc/50-install-test-container.yaml.j2 | 6 - tests/templates/kuttl/oidc/login.py | 64 +++----- .../kuttl/opa/30-install-airflow.yaml.j2 | 3 +- tests/templates/kuttl/opa/31-opa-rules.yaml | 53 ++---- .../kuttl/opa/41-check-authorization.yaml.j2 | 6 +- ...ization_3.py => 41_check-authorization.py} | 11 +- .../kuttl/opa/41_check-authorization_2.py | 154 ------------------ .../kuttl/openlineage/check_lineage.py | 5 +- .../remote-logging/remote-logging-metrics.py | 18 +- tests/templates/kuttl/smoke/60-assert.yaml.j2 | 7 +- tests/templates/kuttl/smoke/task-logs.py | 5 - .../kuttl/triggerer/triggerer_metrics.py | 67 +------- .../templates/kuttl/versioning/dag_metrics.py | 28 ++-- tests/test-definition.yaml | 1 - 26 files changed, 122 insertions(+), 478 deletions(-) rename tests/templates/kuttl/opa/{41_check-authorization_3.py => 41_check-authorization.py} (96%) delete mode 100644 tests/templates/kuttl/opa/41_check-authorization_2.py mode change 100644 => 100755 tests/templates/kuttl/openlineage/check_lineage.py mode change 100644 => 100755 tests/templates/kuttl/smoke/task-logs.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b8918d74..43d0bd802 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -84,6 +84,7 @@ ### Removed - Removed airflow `3.1.6` ([#865]). +- Removed airflow `2.9.3` ([#900]). [#814]: https://github.com/stackabletech/airflow-operator/pull/814 [#821]: https://github.com/stackabletech/airflow-operator/pull/821 @@ -117,6 +118,7 @@ [#887]: https://github.com/stackabletech/airflow-operator/pull/887 [#888]: https://github.com/stackabletech/airflow-operator/pull/888 [#892]: https://github.com/stackabletech/airflow-operator/pull/892 +[#900]: https://github.com/stackabletech/airflow-operator/pull/900 ## [26.7.0] - 2026-07-21 diff --git a/docs/modules/airflow/pages/getting_started/first_steps.adoc b/docs/modules/airflow/pages/getting_started/first_steps.adoc index c210ec114..6ed0a6313 100644 --- a/docs/modules/airflow/pages/getting_started/first_steps.adoc +++ b/docs/modules/airflow/pages/getting_started/first_steps.adoc @@ -41,7 +41,8 @@ An Airflow cluster is made up of several components, two of which are optional: * `executors`: the CeleryExecutor or KubernetesExecutor nodes over which the job workload is distributed by the scheduler * `scheduler`: responsible for triggering jobs and persisting their metadata to the backend database * `dagProcessors`: (Optional) responsible for monitoring, parsing and preparing DAGs for processing. -If this role is not specified then the process will be started as a scheduler subprocess (Airflow 2.x), or as a standalone process in the same container as the scheduler (Airflow 3.x+). We recommend specifying this role for production settings as running multiple processes in the same container complicates proper supervision. +If this role is not specified then the process will be started as a standalone process in the same container as the scheduler. +We recommend specifying this role for production settings as running multiple processes in the same container complicates proper supervision. * `triggerers`: (Optional) DAGs making use of deferrable operators can be used together with one or more triggerer processes to free up worker slots. This deferral process is also useful for providing a measure of high availability diff --git a/docs/modules/airflow/pages/index.adoc b/docs/modules/airflow/pages/index.adoc index 0f88fafa8..115abe959 100644 --- a/docs/modules/airflow/pages/index.adoc +++ b/docs/modules/airflow/pages/index.adoc @@ -70,9 +70,8 @@ kubernetesExecutors: === DAG-Processors -In Airflow 2.x, a DAG-Processor can be started either as a standalone process or a subprocess within the scheduler component. -For Airflow 3.x+ it _must_ be started as a standalone process, either in a separate container or in the scheduler container. -In each case the default will be applied (subprocess or combined in the scheduler container) if the role is not specified. +A DAG-Processor _must_ be started as a standalone process, either in a separate container or in the scheduler container. +If the role is not specified, it is combined into the scheduler container. === Triggerers diff --git a/docs/modules/airflow/pages/usage-guide/mounting-dags.adoc b/docs/modules/airflow/pages/usage-guide/mounting-dags.adoc index cad1d3382..b37ad2834 100644 --- a/docs/modules/airflow/pages/usage-guide/mounting-dags.adoc +++ b/docs/modules/airflow/pages/usage-guide/mounting-dags.adoc @@ -111,7 +111,6 @@ Use DAG bundles when: === Prerequisites -* Airflow 3.x (the `dag_bundle_config_list` setting does not exist in Airflow 2.x). * Each `GitDagBundle` requires an https://airflow.apache.org/docs/apache-airflow-providers-git/stable/connections/git.html[Airflow Git connection] - even for public repositories. For public repos, the connection only needs a `host` (the repository URL) and no credentials. Connections can be created via the Airflow UI, CLI, a https://airflow.apache.org/docs/apache-airflow/stable/security/secrets/secrets-backend/index.html[secrets backend], or - as shown in the example below - via `AIRFLOW_CONN_*` environment variables. diff --git a/docs/modules/airflow/pages/usage-guide/reverse-proxy.adoc b/docs/modules/airflow/pages/usage-guide/reverse-proxy.adoc index d2bfbffc2..5f5ae5330 100644 --- a/docs/modules/airflow/pages/usage-guide/reverse-proxy.adoc +++ b/docs/modules/airflow/pages/usage-guide/reverse-proxy.adoc @@ -26,9 +26,7 @@ spec: the only entry in the list: combining it with other entries is rejected, since it would silently degrade to trusting only those other entries. -On Airflow 3.x the operator starts the api-server with `--proxy-headers` and restricts the headers -to the listed peers. Airflow 2.x has no equivalent restriction: see -<>. +The operator starts the api-server with `--proxy-headers` and restricts the headers to the listed peers. == Choosing the value @@ -56,23 +54,8 @@ themselves. WARNING: A peer that is trusted can set the client address that ends up in the webserver's access log. Do not list ranges wider than the proxies you operate. -[#airflow-2-x-has-no-peer-restriction] -== Airflow 2.x has no peer restriction - -Airflow 2.x's webserver has no analogue support for trusted network addresses. Once enabled, it -unconditionally trusts `X-Forwarded-*` from *any* peer, the same as `trustedProxies: ["*"]` on 3.x. - -This means that for Airflow 2.x, `trustedProxies: ["*"]` is the only valid configuration. Using -any other value than `*` will lead the operator to reject reconciliation. - == Interaction with overrides -On Airflow 3.x, the operator sets `FORWARDED_ALLOW_IPS` from this field, before `envOverrides` are -applied -- so an `envOverrides` entry for that variable wins over the value derived from -`trustedProxies`. This override only takes effect while `trustedProxies` is non-empty: an empty -list means the api-server is not started with `--proxy-headers` at all, so uvicorn never installs -the middleware that reads `FORWARDED_ALLOW_IPS`, and the override has no effect regardless of its -value. - -On Airflow 2.x, the same applies to `AIRFLOW__WEBSERVER__ENABLE_PROXY_FIX` and -`AIRFLOW__WEBSERVER__PROXY_FIX_X_FOR`. +The operator sets `FORWARDED_ALLOW_IPS` from this field, before `envOverrides` are applied -- so an `envOverrides` entry for that variable wins over the value derived from `trustedProxies`. +This override only takes effect while `trustedProxies` is non-empty: +an empty list means the api-server is not started with `--proxy-headers` at all, so uvicorn never installs the middleware that reads `FORWARDED_ALLOW_IPS`, and the override has no effect regardless of its value. diff --git a/docs/modules/airflow/partials/supported-versions.adoc b/docs/modules/airflow/partials/supported-versions.adoc index 209ddc9a9..ff65edb34 100644 --- a/docs/modules/airflow/partials/supported-versions.adoc +++ b/docs/modules/airflow/partials/supported-versions.adoc @@ -5,4 +5,3 @@ - 3.3.2 - 3.2.2 (deprecated) - 3.0.6 (LTS) -- 2.9.3 (deprecated) diff --git a/tests/templates/kuttl/commons/health.py b/tests/templates/kuttl/commons/health.py index 4f7d56d78..e47e1a826 100755 --- a/tests/templates/kuttl/commons/health.py +++ b/tests/templates/kuttl/commons/health.py @@ -1,22 +1,17 @@ #!/usr/bin/env python +import argparse import logging -import requests import sys import time -import argparse + +import requests # Every component of the health endpoint reports its heartbeat under a key named # after itself, e.g. `latest_scheduler_heartbeat` for the `scheduler`. The # exception is `metadatabase`, which reports a status only. HEARTBEAT_KEY = "latest_{}_heartbeat".format - -def health_url(airflow_version): - """Return the health endpoint of the given Airflow version.""" - if airflow_version and airflow_version.startswith("3"): - return "http://airflow-webserver:8080/api/v2/monitor/health" - else: - return "http://airflow-webserver:8080/api/v1/health" +HEALTH_URL = "http://airflow-webserver:8080/api/v2/monitor/health" def component_states(health, components): @@ -73,7 +68,7 @@ def all_healthy(states, baseline): ) opts = parser.parse_args() - url = health_url(opts.airflow_version) + url = HEALTH_URL deadline = time.monotonic() + opts.timeout if opts.timeout else None baseline = None @@ -103,13 +98,12 @@ def all_healthy(states, baseline): except requests.exceptions.Timeout: print(f"Connection timed out, retrying attempt no [{count}] ....") except requests.ConnectionError as e: - print(f"Connection Error: {str(e)}") + print(f"Connection Error: {e!s}") except requests.RequestException as e: - print(f"General Error: {str(e)}") - except Exception as e: - print( - f"General error occurred {str(e)}, retrying attempt no [{count}] ...." - ) + print(f"General Error: {e!s}") + # Retry on anything: this loop polls until the endpoint reports healthy. + except Exception as e: # noqa: BLE001 + print(f"General error occurred {e!s}, retrying attempt no [{count}] ....") if deadline and time.monotonic() > deadline: sys.exit( diff --git a/tests/templates/kuttl/commons/metrics.py b/tests/templates/kuttl/commons/metrics.py index b8ef66c42..e8f9c4943 100755 --- a/tests/templates/kuttl/commons/metrics.py +++ b/tests/templates/kuttl/commons/metrics.py @@ -1,11 +1,12 @@ #!/usr/bin/env python -import requests -import time -import sys -from datetime import datetime, timezone import argparse import logging +import sys +import time +from datetime import UTC, datetime + +import requests def exception_handler(exception_type, exception, traceback): @@ -42,7 +43,7 @@ def assert_dag_started(rest_url, headers, dag_id, dag_run_id): def metrics_v3(role_group: str) -> None: - now = datetime.now(timezone.utc) + now = datetime.now(UTC) ts = now.strftime("%Y-%m-%dT%H:%M:%S.%f") + now.strftime("%z") # Trigger a DAG run to create metrics @@ -114,58 +115,6 @@ def metrics_v3(role_group: str) -> None: sys.exit(1) -def metrics_v2(role_group: str) -> None: - # Trigger a DAG run to create metrics - dag_id = "example_trigger_target_dag" - dag_conf = {"message": "Hello World"} - - rest_url = f"http://airflow-webserver-{role_group}-headless:8080/api/v1" - auth = ("airflow", "airflow") - - # allow a few moments for the DAGs to be registered to all roles - time.sleep(10) - - response = requests.patch( - f"{rest_url}/dags/{dag_id}", auth=auth, json={"is_paused": False} - ) - response = requests.post( - f"{rest_url}/dags/{dag_id}/dagRuns", auth=auth, json={"conf": dag_conf} - ) - - # Test the DAG in a loop. Each time we call the script a new job will be started: we can avoid - # or minimize this by looping over the check instead. - iterations = 4 - loop = 0 - while True: - assert response.status_code == 200, "DAG run could not be triggered." - # Wait for the metrics to be consumed by the statsd-exporter - time.sleep(5) - # (disable line-break flake checks) - if ( - (assert_metric("scheduler", role_group, "airflow_scheduler_heartbeat")) - and ( - assert_metric( - "webserver", - role_group, - "airflow_task_instance_created_BashOperator", - ) - ) # noqa: W503, W504 - and ( - assert_metric( - "scheduler", - role_group, - "airflow_dagrun_duration_success_example_trigger_target_dag_count", - ) - ) - ): # noqa: W503, W504 - break - time.sleep(10) - loop += 1 - if loop == iterations: - # force re-try of script - sys.exit(1) - - if __name__ == "__main__": log_level = "DEBUG" logging.basicConfig( @@ -181,7 +130,4 @@ def metrics_v2(role_group: str) -> None: parser.add_argument("--airflow-version", type=str, help="Airflow version") opts = parser.parse_args() - if opts.airflow_version and opts.airflow_version.startswith("3"): - metrics_v3(opts.role_group) - else: - metrics_v2(opts.role_group) + metrics_v3(opts.role_group) diff --git a/tests/templates/kuttl/external-access/45-assert.yaml.j2 b/tests/templates/kuttl/external-access/45-assert.yaml.j2 index 4b998a540..7e317c464 100644 --- a/tests/templates/kuttl/external-access/45-assert.yaml.j2 +++ b/tests/templates/kuttl/external-access/45-assert.yaml.j2 @@ -2,18 +2,6 @@ apiVersion: kuttl.dev/v1beta1 kind: TestAssert timeout: 600 -{% if test_scenario['values']['airflow'].startswith("2") %} -commands: - # ProxyFix must be enabled on Airflow 2 - - script: | - kubectl -n $NAMESPACE get statefulset airflow-webserver-default \ - -o jsonpath='{.spec.template.spec.containers[?(@.name=="airflow")].env[?(@.name=="AIRFLOW__WEBSERVER__ENABLE_PROXY_FIX")].value}' \ - | grep -qx 'True' - - script: | - kubectl -n $NAMESPACE get statefulset airflow-webserver-default \ - -o jsonpath='{.spec.template.spec.containers[?(@.name=="airflow")].env[?(@.name=="AIRFLOW__WEBSERVER__PROXY_FIX_X_FOR")].value}' \ - | grep -qx '1' -{% else %} commands: # The api-server must be started with --proxy-headers ... - script: | @@ -25,4 +13,3 @@ commands: kubectl -n $NAMESPACE get statefulset airflow-webserver-default \ -o jsonpath='{.spec.template.spec.containers[?(@.name=="airflow")].env[?(@.name=="FORWARDED_ALLOW_IPS")].value}' \ | grep -qx '\*' -{% endif %} diff --git a/tests/templates/kuttl/logging/51-assert.yaml.j2 b/tests/templates/kuttl/logging/51-assert.yaml.j2 index 6c1092bb8..47a12ce6a 100644 --- a/tests/templates/kuttl/logging/51-assert.yaml.j2 +++ b/tests/templates/kuttl/logging/51-assert.yaml.j2 @@ -9,11 +9,8 @@ timeout: 480 {% else %} {% set airflow_version = test_scenario['values']['airflow'] %} {% endif %} -{% set components = "--component scheduler" %} -{% if airflow_version.startswith("3") %} -{# With 3.x the scheduler container also runs the dag-processor. #} -{% set components = components ~ " --component dag_processor" %} -{% endif %} +{# The scheduler container also runs the dag-processor. #} +{% set components = "--component scheduler --component dag_processor" %} commands: # Called twice so that the webserver logs more than one request, which the # log aggregation is asserted on further down. diff --git a/tests/templates/kuttl/logging/test_log_aggregation.py b/tests/templates/kuttl/logging/test_log_aggregation.py index ad114c3d5..fc0a421b3 100755 --- a/tests/templates/kuttl/logging/test_log_aggregation.py +++ b/tests/templates/kuttl/logging/test_log_aggregation.py @@ -1,3 +1,4 @@ +#!/usr/bin/env python import json import subprocess diff --git a/tests/templates/kuttl/mount-dags-gitsync/dag_metrics.py b/tests/templates/kuttl/mount-dags-gitsync/dag_metrics.py index d2d263509..0d5ba7a3f 100755 --- a/tests/templates/kuttl/mount-dags-gitsync/dag_metrics.py +++ b/tests/templates/kuttl/mount-dags-gitsync/dag_metrics.py @@ -1,10 +1,17 @@ #!/usr/bin/env python -import requests -import time -import sys import logging -from datetime import datetime, timezone +import sys +import time +from datetime import UTC, datetime + +import requests + +logging.basicConfig( + level="DEBUG", format="%(asctime)s %(levelname)s: %(message)s", stream=sys.stdout +) + +log = logging.getLogger(__name__) def assert_metric(role, metric): @@ -17,7 +24,7 @@ def assert_metric(role, metric): return metric in metric_response.text -now = datetime.now(timezone.utc) +now = datetime.now(UTC) ts = now.strftime("%Y-%m-%dT%H:%M:%S.%f") + now.strftime("%z") # Trigger a DAG run to create metrics @@ -63,9 +70,8 @@ def assert_metric(role, metric): # Wait for the metrics to be consumed by the statsd-exporter time.sleep(5) -logging.info(f"Response code: {response.status_code}") +log.info(f"Response code: {response.status_code}") assert response.status_code == 200, "DAG run could not be triggered." # Worker is not deployed with the kubernetes executor so retrieve success metric from scheduler -# (disable line-break flake checks) assert_metric("scheduler", "airflow_scheduler_heartbeat") assert_metric("scheduler", "airflow_dagrun_duration_success_sparkapp_dag_count") diff --git a/tests/templates/kuttl/oidc/50-install-test-container.yaml.j2 b/tests/templates/kuttl/oidc/50-install-test-container.yaml.j2 index 84a517897..56f6e71a7 100644 --- a/tests/templates/kuttl/oidc/50-install-test-container.yaml.j2 +++ b/tests/templates/kuttl/oidc/50-install-test-container.yaml.j2 @@ -76,12 +76,6 @@ spec: valueFrom: fieldRef: fieldPath: metadata.namespace - - name: AIRFLOW_VERSION -{% if test_scenario['values']['airflow-latest'].find(",") > 0 %} - value: "{{ test_scenario['values']['airflow-latest'].split(',')[0] }}" -{% else %} - value: "{{ test_scenario['values']['airflow-latest'] }}" -{% endif %} volumes: - name: tls diff --git a/tests/templates/kuttl/oidc/login.py b/tests/templates/kuttl/oidc/login.py index dc5a04408..67709c843 100644 --- a/tests/templates/kuttl/oidc/login.py +++ b/tests/templates/kuttl/oidc/login.py @@ -1,9 +1,10 @@ # $NAMESPACE will be replaced with the namespace of the test case. import logging -import requests -import sys import os +import sys + +import requests from bs4 import BeautifulSoup logging.basicConfig( @@ -23,29 +24,20 @@ def assert_startwith(a, b, msg): raise AssertionError(f"{msg}\n\tleft: {a}\n\tright: {b}") -def login_page(base_url: str, airflow_version: str) -> str: - if airflow_version.startswith("3"): - return f"{base_url}/auth/login/keycloak?next=" - else: - return f"{base_url}/login/keycloak?next=" +def login_page(base_url: str) -> str: + return f"{base_url}/auth/login/keycloak?next=" -def userinfo_page(base_url: str, airflow_version: str) -> str: - if airflow_version.startswith("3"): - return f"{base_url}/auth/users/userinfo/" - else: - return f"{base_url}/users/userinfo/" +def userinfo_page(base_url: str) -> str: + return f"{base_url}/auth/users/userinfo/" -def auth_cookie(session: requests.Session, airflow_version: str): - # Airflow 3's api-server authenticates via this JWT cookie; there is no equivalent on - # Airflow 2, which uses Flask's own session cookie instead. - if not airflow_version.startswith("3"): - return None +def auth_cookie(session: requests.Session): + # The api-server authenticates via this JWT cookie. return next((c for c in session.cookies if c.name == "_token"), None) -def login(url: str, airflow_version: str) -> requests.Session: +def login(url: str) -> requests.Session: """Log in to Airflow via Keycloak at the given base URL and check that the OIDC data Keycloak provides ends up correctly reflected in Airflow. Returns the session so callers can inspect e.g. cookies afterwards.""" @@ -53,7 +45,7 @@ def login(url: str, airflow_version: str) -> requests.Session: session = requests.Session() # Click on "Sign In with keycloak" in Airflow - login_response = session.get(login_page(url, airflow_version)) + login_response = session.get(login_page(url)) assert login_response.ok, "Redirection from Airflow to Keycloak failed" @@ -76,7 +68,7 @@ def login(url: str, airflow_version: str) -> requests.Session: ) # Open the user information page in Airflow - userinfo_url = userinfo_page(url, airflow_version) + userinfo_url = userinfo_page(url) userinfo_response = session.get(userinfo_url) assert userinfo_response.ok, "Retrieving user information failed" @@ -106,19 +98,16 @@ def login(url: str, airflow_version: str) -> requests.Session: return session -airflow_version = os.environ["AIRFLOW_VERSION"] - # Log in directly against the webserver, bypassing the reverse proxy. -direct_session = login("http://airflow-webserver:8080", airflow_version) +direct_session = login("http://airflow-webserver:8080") log.info("Direct OIDC login test passed") # The webserver is plain HTTP here, so its auth cookie must not be marked Secure. -direct_cookie = auth_cookie(direct_session, airflow_version) -if airflow_version.startswith("3"): - assert direct_cookie is not None, "Expected an auth cookie after a successful login" - assert not direct_cookie.secure, ( - "The auth cookie must not be marked Secure when accessed directly over HTTP" - ) +direct_cookie = auth_cookie(direct_session) +assert direct_cookie is not None, "Expected an auth cookie after a successful login" +assert not direct_cookie.secure, ( + "The auth cookie must not be marked Secure when accessed directly over HTTP" +) # Log in again through the TLS-terminating reverse proxy installed in # 45-install-reverse-proxy.yaml, which is covered by trustedProxies in install-airflow.yaml.j2. @@ -129,18 +118,15 @@ def login(url: str, airflow_version: str) -> requests.Session: proxy_url = ( f"https://airflow-reverse-proxy.{os.environ['NAMESPACE']}.svc.cluster.local:8443" ) -proxied_session = login(proxy_url, airflow_version) +proxied_session = login(proxy_url) log.info("Reverse-proxied OIDC login test passed") -proxied_cookie = auth_cookie(proxied_session, airflow_version) -if airflow_version.startswith("3"): - assert proxied_cookie is not None, ( - "Expected an auth cookie after a successful login" - ) - assert proxied_cookie.secure, ( - "The auth cookie must be marked Secure when trustedProxies allows the webserver to " - "trust the reverse proxy's X-Forwarded-Proto: https" - ) +proxied_cookie = auth_cookie(proxied_session) +assert proxied_cookie is not None, "Expected an auth cookie after a successful login" +assert proxied_cookie.secure, ( + "The auth cookie must be marked Secure when trustedProxies allows the webserver to " + "trust the reverse proxy's X-Forwarded-Proto: https" +) log.info("OIDC login test passed") diff --git a/tests/templates/kuttl/opa/30-install-airflow.yaml.j2 b/tests/templates/kuttl/opa/30-install-airflow.yaml.j2 index 2ac453603..789585b12 100644 --- a/tests/templates/kuttl/opa/30-install-airflow.yaml.j2 +++ b/tests/templates/kuttl/opa/30-install-airflow.yaml.j2 @@ -73,9 +73,8 @@ spec: configOverrides: webserver_config.py: WTF_CSRF_ENABLED: "False" # Allow "POST /login/" without CSRF token - AUTH_OPA_CACHE_MAXSIZE: "0" # Airflow 2: Disable decision caching for easy debugging envOverrides: - AIRFLOW__CORE__AUTH_OPA_CACHE_MAXSIZE: "0" # Airflow 3: Disable decision caching for easy debugging + AIRFLOW__CORE__AUTH_OPA_CACHE_MAXSIZE: "0" # Disable decision caching for easy debugging roleGroups: default: replicas: 1 diff --git a/tests/templates/kuttl/opa/31-opa-rules.yaml b/tests/templates/kuttl/opa/31-opa-rules.yaml index f9f1ab099..df731327f 100644 --- a/tests/templates/kuttl/opa/31-opa-rules.yaml +++ b/tests/templates/kuttl/opa/31-opa-rules.yaml @@ -12,13 +12,10 @@ data: default is_authorized_configuration := false default is_authorized_connection := false default is_authorized_dag := false - # This is no longer present in Airflow 3 - default is_authorized_dataset := false default is_authorized_pool := false default is_authorized_variable := false default is_authorized_view := false default is_authorized_custom_view := false - # These are new in Airflow 3 default is_authorized_backfill := false default is_authorized_asset := false default is_authorized_asset_alias := false @@ -34,18 +31,12 @@ data: is_authorized_configuration if { input.user.name == "airflow" } - is_authorized_configuration if { - input.user.name == "airflow" - } is_authorized_connection if { input.user.name == "airflow" } is_authorized_dag if { input.user.name == "airflow" } - is_authorized_dataset if { - input.user.name == "airflow" - } is_authorized_pool if { input.user.name == "airflow" } @@ -68,7 +59,7 @@ data: input.user.name == "airflow" } - # GET /api/v1/config + # GET /api/v2/config is_authorized_configuration if { input.method == "GET" input.details.section == null @@ -76,7 +67,7 @@ data: input.user.name == "jane.doe" } - # GET /api/v1/config?section=core + # GET /api/v2/config/section/core/option/dags_folder is_authorized_configuration if { input.method == "GET" input.details.section == "core" @@ -84,7 +75,7 @@ data: input.user.name == "jane.doe" } - # GET /api/v1/connections + # GET /api/v2/connections is_authorized_connection if { input.method == "GET" input.details.conn_id == null @@ -92,7 +83,7 @@ data: input.user.name == "jane.doe" } - # GET /api/v1/connections/postgres_default + # GET /api/v2/connections/postgres_default is_authorized_connection if { input.method == "GET" input.details.conn_id == "postgres_default" @@ -100,7 +91,7 @@ data: input.user.name == "jane.doe" } - # GET /api/v1/dags/example_trigger_target_dag + # GET /api/v2/dags/example_trigger_target_dag is_authorized_dag if { input.method == "GET" input.access_entity == null @@ -109,18 +100,18 @@ data: input.user.name == "jane.doe" } - # GET /api/v1/dags/~/dagRuns + # GET /api/v2/dags/~/dagRuns is_authorized_dag if { input.method == "GET" input.access_entity == "RUN" - # Airflow 2 sets this to null - # Ignore for now so this rule can be used with Airflow 2 and 3 - # input.details.id == "~" + # Airflow maps the `~` wildcard to `None` before it calls the auth + # manager, so the DAG id arrives here as null rather than as "~". + input.details.id == null input.user.name == "jane.doe" } - # GET /api/v1/dags/example_trigger_target_dag/dagRuns + # GET /api/v2/dags/example_trigger_target_dag/dagRuns is_authorized_dag if { input.method == "GET" input.access_entity == "RUN" @@ -129,23 +120,7 @@ data: input.user.name == "jane.doe" } - # GET /api/v1/datasets - is_authorized_dataset if { - input.method == "GET" - input.details.uri == null - - input.user.name == "jane.doe" - } - - # GET /api/v1/datasets/s3%3A%2F%2Fdag1%2Foutput_1.txt - is_authorized_dataset if { - input.method == "GET" - input.details.uri == "s3://dag1/output_1.txt" - - input.user.name == "jane.doe" - } - - # GET /api/v1/pools + # GET /api/v2/pools is_authorized_pool if { input.method == "GET" input.details.name == null @@ -153,7 +128,7 @@ data: input.user.name == "jane.doe" } - # GET /api/v1/pools/default_pool + # GET /api/v2/pools/default_pool is_authorized_pool if { input.method == "GET" input.details.name == "default_pool" @@ -161,7 +136,7 @@ data: input.user.name == "jane.doe" } - # POST /api/v1/variables + # POST /api/v2/variables is_authorized_variable if { input.method == "POST" input.details.key == null @@ -169,7 +144,7 @@ data: input.user.name == "jane.doe" } - # GET /api/v1/variables/myVar + # GET /api/v2/variables/myVar is_authorized_variable if { input.method == "GET" input.details.key == "myVar" diff --git a/tests/templates/kuttl/opa/41-check-authorization.yaml.j2 b/tests/templates/kuttl/opa/41-check-authorization.yaml.j2 index 1f2cece3f..f2f392be0 100644 --- a/tests/templates/kuttl/opa/41-check-authorization.yaml.j2 +++ b/tests/templates/kuttl/opa/41-check-authorization.yaml.j2 @@ -6,9 +6,5 @@ metadata: commands: - script: > kubectl cp -{% if test_scenario['values']['airflow'].startswith("2") %} - 41_check-authorization_2.py -{% else %} - 41_check-authorization_3.py -{% endif %} + 41_check-authorization.py $NAMESPACE/test-runner-0:/stackable/check-authorization.py diff --git a/tests/templates/kuttl/opa/41_check-authorization_3.py b/tests/templates/kuttl/opa/41_check-authorization.py similarity index 96% rename from tests/templates/kuttl/opa/41_check-authorization_3.py rename to tests/templates/kuttl/opa/41_check-authorization.py index 55a20fe30..ee440270e 100644 --- a/tests/templates/kuttl/opa/41_check-authorization_3.py +++ b/tests/templates/kuttl/opa/41_check-authorization.py @@ -133,13 +133,6 @@ def test_is_authorized_dag(): check_api_authorization("GET", "dags/example_trigger_target_dag/dagRuns") -def test_is_authorized_dataset(): - # uri == null - check_api_authorization("GET", "datasets") - # uri != null - check_api_authorization("GET", "datasets/s3%3A%2F%2Fdag1%2Foutput_1.txt") - - def test_is_authorized_pool(): # name == null check_api_authorization("GET", "pools") @@ -148,11 +141,11 @@ def test_is_authorized_pool(): def test_is_authorized_variable(): - # key != null + # key == null check_api_authorization( "POST", "variables", 201, data={"key": "myVar", "value": "1"} ) - # key == null + # key != null check_api_authorization("GET", "variables/myVar") diff --git a/tests/templates/kuttl/opa/41_check-authorization_2.py b/tests/templates/kuttl/opa/41_check-authorization_2.py deleted file mode 100644 index c38a81300..000000000 --- a/tests/templates/kuttl/opa/41_check-authorization_2.py +++ /dev/null @@ -1,154 +0,0 @@ -import logging -import requests -import sys - - -logging.basicConfig( - level="DEBUG", format="%(asctime)s %(levelname)s: %(message)s", stream=sys.stdout -) - -# Jane Doe has access to specific resources. -user_jane_doe = { - "first_name": "Jane", - "last_name": "Doe", - "username": "jane.doe", - "email": "jane.doe@stackable.tech", - "roles": [{"name": "User"}], - "password": "T8mn72D9", -} -# Richard Roe has no access. -user_richard_roe = { - "first_name": "Richard", - "last_name": "Roe", - "username": "richard.roe", - "email": "richard.roe@stackable.tech", - "roles": [{"name": "User"}], - "password": "NvfpU518", -} - -url = "http://airflow-webserver:8080" - - -def check_api_authorization_for_user( - user, expected_status_code, method, endpoint, data=None, api="api/v1" -): - api_url = f"{url}/{api}" - - auth = (user["username"], user["password"]) - response = requests.request(method, f"{api_url}/{endpoint}", auth=auth, json=data) - assert response.status_code == expected_status_code - - -def check_api_authorization(method, endpoint, data=None, api="api/v1"): - check_api_authorization_for_user( - user_jane_doe, 200, method=method, endpoint=endpoint, data=data, api=api - ) - check_api_authorization_for_user( - user_richard_roe, 403, method=method, endpoint=endpoint, data=data, api=api - ) - - -def check_website_authorization_for_user(user, expected_status_code): - username = user["username"] - password = user["password"] - with requests.Session() as session: - login_response = session.post( - f"{url}/login/", - data=f"username={username}&password={password}", - allow_redirects=False, - headers={"Content-Type": "application/x-www-form-urlencoded"}, - ) - assert login_response.ok, f"Login for {username} failed" - home_response = session.get(f"{url}/home", allow_redirects=False) - assert home_response.status_code == expected_status_code, ( - f"GET /home returned status code {home_response.status_code}, but {expected_status_code} was expected." - ) - - -def test_is_authorized_configuration(): - # section == null - check_api_authorization("GET", "config") - # section != null - check_api_authorization("GET", "config?section=core") - - -def test_is_authorized_connection(): - # conn_id == null - check_api_authorization("GET", "connections") - # conn_id != null - check_api_authorization("GET", "connections/postgres_default") - - -def test_is_authorized_dag(): - # access_entity == null and id == null - # There is no API endpoint to test this case. - - # access_entity == null and id != null - check_api_authorization("GET", "dags/example_trigger_target_dag") - - # access_entity != null and id == null - # Check "GET /dags/~/dagRuns" because access to "GET /dags" is always allowed - check_api_authorization("GET", "dags/~/dagRuns") - - # access_entity != null and id != null - check_api_authorization("GET", "dags/example_trigger_target_dag/dagRuns") - - -def test_is_authorized_dataset(): - # uri == null - check_api_authorization("GET", "datasets") - # uri != null - check_api_authorization("GET", "datasets/s3%3A%2F%2Fdag1%2Foutput_1.txt") - - -def test_is_authorized_pool(): - # name == null - check_api_authorization("GET", "pools") - # name != null - check_api_authorization("GET", "pools/default_pool") - - -def test_is_authorized_variable(): - # key != null - check_api_authorization("POST", "variables", data={"key": "myVar", "value": "1"}) - # key == null - check_api_authorization("GET", "variables/myVar") - - -def test_is_authorized_view(): - check_website_authorization_for_user(user_jane_doe, 200) - check_website_authorization_for_user(user_richard_roe, 403) - - -def test_is_authorized_custom_view(): - user_jane_doe_patched = user_jane_doe.copy() - user_jane_doe_patched["email"] = "jane@stackable.tech" - check_api_authorization_for_user( - user_jane_doe, - 200, - "PATCH", - "users/jane.doe?update_mask=email", - data=user_jane_doe_patched, - api="/auth/fab/v1", - ) - - user_richard_roe_patched = user_richard_roe.copy() - user_richard_roe_patched["email"] = "richard@stackable.tech" - check_api_authorization_for_user( - user_richard_roe, - 403, - "PATCH", - "users/richard.roe?update_mask=email", - data=user_richard_roe_patched, - api="/auth/fab/v1", - ) - - -test_is_authorized_configuration() -test_is_authorized_connection() -test_is_authorized_dag() -test_is_authorized_dataset() -test_is_authorized_pool() -test_is_authorized_variable() -test_is_authorized_view() -test_is_authorized_custom_view() diff --git a/tests/templates/kuttl/openlineage/check_lineage.py b/tests/templates/kuttl/openlineage/check_lineage.py old mode 100644 new mode 100755 index 274898d95..8627abf21 --- a/tests/templates/kuttl/openlineage/check_lineage.py +++ b/tests/templates/kuttl/openlineage/check_lineage.py @@ -9,7 +9,7 @@ import argparse import sys import time -from datetime import datetime, timezone +from datetime import UTC, datetime import requests import urllib3 @@ -33,7 +33,7 @@ def trigger_dag(base_url: str, headers: dict) -> bool: # Airflow 3 API expects an ISO logical_date (a null value can be rejected with a 422). # Returns True only if the run was actually accepted (2xx); the DAG may not be registered yet # (ConfigMap mount + dag-processor parse takes time), in which case the caller must retry. - now = datetime.now(timezone.utc) + now = datetime.now(UTC) logical_date = now.strftime("%Y-%m-%dT%H:%M:%S.%f") + now.strftime("%z") patch_resp = requests.patch( f"{base_url}/api/v2/dags/{DAG_ID}", @@ -97,6 +97,7 @@ def receiver_has_lineage(receiver_url: str) -> bool: if triggered and receiver_has_lineage(opts.receiver_url): print("OpenLineage events for the DAG were received.") sys.exit(0) + # Retry on anything: this loop polls until the lineage events arrive. except Exception as e: # noqa: BLE001 print(f"Retrying after error: {e}") diff --git a/tests/templates/kuttl/remote-logging/remote-logging-metrics.py b/tests/templates/kuttl/remote-logging/remote-logging-metrics.py index d810e1620..f34963808 100755 --- a/tests/templates/kuttl/remote-logging/remote-logging-metrics.py +++ b/tests/templates/kuttl/remote-logging/remote-logging-metrics.py @@ -1,11 +1,12 @@ #!/usr/bin/env python -import requests -import time -import sys -from datetime import datetime, timezone import argparse import logging +import sys +import time +from datetime import UTC, datetime + +import requests def exception_handler(exception_type, exception, traceback): @@ -86,7 +87,7 @@ def prefix_is_matched( def remote_logging(airflow_version: str) -> None: - now = datetime.now(timezone.utc) + now = datetime.now(UTC) ts = now.strftime("%Y-%m-%dT%H:%M:%S.%f") + now.strftime("%z") # Trigger a DAG run to create logs @@ -180,9 +181,4 @@ def remote_logging(airflow_version: str) -> None: parser.add_argument("--airflow-version", type=str, help="Airflow version") opts = parser.parse_args() - if opts.airflow_version and not opts.airflow_version.startswith("2."): - remote_logging(opts.airflow_version) - else: - # should not happen as we are using airflow-latest - print("Remote logging is not tested for version < 3.x!") - sys.exit(1) + remote_logging(opts.airflow_version) diff --git a/tests/templates/kuttl/smoke/60-assert.yaml.j2 b/tests/templates/kuttl/smoke/60-assert.yaml.j2 index 2a39317de..af7eefca9 100644 --- a/tests/templates/kuttl/smoke/60-assert.yaml.j2 +++ b/tests/templates/kuttl/smoke/60-assert.yaml.j2 @@ -9,11 +9,8 @@ timeout: 480 {% else %} {% set airflow_version = test_scenario['values']['airflow'] %} {% endif %} -{% set components = "--component scheduler --component triggerer" %} -{% if airflow_version.startswith("3") %} -{# Only 3.x runs the dag-processor as a process of its own. #} -{% set components = components ~ " --component dag_processor" %} -{% endif %} +{# The dag-processor runs as a process of its own. #} +{% set components = "--component scheduler --component triggerer --component dag_processor" %} commands: - script: | kubectl exec -n $NAMESPACE test-airflow-python-0 -- python /tmp/health.py \ diff --git a/tests/templates/kuttl/smoke/task-logs.py b/tests/templates/kuttl/smoke/task-logs.py old mode 100644 new mode 100755 index 24b822a28..c18dfb462 --- a/tests/templates/kuttl/smoke/task-logs.py +++ b/tests/templates/kuttl/smoke/task-logs.py @@ -189,11 +189,6 @@ def assert_log_is_readable(headers, dag_run_id: str) -> None: def main(airflow_version: str) -> None: - if airflow_version.startswith("2."): - # Airflow 2 serves task logs through a different API; not covered here. - print(f"Skipping: not applicable to Airflow {airflow_version}") - return - headers = { "Authorization": f"Bearer {get_token()}", "Content-Type": "application/json", diff --git a/tests/templates/kuttl/triggerer/triggerer_metrics.py b/tests/templates/kuttl/triggerer/triggerer_metrics.py index ddaadb241..465e78b16 100755 --- a/tests/templates/kuttl/triggerer/triggerer_metrics.py +++ b/tests/templates/kuttl/triggerer/triggerer_metrics.py @@ -1,11 +1,12 @@ #!/usr/bin/env python -import requests -import time -import sys -from datetime import datetime, timezone import argparse import logging +import sys +import time +from datetime import UTC, datetime + +import requests def exception_handler(exception_type, exception, traceback): @@ -42,7 +43,7 @@ def assert_dag_started(rest_url, headers, dag_id, dag_run_id): def metrics_v3(role_group: str) -> None: - now = datetime.now(timezone.utc) + now = datetime.now(UTC) ts = now.strftime("%Y-%m-%dT%H:%M:%S.%f") + now.strftime("%z") # Trigger a deferrable DAG run to create metrics @@ -113,57 +114,6 @@ def metrics_v3(role_group: str) -> None: sys.exit(1) -def metrics_v2(role_group: str) -> None: - # Trigger a DAG run to create metrics - dag_id = "core_deferrable_sleep_demo" - - rest_url = "http://airflow-webserver:8080/api/v1" - auth = ("airflow", "airflow") - - # allow a few moments for the DAGs to be registered to all roles - time.sleep(10) - - response = requests.patch( - f"{rest_url}/dags/{dag_id}", auth=auth, json={"is_paused": False} - ) - response = requests.post( - f"{rest_url}/dags/{dag_id}/dagRuns", auth=auth, json={"conf": {}} - ) - - # Test the DAG in a loop. Each time we call the script a new job will be started: we can avoid - # or minimize this by looping over the check instead. - iterations = 4 - loop = 0 - while True: - assert response.status_code == 200, "DAG run could not be triggered." - # Wait for the metrics to be consumed by the statsd-exporter - time.sleep(5) - # (disable line-break flake checks) - if ( - (assert_metric("scheduler", role_group, "airflow_scheduler_heartbeat")) - and ( - assert_metric( - "webserver", - role_group, - "airflow_task_instance_created_CoreDeferrableSleepOperator", - ) - ) # noqa: W503, W504 - and ( - assert_metric( - "scheduler", - role_group, - "airflow_dagrun_duration_success_core_deferrable_sleep_demo_count", - ) - ) - ): # noqa: W503, W504 - break - time.sleep(10) - loop += 1 - if loop == iterations: - # force re-try of script - sys.exit(1) - - if __name__ == "__main__": log_level = "DEBUG" logging.basicConfig( @@ -179,7 +129,4 @@ def metrics_v2(role_group: str) -> None: parser.add_argument("--airflow-version", type=str, help="Airflow version") opts = parser.parse_args() - if opts.airflow_version and opts.airflow_version.startswith("3"): - metrics_v3(opts.role_group) - else: - metrics_v2(opts.role_group) + metrics_v3(opts.role_group) diff --git a/tests/templates/kuttl/versioning/dag_metrics.py b/tests/templates/kuttl/versioning/dag_metrics.py index 20a645ca6..e95bed9c3 100755 --- a/tests/templates/kuttl/versioning/dag_metrics.py +++ b/tests/templates/kuttl/versioning/dag_metrics.py @@ -1,10 +1,17 @@ #!/usr/bin/env python -import requests -import time -import sys import logging -from datetime import datetime, timezone +import sys +import time +from datetime import UTC, datetime + +import requests + +logging.basicConfig( + level="DEBUG", format="%(asctime)s %(levelname)s: %(message)s", stream=sys.stdout +) + +log = logging.getLogger(__name__) def assert_metric(role, metric): @@ -17,7 +24,7 @@ def assert_metric(role, metric): return metric in metric_response.text -now = datetime.now(timezone.utc) +now = datetime.now(UTC) ts = now.strftime("%Y-%m-%dT%H:%M:%S.%f") + now.strftime("%z") # Trigger a DAG run to create metrics @@ -56,7 +63,7 @@ def assert_metric(role, metric): f"{rest_url}/dags/{dag_id}", headers=headers, json={"is_paused": False} ) if response.status_code != 200: - logging.error("DAG run could not be activated") + log.error("DAG run could not be activated") sys.exit(1) # trigger DAG @@ -64,7 +71,7 @@ def assert_metric(role, metric): f"{rest_url}/dags/{dag_id}/dagRuns", headers=headers, json=dag_data ) if response.status_code != 200: - logging.error("DAG run could not be triggered") + log.error("DAG run could not be triggered") sys.exit(1) # Wait for the metrics to be consumed by the statsd-exporter @@ -76,18 +83,17 @@ def assert_metric(role, metric): while True: try: # Worker is not deployed with the kubernetes executor so retrieve success metric from scheduler - # (disable line-break flake checks) if (assert_metric("scheduler", "airflow_scheduler_heartbeat")) and ( assert_metric( "scheduler", "airflow_dagrun_duration_success_sparkapp_dag_count" ) - ): # noqa: W503, W504 + ): break time.sleep(10) loop += 1 if loop == iterations: - logging.error("Still waiting for metrics. Exiting to start a new loop....") + log.error("Still waiting for metrics. Exiting to start a new loop....") # force re-try of script sys.exit(1) except AssertionError as error: - logging.warning(f"Encountered: {error}") + log.warning(f"Encountered: {error}") diff --git a/tests/test-definition.yaml b/tests/test-definition.yaml index b349bd54f..a4bd7c631 100644 --- a/tests/test-definition.yaml +++ b/tests/test-definition.yaml @@ -7,7 +7,6 @@ dimensions: - name: airflow values: - - 2.9.3 - 3.0.6 - 3.2.2 - 3.3.2