You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "bugraoz93 (via GitHub)" <gi...@apache.org> on 2024/12/30 20:46:57 UTC
[PR] Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
bugraoz93 opened a new pull request, #45300:
URL: https://github.com/apache/airflow/pull/45300
**Summary**
This PR introduces a central API communication mechanism for the CLI and adopts one of the broadest endpoint ranges in the API, focusing on connection commands. After several iterations to automate API call generation and handle edge cases, I couldn't achieve a fully dynamic request generation process. Instead, I landed on a structure similar to TaskSDK <-> ExecutionAPI. This approach simplifies reviews, maintains consistency across clients, and opens the door for better automation in future iterations, possibly in 3.1 or 3.2.
**Implementation Details**
- Added a central API communication mechanism for the CLI.
- Integrated connection_command.py with unit tests.
- Implemented most of the necessary CLI operations.
- Data model generation from RestAPI to CLI is handled using uv.
- Added decorators to cascade generic processes to operations.
- Created a testing framework for CLI testing, with an example implementation for connection command.
- Pending Work
- Some minor features related to the connection command are still in progress and will be added in follow-up updates before 3.0.
**Notes on task_command**
While working on this, I realized that task_command behaves more like a local_command than a remote_command. This needs further discussion, especially regarding its integration with TaskSDK. From the CLI perspective, depending on TaskSDK seems cleaner than directly calling ExecutionAPI, as it avoids duplication and keeps the structure consistent. Even if the CLI calls TaskSDK, the two-hop process to reach the ExecutionAPI feels a bit redundant. What do you think, @ashb?
<!-- Please keep an empty line above the dashes. -->
---
**^ Add meaningful description above**
Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2695619677
> LGTM :) Got a small comment, and also you should rebase from main and resolve conflicts.
Many thanks for your time, Shahar! :) Rebased and resolved
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 - API Communication Mechanism [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham merged PR #45300:
URL: https://github.com/apache/airflow/pull/45300
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "shahar1 (via GitHub)" <gi...@apache.org>.
shahar1 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1976647548
##########
airflow/cli/commands/remote_commands/connection_command.py:
##########
@@ -108,18 +110,54 @@ def _connection_to_dict(conn: Connection) -> dict:
}
-def create_default_connections(args):
- db_create_default_connections()
+@provide_cli_api_client
+def create_default_connections(args, cli_api_client=NEW_CLI_API_CLIENT):
+ """Create default connections."""
+ cli_api_client.connections.create_defaults()
+ print("Default connections have been created.")
+
+
+def _response_to_connection(response: ConnectionResponse) -> Connection:
+ # TODO: Return is_encrypted from API to properly convert to Connection, otherwise it will be None
Review Comment:
What is `is_encrypted`? It's unclear from the context what exactly should be done as part of this TODO.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1945094131
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,228 @@
+# 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.
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str
+ api_token: str
+
+ def __init__(self, api_url: str, api_token: str = "NO_TOKEN"):
+ self.api_url = api_url
+ self.api_token = api_token
+
+ def save(self):
+ """Save the credentials."""
+ default_config_dir = os.path.expanduser("~/.config/airflow")
+ print(f"Saving credentials to {default_config_dir}")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, "credentials.json"), "w") as f:
+ json.dump(
+ {"api_url": self.api_url, "api_token": base64.b64encode(self.api_token.encode()).decode()}, f
+ )
+
+ @classmethod
+ def load(cls) -> Credentials:
+ """Load the credentials."""
+ default_config_dir = os.path.expanduser("~/.config/airflow")
+ if os.path.exists(default_config_dir):
+ with open(os.path.join(default_config_dir, "credentials.json")) as f:
+ credentials = json.load(f)
+ return cls(
+ api_url=credentials["api_url"],
+ api_token=base64.b64decode(credentials["api_token"]).decode(),
Review Comment:
We should design the credentials file so that it can cope with multiple airflow installed concurrently -- for instance a stage and a prod deployment.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2719235382
CI failures unrelated
* `The image /mnt/ci-image-save-linux_amd64-3.9.tar does not exist.` transient
* `AssertionError: Could not trigger a DAG-run: {'detail': 'Forbidden'}` K8s Test API related
* `requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))` K8s Test API related
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996627411
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,264 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import sys
+from functools import wraps
+from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
+
+import httpx
+import keyring
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.exceptions import AirflowNotFoundException
+from airflow.typing_compat import ParamSpec
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
Review Comment:
I follow now, it's more like name for a git remote, or k8s cluster in your config. How this is presented to users in docs and help text in the cli command is going to be critical, as this is a new concept completely and isn't immediately obvious like "url" is.
I think env var or flag like you have now is fine.
Not a blocker, but I think a rename and having something like current context in k8s would be a nice usability improvement. Maybe in a follow up.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2727262821
Yup I think we can start with using the name to be quick and then contribute the "dev"/airflow standalone type of code. :)
> We could later **actually** incorporate `airflowctl` into that new package @kaxil -> I see no issue with that if you are willing to contribute it still :D
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1982194357
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,244 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.set_environment(api_environment)
+
+ @lru_cache()
+ def get_input_cli_config_file(self) -> str:
+ """Generate path and always generate that path but let's not world readable."""
+ self.set_environment()
+ return f"{self.api_environment}.json"
+
+ def set_environment(self, api_environment: str = "production"):
+ """Read the environment from the environment variable."""
+ self.api_environment = os.getenv("APACHE_AIRFLOW_CLI_ENVIRONMENT") or api_environment
Review Comment:
The old habit from C. You are right. Agree, property is the right choice here, missed that.
Actually, on the constructor part, we don't even need that method indeed. Removed and moved the assignment to the constructor. I made the `input_cli_config_file` method `property` rather than a set method. :) Thanks!
Most probably, I wanted to set from multiple places while testing and forgot to delete some of them and CLI took precedence. Removing them should also fix that ambiguity.
##########
airflow/cli/commands/remote_commands/auth_command.py:
##########
@@ -0,0 +1,44 @@
+#
+# 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.
+
+from __future__ import annotations
+
+import os
+import sys
+
+import rich
+
+from airflow.cli.api.cli_api_client import Credentials
+from airflow.utils import cli as cli_utils
+
+
+@cli_utils.action_cli
+def login(args) -> None:
+ """Login to a provider."""
+ if not args.api_token and not os.environ.get("APACHE_AIRFLOW_CLI_TOKEN"):
+ # Exit
+ rich.print("[red]No token found.")
+ rich.print(
+ "[green]Please pass: [blue]--api-token or set APACHE_AIRFLOW_CLI_TOKEN environment variable to login."
Review Comment:
I fell into the same questioning but without closing worked for the rest and converted the colours when the other started in this case blue. I closed them and made them more specific to variable names. It looks better like this
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1981836971
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,244 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.set_environment(api_environment)
+
+ @lru_cache()
+ def get_input_cli_config_file(self) -> str:
+ """Generate path and always generate that path but let's not world readable."""
+ self.set_environment()
+ return f"{self.api_environment}.json"
+
+ def set_environment(self, api_environment: str = "production"):
+ """Read the environment from the environment variable."""
+ self.api_environment = os.getenv("APACHE_AIRFLOW_CLI_ENVIRONMENT") or api_environment
Review Comment:
Having a `set_x` method on a python class is un-common, it's more common to do this as a property setter instead, if it's even needed.
Another option might be to do this in the constructor instead
```
self.api_environment = os.getenv("APACHE_AIRFLOW_CLI_ENVIRONMENT") or api_environment
```
(Though I wonder why the default is the CLI value, not the value passed to the constructor?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2708393979
The API is already integrated with the authentication. This is why I needed to add authentication here https://github.com/apache/airflow/pull/45300/commits/56c0cf96d53dd460cf8378be45c12cd73f617ca0. Otherwise, it started doesn't work with an error.
```
2025-03-08 16:44:09 [error ] Connection not found [airflow.cli.api.operations] detail=ServerResponseError("Client error message: {'detail': 'Not authenticated'}") status_code=401
```
Thanks to `TaskSDK` work, it was smooth without too much effort.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "perry2of5 (via GitHub)" <gi...@apache.org>.
perry2of5 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1901116617
##########
airflow/cli/api/cli_api_client.py:
##########
@@ -0,0 +1,69 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+import httpx
+
+from airflow.cli.api.client import Client, Credentials
+from airflow.typing_compat import ParamSpec
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials.load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=10)
+ cli_api_client = Client(
+ base_url=credentials.api_url,
+ limits=limits,
+ )
+ yield cli_api_client
+ finally:
+ if cli_api_client:
+ cli_api_client.close()
+
+
+def provide_cli_api_client(func: Callable[PS, RT]) -> Callable[PS, RT]:
+ """
+ Provide a CLI API Client to the decorated function.
+
+ If you want to reuse a CLI API Client or run the function as part of
+ API call, you pass it to the function, if not this wrapper
+ will create one and close it for you.
+ """
+
+ @wraps(func)
+ def wrapper(*args, **kwargs) -> RT:
+ with get_client() as cli_api_client:
Review Comment:
That makes sense. I think this should be:
```
if "cli_api_client" not in kwargs:
with get_client() as cli_api_client:
return func(*args, cli_api_client=cli_api_client, **kwargs)
else:
# use the mock for unit tests:
return func(*args, **kwargs)
```
If you disagree feel free to say so and mark this resolved.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1901160184
##########
airflow/cli/api/cli_api_client.py:
##########
@@ -0,0 +1,69 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+import httpx
+
+from airflow.cli.api.client import Client, Credentials
+from airflow.typing_compat import ParamSpec
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials.load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=10)
+ cli_api_client = Client(
+ base_url=credentials.api_url,
+ limits=limits,
+ )
+ yield cli_api_client
+ finally:
+ if cli_api_client:
+ cli_api_client.close()
+
+
+def provide_cli_api_client(func: Callable[PS, RT]) -> Callable[PS, RT]:
+ """
+ Provide a CLI API Client to the decorated function.
+
+ If you want to reuse a CLI API Client or run the function as part of
+ API call, you pass it to the function, if not this wrapper
+ will create one and close it for you.
+ """
+
+ @wraps(func)
+ def wrapper(*args, **kwargs) -> RT:
+ with get_client() as cli_api_client:
Review Comment:
I answered generically :) Indeed, the if can switch places. Adjusted and placed a comment in case of wrong usage, thanks!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1901109149
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,675 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolPostBulkBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
+
+ # def_
+
+ @classmethod
+ def from_response(cls, response: httpx.Response) -> ServerResponseError | None:
+ if response.status_code < 400:
+ return None
+
+ if response.headers.get("content-type") != "application/json":
+ return None
+
+ if 400 <= response.status_code < 500:
+ response.read()
+ return cls(
+ message=f"Client error message: {response.json()}",
+ request=response.request,
+ response=response,
+ )
+
+ msg = response.json()
+
+ self = cls(message=msg, request=response.request, response=response)
+ return self
+
+
+# Decorator to apply methods to all operations, this is initiated at __init_subclass__ on BaseOperations
+SERVER_CONNECTION_REFUSED_ERROR: str = "API Server is not running, please contact your administrator."
+
+
+def _check_flag_and_exit_if_server_response_error(func):
+ """Return decorator to check for ServerResponseError and exit if the server is not running."""
+
+ def _exit_if_server_response_error(response: Any | ServerResponseError):
+ if isinstance(response, ServerResponseError):
+ rich.print(f"[bold red]Error:[/bold red] {response.response.json()}")
+ sys.exit(1)
+ return response
+
+ def wrapped(self, *args, **kwargs):
+ try:
+ if self.exit_in_error:
+ return _exit_if_server_response_error(response=func(self, *args, **kwargs))
+ else:
+ return func(self, *args, **kwargs)
+ except httpx.ConnectError:
+ rich.print(f"[bold red]{SERVER_CONNECTION_REFUSED_ERROR}[/bold red]")
+ sys.exit(1)
+
+ return wrapped
+
+
+class BaseOperations:
+ """
+ Base class for operations.
+
+ This class is used to decorate all callable methods with a check for ServerResponseError.
+ Set exit_in_error false to not exit.
+ """
+
+ __slots__ = ("client", "response", "exit_in_error")
+
+ def __init__(self, client: Client, response=None, exit_in_error: bool = True):
+ self.client = client
+ self.response = response
+ self.exit_in_error = exit_in_error
+
+ def __init_subclass__(cls, **kwargs):
+ """Decorate all callable methods with a check for ServerResponseError and exit if the server is not running."""
+ super().__init_subclass__(**kwargs)
+ for attr, value in cls.__dict__.items():
+ if callable(value):
+ setattr(cls, attr, _check_flag_and_exit_if_server_response_error(value))
+
+
+# Operations
+# TODO: Get all with limit and offset to overcome default 100 limit for all list operations
Review Comment:
Great point! Thanks for bringing it up! If the queries are returning huge results, we should also have pagination on the CLI level in that case if the client is handling this pagination.
Indeed, within this context ([AIP-81](https://cwiki.apache.org/confluence/display/AIRFLOW/AIP-81+Enhanced+Security+in+CLI+via+Integration+of+API)), what we are trying is to lift and shift the current functionality via using REST API. That's why I have included the comment as let's first select all as the same as current behaviour.
**Current Functionality:**
**Connection Export:**
https://github.com/apache/airflow/blob/f236ab14cce14dd49aeadc66bdb47b2e40ba8bb0/airflow/cli/commands/remote_commands/connection_command.py#L190-L191
**Variable Export:**
https://github.com/apache/airflow/blob/f236ab14cce14dd49aeadc66bdb47b2e40ba8bb0/airflow/cli/commands/remote_commands/variable_command.py#L123-L131
We are aiming to release this AIP in v3.0. I am planning to propose another AIP for improvements and generify the approaches in the CLI. This is one of the good fits for that project.
How about we first finish the integration and as the next iteration, we can make these improvements that allow us to scale more on the CLI for v3.1 or v3.2?
If you are interested in contributing to the CLI, maybe you can check the READY column in this project.
https://github.com/orgs/apache/projects/415.
##########
airflow/cli/api/cli_api_client.py:
##########
@@ -0,0 +1,69 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+import httpx
+
+from airflow.cli.api.client import Client, Credentials
+from airflow.typing_compat import ParamSpec
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials.load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=10)
+ cli_api_client = Client(
+ base_url=credentials.api_url,
+ limits=limits,
+ )
+ yield cli_api_client
+ finally:
+ if cli_api_client:
+ cli_api_client.close()
+
+
+def provide_cli_api_client(func: Callable[PS, RT]) -> Callable[PS, RT]:
+ """
+ Provide a CLI API Client to the decorated function.
+
+ If you want to reuse a CLI API Client or run the function as part of
+ API call, you pass it to the function, if not this wrapper
+ will create one and close it for you.
+ """
+
+ @wraps(func)
+ def wrapper(*args, **kwargs) -> RT:
+ with get_client() as cli_api_client:
Review Comment:
No one should pass the `cli_api_client` if it is not and for mocking purposes in `unit tests`. The Client should be generic and singleton for all CLI commands.
Users can run a single command using the `airflow` CLI, which can only run one command at a time. You can run parallel commands with different methods using the `airflow` CLI in the terminal, but each command running is an individual process behind the scenes on the OS level. I think this is why we shouldn't consider having multiple clients within the CLI context.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2657902584
Hey everyone, apologies for the delay! I have been feeling quite terrible since the town hall and have only just managed to pull myself together in recent days. I tried to address all the comments in the code. Could you check again when you have time? Thanks!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996414322
##########
pyproject.toml:
##########
@@ -912,3 +922,30 @@ members = [
"task-sdk",
"devel-common",
]
+
+
+# To use:
+#
+# TODO: Automate this in CI to validate the unit tests with newly generated API endpoint datamodels for compatibility
+# The FastAPI should be running in the background to serve the OpenAPI schema
+# uv run --group codegen --project apache-airflow --directory airflow/ datamodel-codegen
+[tool.datamodel-codegen]
+capitalise-enum-members=true # `State.RUNNING` not `State.running`
+disable-timestamp=true
+enable-version-header=true
+enum-field-as-literal='one' # When a single enum member, make it output a `Literal["..."]`
+input-file-type='openapi'
+output-model-type='pydantic_v2.BaseModel'
+output-datetime-class='datetime'
+target-python-version='3.9'
+no-alias=false
+use-annotated=true
+use-default=true
+use-double-quotes=true
+use-schema-description=true # Desc becomes class doc comment
+use-standard-collections=true # list[] not List[]
+use-subclass-enum=true # enum, not union of Literals
+use-union-operator=false # 3.9+annotations
+
+url = "http://0.0.0.0:9091/openapi.json"
Review Comment:
Yeah, things have been changed a bit :) I will update it and will regenerate the datamodels form top and adopt to operations
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726833672
> > As long as we are able to prove out that the interaction with the api, and foundational pieces that are in core, are good by feature freeze, we are golden. This new cli package wouldn't fall under the freeze :)
>
> Agreed. I also like your idea @jedcunningham of keeping current commands without auth and a separate package for remote stuff. We can re-use `airflowctl` name too since I own that. Naming aside, I like the idea
We could later **actually** incorporate `airflowctl` into that new package @kaxil -> I see no issue with that if you are willing to contribute it still :D
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726804721
> How about I remove the connection command integration from the PR? Let's merge the API integration without integrating into any command so that maintaining that part would be a lot easier even while moving out of the package. I then make the split into apache-airflow-cli and add this connection integration there. From there we start the transition to other remote commands.
I think this is a good plan, especially if we commit to moving the client etc out before Thursday :)
As long as we are able to prove out that the interaction with the api, and foundational pieces that are in core, are good by feature freeze, we are golden. This new cli package wouldn't fall under the freeze :)
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "perry2of5 (via GitHub)" <gi...@apache.org>.
perry2of5 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1900278576
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,675 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolPostBulkBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
+
+ # def_
+
+ @classmethod
+ def from_response(cls, response: httpx.Response) -> ServerResponseError | None:
+ if response.status_code < 400:
+ return None
+
+ if response.headers.get("content-type") != "application/json":
+ return None
+
+ if 400 <= response.status_code < 500:
+ response.read()
+ return cls(
+ message=f"Client error message: {response.json()}",
+ request=response.request,
+ response=response,
+ )
+
+ msg = response.json()
+
+ self = cls(message=msg, request=response.request, response=response)
+ return self
+
+
+# Decorator to apply methods to all operations, this is initiated at __init_subclass__ on BaseOperations
+SERVER_CONNECTION_REFUSED_ERROR: str = "API Server is not running, please contact your administrator."
+
+
+def _check_flag_and_exit_if_server_response_error(func):
+ """Return decorator to check for ServerResponseError and exit if the server is not running."""
+
+ def _exit_if_server_response_error(response: Any | ServerResponseError):
+ if isinstance(response, ServerResponseError):
+ rich.print(f"[bold red]Error:[/bold red] {response.response.json()}")
+ sys.exit(1)
+ return response
+
+ def wrapped(self, *args, **kwargs):
+ try:
+ if self.exit_in_error:
+ return _exit_if_server_response_error(response=func(self, *args, **kwargs))
+ else:
+ return func(self, *args, **kwargs)
+ except httpx.ConnectError:
+ rich.print(f"[bold red]{SERVER_CONNECTION_REFUSED_ERROR}[/bold red]")
+ sys.exit(1)
+
+ return wrapped
+
+
+class BaseOperations:
+ """
+ Base class for operations.
+
+ This class is used to decorate all callable methods with a check for ServerResponseError.
+ Set exit_in_error false to not exit.
+ """
+
+ __slots__ = ("client", "response", "exit_in_error")
+
+ def __init__(self, client: Client, response=None, exit_in_error: bool = True):
+ self.client = client
+ self.response = response
+ self.exit_in_error = exit_in_error
+
+ def __init_subclass__(cls, **kwargs):
+ """Decorate all callable methods with a check for ServerResponseError and exit if the server is not running."""
+ super().__init_subclass__(**kwargs)
+ for attr, value in cls.__dict__.items():
+ if callable(value):
+ setattr(cls, attr, _check_flag_and_exit_if_server_response_error(value))
+
+
+# Operations
+# TODO: Get all with limit and offset to overcome default 100 limit for all list operations
Review Comment:
Would paging the results be better than getting all? Perhaps the XxxxCollectionResponse could track the limit and offset of the current collection and have next_page() and prev_page() methods. This would require the XxxxCollectionResponse contain a link back to the operator I suppose. This seems a little cleaner than having the consumer manipulate the limit and offset locally to page the results. I'm wary of getting all in a single call since the result size could be large. Probably not an actual issue in this context.
I'm willing to work on adding paging if the main maintainers are in favor.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jason810496 (via GitHub)" <gi...@apache.org>.
jason810496 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1909132380
##########
airflow/cli/api/datamodels/_generated.py:
##########
@@ -0,0 +1,1300 @@
+# 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.
+
+# generated by datamodel-codegen:
+# filename: http://0.0.0.0:9091/openapi.json
+# version: 0.26.4
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from enum import Enum
+from typing import Annotated, Any, Optional, Union
+
+from pydantic import BaseModel, ConfigDict, Field, RootModel
+
+
+class AppBuilderMenuItemResponse(BaseModel):
Review Comment:
Hi @bugraoz93,
May I ask why the `datamodel-code-generator` tool is needed to generate all datamodels from the Core API side, instead of directly importing the necessary datamodels used by the remote command from the Core API datamodels module?
Thanks!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1990150855
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,226 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.api_environment = os.getenv("APACHE_AIRFLOW_CLI_ENVIRONMENT") or api_environment
+
+ @property
+ def input_cli_config_file(self) -> str:
+ """Generate path and always generate that path but let's not world readable."""
Review Comment:
Updated, indeed, it isn't related. I don't even remember how this left like this. Thanks!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1955330364
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,228 @@
+# 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.
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str
+ api_token: str
+
+ def __init__(self, api_url: str, api_token: str = "NO_TOKEN"):
+ self.api_url = api_url
+ self.api_token = api_token
+
+ def save(self):
+ """Save the credentials."""
+ default_config_dir = os.path.expanduser("~/.config/airflow")
+ print(f"Saving credentials to {default_config_dir}")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, "credentials.json"), "w") as f:
+ json.dump(
+ {"api_url": self.api_url, "api_token": base64.b64encode(self.api_token.encode()).decode()}, f
+ )
+
+ @classmethod
+ def load(cls) -> Credentials:
+ """Load the credentials."""
+ default_config_dir = os.path.expanduser("~/.config/airflow")
+ if os.path.exists(default_config_dir):
+ with open(os.path.join(default_config_dir, "credentials.json")) as f:
+ credentials = json.load(f)
+ return cls(
+ api_url=credentials["api_url"],
+ api_token=base64.b64decode(credentials["api_token"]).decode(),
Review Comment:
Conformed, the user can also switch between environments such as stag, prod or so using environment variables. They can set many environments as they want. I will create an issue and improve how to make this switch in CLI which will come in another PR. Thanks!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1955327952
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,228 @@
+# 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.
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str
+ api_token: str
+
+ def __init__(self, api_url: str, api_token: str = "NO_TOKEN"):
+ self.api_url = api_url
+ self.api_token = api_token
+
+ def save(self):
+ """Save the credentials."""
+ default_config_dir = os.path.expanduser("~/.config/airflow")
+ print(f"Saving credentials to {default_config_dir}")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, "credentials.json"), "w") as f:
Review Comment:
Now, they depend on the environment and are not world-readable. The extension is though. Do you think having the extension would be a problem?
Thanks both!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1955333639
##########
airflow/cli/api/__init__.py:
##########
Review Comment:
If the consensus is to have this as a separate package, I agree, let's include this in a follow-up PR. Additionally, assuming the same consensus, do we want this separation to aim at v3.0?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 - API Communication Mechanism [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2743052549
> Hi @bugraoz93, since this PR has been merged, I think we can start working on the https://github.com/apache/airflow/issues/45661 meta issue, right? Or are there any other dependencies that need to be completed first?
Hi @jason810496 , thanks for flagging! Normally, yes, they are unblocked. Since the direction has been changed and we don't have backward compatibility with the local commands running in core, we can provide outputs and data in a different and in a standard way than what the current commands do. I am trying something that could generate all the commands on the fly from operations created/implemented. It can save us from lots of effort. That's why I holded pinging all of you from the issue for a bit. I will share more details soon, either today or tomorrow, so the direction of the implementations can also be clear for transitions.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996872101
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,487 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkActionResponse,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolBulkActionResponse,
+ PoolBulkBody,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableBulkActionResponse,
+ VariableBulkBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
+
+ # def_
+
Review Comment:
Removed
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996630745
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,264 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import sys
+from functools import wraps
+from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
+
+import httpx
+import keyring
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.exceptions import AirflowNotFoundException
+from airflow.typing_compat import ParamSpec
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.api_environment = os.getenv("AIRFLOW_CLI_ENVIRONMENT") or api_environment
+
+ @property
+ def input_cli_config_file(self) -> str:
+ """Generate path for the CLI config file."""
+ return f"{self.api_environment}.json"
+
+ def save(self):
+ """Save the credentials to keyring and URL to disk as a file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, self.input_cli_config_file), "w") as f:
+ json.dump({"api_url": self.api_url}, f)
+ keyring.set_password("airflow-cli", f"api_token-{self.api_environment}", self.api_token)
+
+ def load(self) -> Credentials:
+ """Load the credentials from keyring and URL from disk file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if os.path.exists(default_config_dir):
+ with open(os.path.join(default_config_dir, self.input_cli_config_file)) as f:
+ credentials = json.load(f)
+ self.api_url = credentials["api_url"]
+ self.api_token = keyring.get_password("airflow-cli", f"api_token-{self.api_environment}")
+ return self
+ else:
+ raise AirflowNotFoundException(f"No credentials found in {default_config_dir}")
+
+
+class BearerAuth(httpx.Auth):
+ def __init__(self, token: str):
+ self.token: str = token
+
+ def auth_flow(self, request: httpx.Request):
+ if self.token:
+ request.headers["Authorization"] = "Bearer " + self.token
+ yield request
+
+
+class Client(httpx.Client):
+ """Client for the Airflow REST API."""
+
+ def __init__(self, *, base_url: str, token: str, **kwargs: Any):
+ auth = BearerAuth(token)
+
+ kwargs["base_url"] = f"{base_url}/public"
+ pyver = f"{'.'.join(map(str, sys.version_info[:3]))}"
+ super().__init__(
+ auth=auth,
+ headers={"user-agent": f"apache-airflow-cli/{version} (Python/{pyver})"},
+ event_hooks={"response": [raise_on_4xx_5xx], "request": [add_correlation_id]},
+ **kwargs,
+ )
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def assets(self):
+ """Operations related to assets."""
+ return AssetsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def backfills(self):
+ """Operations related to backfills."""
+ return BackfillsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def configs(self):
+ """Operations related to configs."""
+ return ConfigOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def connections(self):
+ """Operations related to connections."""
+ return ConnectionsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def dags(self):
+ """Operations related to DAGs."""
+ return DagOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def dag_runs(self):
+ """Operations related to DAG runs."""
+ return DagRunOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def jobs(self):
+ """Operations related to jobs."""
+ return JobsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def pools(self):
+ """Operations related to pools."""
+ return PoolsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def providers(self):
+ """Operations related to providers."""
+ return ProvidersOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def variables(self):
+ """Operations related to variables."""
+ return VariablesOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def version(self):
+ """Get the version of the server."""
+ return VersionOperations(self)
+
+
+# API Client Decorator for CLI Actions
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials().load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=1)
+ cli_api_client = Client(base_url=credentials.api_url, limits=limits, token=credentials.api_token)
+ yield cli_api_client
+ except AirflowNotFoundException as e:
+ raise e
Review Comment:
> The idea was to leave CLI to decide on how to handle the error and log the proper error for the user.
Makes sense.
This just stood out to me as, "oh, we forgot to do something". It also made me question if there was some esoteric behavior or feature I didn't know about. But, this can also be cleaned up in a follow up.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996872013
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,487 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkActionResponse,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolBulkActionResponse,
+ PoolBulkBody,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableBulkActionResponse,
+ VariableBulkBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
Review Comment:
Removed, indeed, this object hasn't been initiated. Even it is initiated, this would be automatically done
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1978278986
##########
airflow/cli/commands/remote_commands/connection_command.py:
##########
@@ -108,18 +110,54 @@ def _connection_to_dict(conn: Connection) -> dict:
}
-def create_default_connections(args):
- db_create_default_connections()
+@provide_cli_api_client
+def create_default_connections(args, cli_api_client=NEW_CLI_API_CLIENT):
+ """Create default connections."""
+ cli_api_client.connections.create_defaults()
+ print("Default connections have been created.")
+
+
+def _response_to_connection(response: ConnectionResponse) -> Connection:
+ # TODO: Return is_encrypted from API to properly convert to Connection, otherwise it will be None
Review Comment:
`is_encrypted` is a column in the database and a parameter for `connection`. Normally, the direct database call returns this but we need to include this functionality if we want to bring back `is_encrypted`. This TODO is making that happen after this PR. I have updated the TODO :)
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1990148643
##########
airflow/cli/cli_config.py:
##########
@@ -1496,15 +1527,14 @@ class GroupCommand(NamedTuple):
name="test",
help="Test a connection",
func=lazy_load_command("airflow.cli.commands.remote_commands.connection_command.connections_test"),
- args=(ARG_CONN_ID, ARG_VERBOSE),
+ args=(ARG_CONN_ID, ARG_CONN_TYPE_POSITIONAL, ARG_VERBOSE),
Review Comment:
This is due to API, I adopted the CLI but I will adopt this behaviour in the API because we don't really need the conn_type in this context. Created a bug issue to fix the behaviour #47646. Thanks for pointing!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1990152153
##########
airflow/cli/api/cli_api_client.py:
##########
Review Comment:
Merged them. At first, I aimed to split the decorator part to be more clear but seems that's not the case. :sweat: Thanks for pointing out!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1982196129
##########
airflow/cli/api/cli_api_client.py:
##########
@@ -0,0 +1,72 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+import httpx
+
+from airflow.cli.api.client import Client, Credentials
+from airflow.typing_compat import ParamSpec
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials().load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=10)
Review Comment:
Yes, single call per CLI command call. Reduced to 1
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2722605804
> I created this doc earlier and shared it in the dev call+dev channel. Please take a look if you have time. Considering deadlines and simplicity the decision was to pass the token to CLI which will be taken from the profile page or API. I think we should provide that but not sure we should include it in this huge PR or even in 3.0. I would be happy to implement that. I created a follow-up #47703. If you think this would be crucial for the users, I can try to implement it within 3.0 via including into AIP-81.
>
> https://docs.google.com/document/d/1BSEQxKEOArPRCclfCrAjAN5hjC56vG0R5nZPc3pxF9Y/edit?usp=sharing
>
> For the documentation, I agree we should include clear guidelines on usage. I know the docs are missing for the user side. I don't want to increase the scope of this PR more so I created a follow-up for that and already started working on it :) #47537 Hope this fills the gaps and addresses your concerns.
Oh, I had read the doc some time ago... long time ago. So I forgot.
Can you maybe just add these 2-3 senctences to the `airflow auth --help` page?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1955326436
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,228 @@
+# 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.
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str
+ api_token: str
+
+ def __init__(self, api_url: str, api_token: str = "NO_TOKEN"):
+ self.api_url = api_url
+ self.api_token = api_token
+
+ def save(self):
+ """Save the credentials."""
+ default_config_dir = os.path.expanduser("~/.config/airflow")
Review Comment:
Both [$XDG_CONFIG_HOME](https://specifications.freedesktop.org/basedir-spec/latest/) and keyring are integrated. Thanks!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996405481
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,264 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import sys
+from functools import wraps
+from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
+
+import httpx
+import keyring
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.exceptions import AirflowNotFoundException
+from airflow.typing_compat import ParamSpec
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.api_environment = os.getenv("AIRFLOW_CLI_ENVIRONMENT") or api_environment
+
+ @property
+ def input_cli_config_file(self) -> str:
+ """Generate path for the CLI config file."""
+ return f"{self.api_environment}.json"
+
+ def save(self):
+ """Save the credentials to keyring and URL to disk as a file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, self.input_cli_config_file), "w") as f:
+ json.dump({"api_url": self.api_url}, f)
+ keyring.set_password("airflow-cli", f"api_token-{self.api_environment}", self.api_token)
+
+ def load(self) -> Credentials:
+ """Load the credentials from keyring and URL from disk file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if os.path.exists(default_config_dir):
+ with open(os.path.join(default_config_dir, self.input_cli_config_file)) as f:
+ credentials = json.load(f)
+ self.api_url = credentials["api_url"]
+ self.api_token = keyring.get_password("airflow-cli", f"api_token-{self.api_environment}")
+ return self
+ else:
+ raise AirflowNotFoundException(f"No credentials found in {default_config_dir}")
+
+
+class BearerAuth(httpx.Auth):
+ def __init__(self, token: str):
+ self.token: str = token
+
+ def auth_flow(self, request: httpx.Request):
+ if self.token:
+ request.headers["Authorization"] = "Bearer " + self.token
+ yield request
+
+
+class Client(httpx.Client):
+ """Client for the Airflow REST API."""
+
+ def __init__(self, *, base_url: str, token: str, **kwargs: Any):
+ auth = BearerAuth(token)
+
+ kwargs["base_url"] = f"{base_url}/public"
+ pyver = f"{'.'.join(map(str, sys.version_info[:3]))}"
+ super().__init__(
+ auth=auth,
+ headers={"user-agent": f"apache-airflow-cli/{version} (Python/{pyver})"},
+ event_hooks={"response": [raise_on_4xx_5xx], "request": [add_correlation_id]},
+ **kwargs,
+ )
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def assets(self):
+ """Operations related to assets."""
+ return AssetsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def backfills(self):
+ """Operations related to backfills."""
+ return BackfillsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def configs(self):
+ """Operations related to configs."""
+ return ConfigOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def connections(self):
+ """Operations related to connections."""
+ return ConnectionsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def dags(self):
+ """Operations related to DAGs."""
+ return DagOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def dag_runs(self):
+ """Operations related to DAG runs."""
+ return DagRunOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def jobs(self):
+ """Operations related to jobs."""
+ return JobsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def pools(self):
+ """Operations related to pools."""
+ return PoolsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def providers(self):
+ """Operations related to providers."""
+ return ProvidersOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def variables(self):
+ """Operations related to variables."""
+ return VariablesOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def version(self):
+ """Get the version of the server."""
+ return VersionOperations(self)
+
+
+# API Client Decorator for CLI Actions
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials().load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=1)
+ cli_api_client = Client(base_url=credentials.api_url, limits=limits, token=credentials.api_token)
+ yield cli_api_client
+ except AirflowNotFoundException as e:
+ raise e
Review Comment:
The idea was to leave CLI to decide on how to handle the error and log the proper error for the user. I first logged each error here and removed them to give to the CLI layer fully. I may add them back in a debug state, otherwise, the errors or warnings between CLI and there could be duplicates or confusing sometimes
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726302312
> Monday is feature freeze
Week of, it'll be Thursday :)
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1990144299
##########
airflow/cli/commands/remote_commands/auth_command.py:
##########
@@ -0,0 +1,45 @@
+#
+# 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.
+
+from __future__ import annotations
+
+import os
+import sys
+
+import rich
+
+from airflow.cli.api.cli_api_client import Credentials
+from airflow.utils import cli as cli_utils
+
+
+@cli_utils.action_cli
+def login(args) -> None:
+ """Login to a provider."""
+ if not args.api_token and not os.environ.get("APACHE_AIRFLOW_CLI_TOKEN"):
Review Comment:
Updated as suggested
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996872053
##########
pyproject.toml:
##########
@@ -912,3 +922,30 @@ members = [
"task-sdk",
"devel-common",
]
+
+
+# To use:
+#
+# TODO: Automate this in CI to validate the unit tests with newly generated API endpoint datamodels for compatibility
+# The FastAPI should be running in the background to serve the OpenAPI schema
+# uv run --group codegen --project apache-airflow --directory airflow/ datamodel-codegen
+[tool.datamodel-codegen]
+capitalise-enum-members=true # `State.RUNNING` not `State.running`
+disable-timestamp=true
+enable-version-header=true
+enum-field-as-literal='one' # When a single enum member, make it output a `Literal["..."]`
+input-file-type='openapi'
+output-model-type='pydantic_v2.BaseModel'
+output-datetime-class='datetime'
+target-python-version='3.9'
+no-alias=false
+use-annotated=true
+use-default=true
+use-double-quotes=true
+use-schema-description=true # Desc becomes class doc comment
+use-standard-collections=true # list[] not List[]
+use-subclass-enum=true # enum, not union of Literals
+use-union-operator=false # 3.9+annotations
+
+url = "http://0.0.0.0:9091/openapi.json"
Review Comment:
Updated
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726747281
> So, after sleeping on this idea, I want to pitch it...
>
> Have you considered having this new api-driven cli be completely standalone and in its own package from day 1? This would leave the existing db-backed cli as-is and functional. The vast majority of this PR is still usable, it'd just not be in `airflow` and not whack the old command.
>
> I'm imagining the scenario where I'm trying to troubleshoot in a remote deployment, jump into the scheduler pod, and try to run `airflow config get-value x y`. Having to auth not on my machine, where other people could also have access and grab my token, then clean up when I'm done isn't ideal. Effectively it'd have to do my troubleshooting remotely, which could be bit a bit cumbersome.
>
> Basically, this new api-driven command could be more like kubectl, airflowctl.
Thanks for your comment @jedcunningham! Yes, this was designed [in the AIP-81](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=315493347#AIP81EnhancedSecurityinCLIviaIntegrationofAPI-ReleaseStrategy). In the first stage of design, my idea was directly like kubectl to airflowctl. In the comments, there were shouts at kubectl too. Of course, the name still will be `airflow` because of decisions at that time (in the dev calls) even though `airflowctl` was on the table in the AIP comments. The idea is indeed to have this as a separate package for sure. We can think of all `remote commands` that will be in the new CLI package. This will for example another thing we should add before separating into another package #47538.
I agree with your point and security considerations. The `remote commands` will only work from remote machines because `airflow auth login` won't work in the scheduler or any components due to there being no installed `keyring` backend inside the containers. Of course, you can install a backend in a remote deployment scheduler pod and run it there but that would be similar if you install the separate CLI package for `remote commands` and use the `airflow auth login` in a similar fashion. I am not sure if we can easily prevent that from day 1 by making the new API-driven CLI be completely standalone package since it will still depend on how authentication is working with the `remote commands`.
What do you think?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726792448
> e.g. thinking in context of the docker compose example we publish, I doubt we want to add a keyring backend into the official docker images. So users either 1) need to modify the image before half the cli is usable or 2) install the cli separately out on their host, which isn't very a "docker compose" friendly pattern.
When thinking half of the commands will be a useless stand, indeed, this would cause ambiguity while lots of bug stories that commands aren't working. Do you suggest splitting the package in this PR? Or a separate one? Let's do this from day 1.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726804704
> Thanks Jarek! How about I remove the connection command integration from the PR? Let's merge the API integration without integrating into any command so that maintaining that part would be a lot easier even while moving out of the package. I then make the split into `apache-airflow-cli` and add this connection integration there. From there we start the transition to other remote commands.
Yeah. I think we could separate it out to a separate change - and do everything so that it works "locally" without authenticaion - but refactoring to make it possible "separately" is good now.
> For the having all in the `apache-airflow-core` too is indeed tricky. We should come up with something that shouldn't need duplicate work for API and DB calls separately for each command if we don't want to remove remote commands from `apache-airflow-core`.
Yeaah. Once I finish the `apache-airflow-core` we can add `apache-airflow-cli` and figure out how to avoid or mitigate duplicaiton.
My first thought (also got a quick chat with @jedcunningham0 is that some duplication is OK as long as we have a pre-commit that will take care to synchronize the client side in `apache-airflow-cli` with the command and "server" side in the API/scheduler. Does it sound good?
BTW. I just reserved `apache-airflow-cli` and `apache-airflow-ctl` in `PyPI` for that separate distribution.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 - API Communication Mechanism [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r2004378989
##########
pyproject.toml:
##########
@@ -317,6 +317,9 @@ testing = ["dev", "providers.tests", "tests_common", "tests"]
"providers/cncf/*/src/airflow/providers/cncf/__init__.py" = ["I002"]
"providers/dbt/*/src/airflow/providers/dbt/__init__.py" = ["I002"]
"providers/microsoft/*/src/airflow/providers/microsoft/__init__.py" = ["I002"]
+"providers/tests/__init__.py" = ["I002"]
+"providers/__init__.py" = ["I002"]
Review Comment:
```suggestion
```
Are these intentional? Probably not, but a miss during rebasing?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "perry2of5 (via GitHub)" <gi...@apache.org>.
perry2of5 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1899821320
##########
airflow/cli/api/cli_api_client.py:
##########
@@ -0,0 +1,69 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+import httpx
+
+from airflow.cli.api.client import Client, Credentials
+from airflow.typing_compat import ParamSpec
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials.load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=10)
+ cli_api_client = Client(
+ base_url=credentials.api_url,
+ limits=limits,
+ )
+ yield cli_api_client
+ finally:
+ if cli_api_client:
+ cli_api_client.close()
+
+
+def provide_cli_api_client(func: Callable[PS, RT]) -> Callable[PS, RT]:
+ """
+ Provide a CLI API Client to the decorated function.
+
+ If you want to reuse a CLI API Client or run the function as part of
+ API call, you pass it to the function, if not this wrapper
+ will create one and close it for you.
+ """
+
+ @wraps(func)
+ def wrapper(*args, **kwargs) -> RT:
+ with get_client() as cli_api_client:
Review Comment:
Can the call to get_client() be avoided if "cli_app_client" is in kwargs? Not sure if we need to always make this call.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2578837385
**Note Update:** The missing parts are included in the PR.
- Create default connections in connection_command
- Include overwrite functionality for file import operations for connections and pool endpoint
- Include overwrite functionality to connection_command
Thanks @jason810496 for your contributions!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1945089953
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,228 @@
+# 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.
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str
+ api_token: str
+
+ def __init__(self, api_url: str, api_token: str = "NO_TOKEN"):
+ self.api_url = api_url
+ self.api_token = api_token
+
+ def save(self):
+ """Save the credentials."""
+ default_config_dir = os.path.expanduser("~/.config/airflow")
Review Comment:
Please respect [`$XDG_CONFIG_HOME`](https://specifications.freedesktop.org/basedir-spec/latest/) if we are going to put files on disk.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1945090401
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,228 @@
+# 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.
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str
+ api_token: str
+
+ def __init__(self, api_url: str, api_token: str = "NO_TOKEN"):
+ self.api_url = api_url
+ self.api_token = api_token
+
+ def save(self):
+ """Save the credentials."""
+ default_config_dir = os.path.expanduser("~/.config/airflow")
Review Comment:
(see my comment in doc about using https://pypi.org/project/keyring/ instead though)
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2641435763
Thanks a lot for your time and your comments! I will address them and adjust the code accordingly soon.
> Next time would be better to cut PRs in smaller chunks not to scare reviewers away by number of LoC :-D
Indeed, that's on me making it big. I thought most parts were repeated on the operations while making the integration easier for contributers and went for it. I agree, that's on me, I will definitely split next time :D
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 - airflowctl - API Communication Mechanism and Creating Package [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2730995130
I will start making the changes soon
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 - API Communication Mechanism [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2738112790
CI seems unrelated
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726486845
> > Monday is feature freeze
>
> Week of, it'll be Thursday :)
I am happy that I was wrong :) I am full force making the changes
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726847175
Many thanks for your swift response! We all press enter around the same for sending the comment :D
>Yeaah. Once I finish the apache-airflow-core we can add apache-airflow-cli and figure out how to avoid or mitigate duplication.
Cool, great to know!
>My first thought (also got a quick chat with @jedcunningham ) is that some duplication is OK as long as we have a pre-commit that will take care to synchronize the client side in apache-airflow-cli with the command and "server" side in the API/scheduler we should be good. Does it sound good?
Sounds good! It seems inevitable to have duplicates at the first steps.
>BTW. I just reserved apache-airflow-cli and apache-airflow-ctl in PyPI for that separate distribution.
Amazing news! :partying_face:
>I think this is a good plan, especially if we commit to moving the client etc out before Thursday :)
Sure, I can move out remote and client part until Thursday :)
>As long as we are able to prove out that the interaction with the api, and foundational pieces that are in core, are good by feature freeze, we are golden. This new cli package wouldn't fall under the freeze :)
Make sense! I think in this way, we will definitely sure the core part working without any client integration. We just need to figure out when to run with which command or parameter to state it is remote or local without separating the package :)
>Agreed. I also like your idea @jedcunningham of keeping current commands without auth and a separate package for remote stuff. We can re-use airflowctl name too since I own that. Naming aside, I like the idea
Great, I would be happy if we use `airflowctl` :D Thanks Kaxil!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726804593
What do you think? @potiuk @jedcunningham
I am just concerned that reviewing everything could be harder if the PR have all, it may increase the LoC. If that's okay, I am happy to do this in this one
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726791375
Speaking of what we are going to release - we should be able to release a separate "apache-airflow-cli" distribution and only that distribution should have`keyring` as paraemeter and should authenticate with the server.
Now - we need to figure out how to keep the `remote` commands still working remotely in a separate package, while also have them available as airflow commands in `apache-airflow-core` distribution (without the keyring).
That is a bit tricky, but I am sure we can work it out.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2725984557
Thanks a lot, Jed for the review!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2723012148
> Okay, attempted (again) and... there is no "profile" page. Attempted to grab the "token" from the browser inspector: 
>
> ...but this was not working, `airflow login auth` was accepting. But then got a 403 when attempting to `airflow connections list`. So
>
> (1) Still even after re-reading the Google spec doc I am not able to find the right token. Some description is needed, else almost nobody can use the CLI. (Hope it is not an individual short-coming just in front of my keyboard) (2) I would encourage that if a user calls `airflow auth login --api-token <something>` that the token is also validated. It seems it was "just" stored but was not working. Or the `airflow connections list` call is broken. (3) With every call I was asked for the keystore password. Is there a way to temporarily store this in the session? Would be tideous to enter the passphrase of the keystore every time. (Or is this a specific shortcoming of the breeze container?)
> Okay, attempted (again) and... there is no "profile" page. Attempted to grab the "token" from the browser inspector: 
>
> ...but this was not working, `airflow login auth` was accepting. But then got a 403 when attempting to `airflow connections list`. So
>
> (1) Still even after re-reading the Google spec doc I am not able to find the right token. Some description is needed, else almost nobody can use the CLI. (Hope it is not an individual short-coming just in front of my keyboard) (2) I would encourage that if a user calls `airflow auth login --api-token <something>` that the token is also validated. It seems it was "just" stored but was not working. Or the `airflow connections list` call is broken. (3) With every call I was asked for the keystore password. Is there a way to temporarily store this in the session? Would be tideous to enter the passphrase of the keystore every time. (Or is this a specific shortcoming of the breeze container?)
Thanks for your feedback! They are valuable for me to shape this into better. I don't want to ship anything missing or hard to use.
Please don't get me wrong, my aim is not to rush into something and release a broken or non-usable piece of work. My thinking was unblocking the huge block of work in AIP-81. That block of work is the parallel migration of remote commands (~10) to use the client. My thinking was I could fill these gaps in the meantime as follow-ups.
Considering your concerns,
1) Let me include this in the PR.
2) Let me include work with the automated retrieving token into this PR then use `--username --password` which is more intuitive for users. Also the documentation part and make this already deliverable piece of work in the PR.
I did the developer tests with all connection commands and multiple cases and they were working fine. I am not sure why they didn't work. Let me double-check since there are so many moving things and provide more info later.
3) I haven't started making tests on each OS and each backend. I believe it should be limited to the dev package though. I agree I think that should be kept in either session or some solution is needed. If it is the same for all OS backends, I think it is worth including this as a feature rather would be faster than testing each backend and including integrations test for them.
The aim to make AIP-81 happen is the 17th of March week which is the next release week. Even if I added those things into this PR, I don't think migration of the remote commands can finish in 3 days with all review processes. Even if they are all implemented in 1-2 days, they still need to be reviewed and merged. We may need to extend the release of integration of API and this PR. So that everything can be ready without any friction.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726906594
This also has the advantage of not being tied to same feature +code freeze for Airflow 3!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996233785
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,264 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import sys
+from functools import wraps
+from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
+
+import httpx
+import keyring
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.exceptions import AirflowNotFoundException
+from airflow.typing_compat import ParamSpec
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
Review Comment:
Why do we need a separate environment? Isn't the instance url unique enough?
##########
pyproject.toml:
##########
@@ -912,3 +922,30 @@ members = [
"task-sdk",
"devel-common",
]
+
+
+# To use:
+#
+# TODO: Automate this in CI to validate the unit tests with newly generated API endpoint datamodels for compatibility
+# The FastAPI should be running in the background to serve the OpenAPI schema
+# uv run --group codegen --project apache-airflow --directory airflow/ datamodel-codegen
+[tool.datamodel-codegen]
+capitalise-enum-members=true # `State.RUNNING` not `State.running`
+disable-timestamp=true
+enable-version-header=true
+enum-field-as-literal='one' # When a single enum member, make it output a `Literal["..."]`
+input-file-type='openapi'
+output-model-type='pydantic_v2.BaseModel'
+output-datetime-class='datetime'
+target-python-version='3.9'
+no-alias=false
+use-annotated=true
+use-default=true
+use-double-quotes=true
+use-schema-description=true # Desc becomes class doc comment
+use-standard-collections=true # list[] not List[]
+use-subclass-enum=true # enum, not union of Literals
+use-union-operator=false # 3.9+annotations
+
+url = "http://0.0.0.0:9091/openapi.json"
Review Comment:
```suggestion
url = "http://0.0.0.0:8080/openapi.json"
```
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,487 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkActionResponse,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolBulkActionResponse,
+ PoolBulkBody,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableBulkActionResponse,
+ VariableBulkBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
+
+ # def_
+
Review Comment:
```suggestion
```
?
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,264 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import sys
+from functools import wraps
+from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
+
+import httpx
+import keyring
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.exceptions import AirflowNotFoundException
+from airflow.typing_compat import ParamSpec
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.api_environment = os.getenv("AIRFLOW_CLI_ENVIRONMENT") or api_environment
+
+ @property
+ def input_cli_config_file(self) -> str:
+ """Generate path for the CLI config file."""
+ return f"{self.api_environment}.json"
+
+ def save(self):
+ """Save the credentials to keyring and URL to disk as a file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, self.input_cli_config_file), "w") as f:
+ json.dump({"api_url": self.api_url}, f)
+ keyring.set_password("airflow-cli", f"api_token-{self.api_environment}", self.api_token)
+
+ def load(self) -> Credentials:
+ """Load the credentials from keyring and URL from disk file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if os.path.exists(default_config_dir):
+ with open(os.path.join(default_config_dir, self.input_cli_config_file)) as f:
+ credentials = json.load(f)
+ self.api_url = credentials["api_url"]
+ self.api_token = keyring.get_password("airflow-cli", f"api_token-{self.api_environment}")
+ return self
+ else:
+ raise AirflowNotFoundException(f"No credentials found in {default_config_dir}")
+
+
+class BearerAuth(httpx.Auth):
+ def __init__(self, token: str):
+ self.token: str = token
+
+ def auth_flow(self, request: httpx.Request):
+ if self.token:
+ request.headers["Authorization"] = "Bearer " + self.token
+ yield request
+
+
+class Client(httpx.Client):
+ """Client for the Airflow REST API."""
+
+ def __init__(self, *, base_url: str, token: str, **kwargs: Any):
+ auth = BearerAuth(token)
+
+ kwargs["base_url"] = f"{base_url}/public"
+ pyver = f"{'.'.join(map(str, sys.version_info[:3]))}"
+ super().__init__(
+ auth=auth,
+ headers={"user-agent": f"apache-airflow-cli/{version} (Python/{pyver})"},
+ event_hooks={"response": [raise_on_4xx_5xx], "request": [add_correlation_id]},
+ **kwargs,
+ )
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def assets(self):
+ """Operations related to assets."""
+ return AssetsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def backfills(self):
+ """Operations related to backfills."""
+ return BackfillsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def configs(self):
+ """Operations related to configs."""
+ return ConfigOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def connections(self):
+ """Operations related to connections."""
+ return ConnectionsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def dags(self):
+ """Operations related to DAGs."""
+ return DagOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def dag_runs(self):
+ """Operations related to DAG runs."""
+ return DagRunOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def jobs(self):
+ """Operations related to jobs."""
+ return JobsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def pools(self):
+ """Operations related to pools."""
+ return PoolsOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def providers(self):
+ """Operations related to providers."""
+ return ProvidersOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def variables(self):
+ """Operations related to variables."""
+ return VariablesOperations(self)
+
+ @lru_cache() # type: ignore[misc]
+ @property
+ def version(self):
+ """Get the version of the server."""
+ return VersionOperations(self)
+
+
+# API Client Decorator for CLI Actions
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials().load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=1)
+ cli_api_client = Client(base_url=credentials.api_url, limits=limits, token=credentials.api_token)
+ yield cli_api_client
+ except AirflowNotFoundException as e:
+ raise e
Review Comment:
Why catch then immediately reraise?
(I see this in a number of places, only commenting once)
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1945411598
##########
airflow/cli/api/__init__.py:
##########
Review Comment:
The split of distributions... I think it was intended to shift packages around after providers have been moved... @potiuk ... correct? So would assume this is a follow-up PR.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "perry2of5 (via GitHub)" <gi...@apache.org>.
perry2of5 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1899821320
##########
airflow/cli/api/cli_api_client.py:
##########
@@ -0,0 +1,69 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+import httpx
+
+from airflow.cli.api.client import Client, Credentials
+from airflow.typing_compat import ParamSpec
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials.load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=10)
+ cli_api_client = Client(
+ base_url=credentials.api_url,
+ limits=limits,
+ )
+ yield cli_api_client
+ finally:
+ if cli_api_client:
+ cli_api_client.close()
+
+
+def provide_cli_api_client(func: Callable[PS, RT]) -> Callable[PS, RT]:
+ """
+ Provide a CLI API Client to the decorated function.
+
+ If you want to reuse a CLI API Client or run the function as part of
+ API call, you pass it to the function, if not this wrapper
+ will create one and close it for you.
+ """
+
+ @wraps(func)
+ def wrapper(*args, **kwargs) -> RT:
+ with get_client() as cli_api_client:
Review Comment:
Can the call to get_client() be avoided if "cli_app_client" is in kwargs? Not sure if we need to always make this call.
##########
airflow/cli/api/cli_api_client.py:
##########
@@ -0,0 +1,69 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+import httpx
+
+from airflow.cli.api.client import Client, Credentials
+from airflow.typing_compat import ParamSpec
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials.load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=10)
+ cli_api_client = Client(
+ base_url=credentials.api_url,
+ limits=limits,
+ )
+ yield cli_api_client
+ finally:
+ if cli_api_client:
+ cli_api_client.close()
+
+
+def provide_cli_api_client(func: Callable[PS, RT]) -> Callable[PS, RT]:
+ """
+ Provide a CLI API Client to the decorated function.
+
+ If you want to reuse a CLI API Client or run the function as part of
+ API call, you pass it to the function, if not this wrapper
+ will create one and close it for you.
+ """
+
+ @wraps(func)
+ def wrapper(*args, **kwargs) -> RT:
+ with get_client() as cli_api_client:
Review Comment:
Can the call to get_client() be avoided if "cli_app_client" is in kwargs? Not sure if we need to always make this call.
##########
airflow/cli/api/cli_api_client.py:
##########
@@ -0,0 +1,69 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+import httpx
+
+from airflow.cli.api.client import Client, Credentials
+from airflow.typing_compat import ParamSpec
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials.load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=10)
+ cli_api_client = Client(
+ base_url=credentials.api_url,
+ limits=limits,
+ )
+ yield cli_api_client
+ finally:
+ if cli_api_client:
+ cli_api_client.close()
+
+
+def provide_cli_api_client(func: Callable[PS, RT]) -> Callable[PS, RT]:
+ """
+ Provide a CLI API Client to the decorated function.
+
+ If you want to reuse a CLI API Client or run the function as part of
+ API call, you pass it to the function, if not this wrapper
+ will create one and close it for you.
+ """
+
+ @wraps(func)
+ def wrapper(*args, **kwargs) -> RT:
+ with get_client() as cli_api_client:
Review Comment:
Can the call to get_client() be avoided if "cli_app_client" is in kwargs? Not sure if we need to always make this call.
##########
airflow/cli/api/cli_api_client.py:
##########
@@ -0,0 +1,69 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+import httpx
+
+from airflow.cli.api.client import Client, Credentials
+from airflow.typing_compat import ParamSpec
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials.load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=10)
+ cli_api_client = Client(
+ base_url=credentials.api_url,
+ limits=limits,
+ )
+ yield cli_api_client
+ finally:
+ if cli_api_client:
+ cli_api_client.close()
+
+
+def provide_cli_api_client(func: Callable[PS, RT]) -> Callable[PS, RT]:
+ """
+ Provide a CLI API Client to the decorated function.
+
+ If you want to reuse a CLI API Client or run the function as part of
+ API call, you pass it to the function, if not this wrapper
+ will create one and close it for you.
+ """
+
+ @wraps(func)
+ def wrapper(*args, **kwargs) -> RT:
+ with get_client() as cli_api_client:
Review Comment:
Can the call to get_client() be avoided if "cli_app_client" is in kwargs? Not sure if we need to always make this call.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jason810496 (via GitHub)" <gi...@apache.org>.
jason810496 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1912104862
##########
airflow/cli/api/datamodels/_generated.py:
##########
@@ -0,0 +1,1300 @@
+# 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.
+
+# generated by datamodel-codegen:
+# filename: http://0.0.0.0:9091/openapi.json
+# version: 0.26.4
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from enum import Enum
+from typing import Annotated, Any, Optional, Union
+
+from pydantic import BaseModel, ConfigDict, Field, RootModel
+
+
+class AppBuilderMenuItemResponse(BaseModel):
Review Comment:
Thanks @bugraoz93 for detailed reply!
> but there was a general agreement on splitting the packages out while keeping apache-airflow as a meta-package that brings it all together
For this purpose, I think using datamodel-code-generator tool is a good option then.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "perry2of5 (via GitHub)" <gi...@apache.org>.
perry2of5 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1901117870
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,675 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolPostBulkBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
+
+ # def_
+
+ @classmethod
+ def from_response(cls, response: httpx.Response) -> ServerResponseError | None:
+ if response.status_code < 400:
+ return None
+
+ if response.headers.get("content-type") != "application/json":
+ return None
+
+ if 400 <= response.status_code < 500:
+ response.read()
+ return cls(
+ message=f"Client error message: {response.json()}",
+ request=response.request,
+ response=response,
+ )
+
+ msg = response.json()
+
+ self = cls(message=msg, request=response.request, response=response)
+ return self
+
+
+# Decorator to apply methods to all operations, this is initiated at __init_subclass__ on BaseOperations
+SERVER_CONNECTION_REFUSED_ERROR: str = "API Server is not running, please contact your administrator."
+
+
+def _check_flag_and_exit_if_server_response_error(func):
+ """Return decorator to check for ServerResponseError and exit if the server is not running."""
+
+ def _exit_if_server_response_error(response: Any | ServerResponseError):
+ if isinstance(response, ServerResponseError):
+ rich.print(f"[bold red]Error:[/bold red] {response.response.json()}")
+ sys.exit(1)
+ return response
+
+ def wrapped(self, *args, **kwargs):
+ try:
+ if self.exit_in_error:
+ return _exit_if_server_response_error(response=func(self, *args, **kwargs))
+ else:
+ return func(self, *args, **kwargs)
+ except httpx.ConnectError:
+ rich.print(f"[bold red]{SERVER_CONNECTION_REFUSED_ERROR}[/bold red]")
+ sys.exit(1)
+
+ return wrapped
+
+
+class BaseOperations:
+ """
+ Base class for operations.
+
+ This class is used to decorate all callable methods with a check for ServerResponseError.
+ Set exit_in_error false to not exit.
+ """
+
+ __slots__ = ("client", "response", "exit_in_error")
+
+ def __init__(self, client: Client, response=None, exit_in_error: bool = True):
+ self.client = client
+ self.response = response
+ self.exit_in_error = exit_in_error
+
+ def __init_subclass__(cls, **kwargs):
+ """Decorate all callable methods with a check for ServerResponseError and exit if the server is not running."""
+ super().__init_subclass__(**kwargs)
+ for attr, value in cls.__dict__.items():
+ if callable(value):
+ setattr(cls, attr, _check_flag_and_exit_if_server_response_error(value))
+
+
+# Operations
+# TODO: Get all with limit and offset to overcome default 100 limit for all list operations
Review Comment:
Makes perfect sense.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1982197874
##########
airflow/cli/api/datamodels/_generated.py:
##########
Review Comment:
I saw it. It looks cool. It is in my TODO. Let me do that in another PR so that this won't get more changes in this :)
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1988811690
##########
airflow/cli/api/cli_api_client.py:
##########
Review Comment:
Nit: can we call this file `airflow/cli/api/client.py` -- repeating cli api twice is just noise I feel
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,226 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.api_environment = os.getenv("APACHE_AIRFLOW_CLI_ENVIRONMENT") or api_environment
+
+ @property
+ def input_cli_config_file(self) -> str:
+ """Generate path and always generate that path but let's not world readable."""
Review Comment:
I dont think we do anything here about "world readable", so remove that bit?
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,226 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.api_environment = os.getenv("APACHE_AIRFLOW_CLI_ENVIRONMENT") or api_environment
Review Comment:
No other env vars have the `APACHE_` prefix
```suggestion
self.api_environment = os.getenv("AIRFLOW_CLI_ENVIRONMENT") or api_environment
```
##########
airflow/cli/commands/remote_commands/auth_command.py:
##########
@@ -0,0 +1,45 @@
+#
+# 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.
+
+from __future__ import annotations
+
+import os
+import sys
+
+import rich
+
+from airflow.cli.api.cli_api_client import Credentials
+from airflow.utils import cli as cli_utils
+
+
+@cli_utils.action_cli
+def login(args) -> None:
+ """Login to a provider."""
+ if not args.api_token and not os.environ.get("APACHE_AIRFLOW_CLI_TOKEN"):
+ # Exit
+ rich.print("[red]No token found.")
+ rich.print(
+ "[green]Please pass:[/green] [blue]--api-token[/blue] or set "
+ "[blue]APACHE_AIRFLOW_CLI_TOKEN[/blue] environment variable to login."
+ )
+ sys.exit(1)
+ Credentials(
+ api_url=args.api_url,
+ api_token=args.api_token or os.getenv("APACHE_AIRFLOW_CLI_TOKEN"),
Review Comment:
```suggestion
api_token=token,
```
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,226 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.api_environment = os.getenv("APACHE_AIRFLOW_CLI_ENVIRONMENT") or api_environment
+
+ @property
+ def input_cli_config_file(self) -> str:
+ """Generate path and always generate that path but let's not world readable."""
+ return f"{self.api_environment}.json"
+
+ def save(self):
+ """Save the credentials to keyring and URL to disk as a file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, self.input_cli_config_file), "w") as f:
+ json.dump({"api_url": self.api_url}, f)
+ keyring.set_password("airflow-cli", f"api_token-{self.api_environment}", self.api_token)
+
+ def load(self) -> Credentials:
+ """Load the credentials from keyring and URL from disk file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if os.path.exists(default_config_dir):
+ with open(os.path.join(default_config_dir, self.input_cli_config_file)) as f:
+ credentials = json.load(f)
+ self.api_url = credentials["api_url"]
+ self.api_token = keyring.get_password("airflow-cli", f"api_token-{self.api_environment}")
+ return self
+ else:
+ rich.print("[red]No credentials found.")
+ rich.print("[green]Please run: [blue]airflow auth login")
+ sys.exit(1)
+
+
+class BearerAuth(httpx.Auth):
+ def __init__(self, token: str):
+ self.token: str = token
+
+ def auth_flow(self, request: httpx.Request):
+ if self.token:
+ request.headers["Authorization"] = "Bearer " + self.token
+ yield request
+
+
+class Client(httpx.Client):
+ """Client for the Airflow REST API."""
+
+ def __init__(self, *, base_url: str | None, dry_run: bool = False, token: str, **kwargs: Any):
+ if (not base_url) ^ dry_run:
+ raise ValueError(f"Can only specify one of {base_url=} or {dry_run=}")
+ auth = BearerAuth(token)
+
+ if dry_run:
+ # If dry run is requested, install a no op handler so that simple tasks can "heartbeat" using a
+ # real client, but just don't make any HTTP requests
+ kwargs["base_url"] = "dry-run://server"
+ else:
+ kwargs["base_url"] = f"{base_url}/public"
Review Comment:
```suggestion
def __init__(self, *, base_url: str, token: str, **kwargs: Any):
auth = BearerAuth(token)
kwargs["base_url"] = f"{base_url}/public"
```
i think
##########
airflow/cli/commands/remote_commands/auth_command.py:
##########
@@ -0,0 +1,45 @@
+#
+# 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.
+
+from __future__ import annotations
+
+import os
+import sys
+
+import rich
+
+from airflow.cli.api.cli_api_client import Credentials
+from airflow.utils import cli as cli_utils
+
+
+@cli_utils.action_cli
+def login(args) -> None:
+ """Login to a provider."""
+ if not args.api_token and not os.environ.get("APACHE_AIRFLOW_CLI_TOKEN"):
+ # Exit
+ rich.print("[red]No token found.")
+ rich.print(
+ "[green]Please pass:[/green] [blue]--api-token[/blue] or set "
+ "[blue]APACHE_AIRFLOW_CLI_TOKEN[/blue] environment variable to login."
Review Comment:
```suggestion
"[blue]AIRFLOW_CLI_TOKEN[/blue] environment variable to login."
```
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,226 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.api_environment = os.getenv("APACHE_AIRFLOW_CLI_ENVIRONMENT") or api_environment
+
+ @property
+ def input_cli_config_file(self) -> str:
+ """Generate path and always generate that path but let's not world readable."""
+ return f"{self.api_environment}.json"
+
+ def save(self):
+ """Save the credentials to keyring and URL to disk as a file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, self.input_cli_config_file), "w") as f:
+ json.dump({"api_url": self.api_url}, f)
+ keyring.set_password("airflow-cli", f"api_token-{self.api_environment}", self.api_token)
+
+ def load(self) -> Credentials:
+ """Load the credentials from keyring and URL from disk file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if os.path.exists(default_config_dir):
+ with open(os.path.join(default_config_dir, self.input_cli_config_file)) as f:
+ credentials = json.load(f)
+ self.api_url = credentials["api_url"]
+ self.api_token = keyring.get_password("airflow-cli", f"api_token-{self.api_environment}")
+ return self
+ else:
+ rich.print("[red]No credentials found.")
+ rich.print("[green]Please run: [blue]airflow auth login")
+ sys.exit(1)
Review Comment:
We shouldn't be printing here as this makes it harder to use this "properly". This should raise something, and yhe print and exit be closer to the cli layer
##########
airflow/cli/api/cli_api_client.py:
##########
Review Comment:
Wait, we have both.
Merge these fns in to the other file, its not clear from the outside which one to use otherwise
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,684 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkActionResponse,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolBulkActionResponse,
+ PoolBulkBody,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableBulkActionResponse,
+ VariableBulkBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
+
+ # def_
+
+ @classmethod
+ def from_response(cls, response: httpx.Response) -> ServerResponseError | None:
+ if response.status_code < 400:
+ return None
+
+ if response.headers.get("content-type") != "application/json":
+ return None
+
+ if 400 <= response.status_code < 500:
+ response.read()
+ return cls(
+ message=f"Client error message: {response.json()}",
+ request=response.request,
+ response=response,
+ )
+
+ msg = response.json()
+
+ self = cls(message=msg, request=response.request, response=response)
+ return self
+
+
+# Decorator to apply methods to all operations, this is initiated at __init_subclass__ on BaseOperations
+SERVER_CONNECTION_REFUSED_ERROR: str = "API Server is not running, please contact your administrator."
+
+
+def _check_flag_and_exit_if_server_response_error(func):
+ """Return decorator to check for ServerResponseError and exit if the server is not running."""
+
+ def _exit_if_server_response_error(response: Any | ServerResponseError):
+ if isinstance(response, ServerResponseError):
+ rich.print(f"[bold red]Error:[/bold red] {response.response.json()}")
+ sys.exit(1)
+ return response
+
+ def wrapped(self, *args, **kwargs):
+ try:
+ if self.exit_in_error:
+ return _exit_if_server_response_error(response=func(self, *args, **kwargs))
+ else:
+ return func(self, *args, **kwargs)
+ except httpx.ConnectError as e:
+ rich.print(f"error: {e}")
+ rich.print(f"[bold red]{SERVER_CONNECTION_REFUSED_ERROR}[/bold red]")
+ sys.exit(1)
Review Comment:
Similar here, this shouldnt be handled so "deep" in the stack
##########
airflow/cli/cli_config.py:
##########
@@ -1496,15 +1527,14 @@ class GroupCommand(NamedTuple):
name="test",
help="Test a connection",
func=lazy_load_command("airflow.cli.commands.remote_commands.connection_command.connections_test"),
- args=(ARG_CONN_ID, ARG_VERBOSE),
+ args=(ARG_CONN_ID, ARG_CONN_TYPE_POSITIONAL, ARG_VERBOSE),
Review Comment:
Why didn't we need this before? Was it just missed?
##########
airflow/cli/commands/remote_commands/connection_command.py:
##########
@@ -64,35 +70,31 @@ def _connection_mapper(conn: Connection) -> dict[str, Any]:
@suppress_logs_and_warning
@providers_configuration_loaded
-def connections_get(args):
+@provide_cli_api_client
+def connections_get(args, cli_api_client=NEW_CLI_API_CLIENT):
"""Get a connection."""
- try:
- conn = BaseHook.get_connection(args.conn_id)
- except AirflowNotFoundException:
- raise SystemExit("Connection not found.")
Review Comment:
I think something like this is the error handling pattern we should keep
##########
hatch_build.py:
##########
@@ -225,6 +225,8 @@
"itsdangerous>=2.0",
"jinja2>=3.0.0",
"jsonschema>=4.18.0",
+ # Added for CLI
+ "keyring>=25.6.0",
Review Comment:
Do we recommend/require anywhere the native os backends for this?
##########
hatch_build.py:
##########
@@ -238,6 +240,8 @@
"opentelemetry-exporter-otlp>=1.24.0",
"packaging>=23.2",
"pathspec>=0.9.0",
+ # Added for CLI
Review Comment:
```suggestion
```
##########
airflow/cli/commands/remote_commands/auth_command.py:
##########
@@ -0,0 +1,45 @@
+#
+# 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.
+
+from __future__ import annotations
+
+import os
+import sys
+
+import rich
+
+from airflow.cli.api.cli_api_client import Credentials
+from airflow.utils import cli as cli_utils
+
+
+@cli_utils.action_cli
+def login(args) -> None:
+ """Login to a provider."""
+ if not args.api_token and not os.environ.get("APACHE_AIRFLOW_CLI_TOKEN"):
Review Comment:
```suggestion
if not (token := args.api_token or os.environ.get("AIRFLOW_CLI_TOKEN")):
```
##########
hatch_build.py:
##########
@@ -225,6 +225,8 @@
"itsdangerous>=2.0",
"jinja2>=3.0.0",
"jsonschema>=4.18.0",
+ # Added for CLI
Review Comment:
```suggestion
```
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1945414617
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,228 @@
+# 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.
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str
+ api_token: str
+
+ def __init__(self, api_url: str, api_token: str = "NO_TOKEN"):
+ self.api_url = api_url
+ self.api_token = api_token
+
+ def save(self):
+ """Save the credentials."""
+ default_config_dir = os.path.expanduser("~/.config/airflow")
+ print(f"Saving credentials to {default_config_dir}")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, "credentials.json"), "w") as f:
Review Comment:
+1 also means during loading like SSH we should reject if they are world-readable by accident?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1912094745
##########
airflow/cli/api/datamodels/_generated.py:
##########
@@ -0,0 +1,1300 @@
+# 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.
+
+# generated by datamodel-codegen:
+# filename: http://0.0.0.0:9091/openapi.json
+# version: 0.26.4
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from enum import Enum
+from typing import Annotated, Any, Optional, Union
+
+from pydantic import BaseModel, ConfigDict, Field, RootModel
+
+
+class AppBuilderMenuItemResponse(BaseModel):
Review Comment:
Hi @jason810496,
This is a good question. I made it like this to reduce dependency on Rest API (FastAPI). This means that CLI shouldn't be impacted and needs to be updated all the time when there is a change on the API end. Both can have separate flows when it comes to their lifecycles while releasing changes. This would allow us time to adapt. Otherwise, whoever doing changes to the data models on API will have to make mandatory changes to the CLI code else tests will fail.
Of course, there could be still an impact if there are breaking changes on the API end which can make some changes mandatory for CLI. I think if we think about this, this brought up another discussion point in [a section in the AIP-81](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=315493347#AIP81EnhancedSecurityinCLIviaIntegrationofAPI-ReleaseStrategy) which we should discuss with the broader group concerning release strategy of Apache Airflow CLI. For me, in the long run, we should reduce the dependencies as much as possible to make this real in case we would like to go with this route. This would %100 eliminate mandatory changes.
In [one of the dev calls](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=308153072#Airflow3Devcall:MeetingNotes-Summary.6) (8 August 2024) for Apache Airflow v3, there was a question and decision around this topic. Meanwhile, this doesn't mean they will have separate versions but may have separate flows to do their development while releasing newer versions together. Or maybe in the future, the decision could be on also releasing it similar to providers and TaskSDK as separate packages. In both cases, reducing this dependency will be useful.
> Should we split Webserver, SDK, CLI, Scheduler, and Triggerer into separately installable packages for the users, while the dev code is in same mono-repo? (@potiuk)
> * The consensus was to wait until there is decent progress on AIP-72 implementation, but there was a general agreement on splitting the packages out while keeping apache-airflow as a meta-package that brings it all together. The intention is not to have a separate version scheme or release these separately however unlike Providers.
This decision meant we should lean forward making apache-airflow as a meta-package for these main components as possible.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 - API Communication Mechanism [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2738492886
Failure is unrelated. Merging!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2719279219
Thanks for the major rework and updates. Looked at the code and this is okay.
I wanted to test interactively and failed miserably because... when calling `airflow auth...` it seems I need an API token. `--help` was not able to help me, no docs are added. Also no PR hints. Where can I (and a potential user in future) create an API token? Via CLI? Either I am too stupid to read, lost the context... or we need to add some docs such that users also would know how... or some more hints needed in `--help` giving hints to generate an API-Token. I expected to be able to pass user+password (admin/admin)...
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1982195398
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,244 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
Review Comment:
Removed
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1990144043
##########
airflow/cli/commands/remote_commands/connection_command.py:
##########
@@ -64,35 +70,31 @@ def _connection_mapper(conn: Connection) -> dict[str, Any]:
@suppress_logs_and_warning
@providers_configuration_loaded
-def connections_get(args):
+@provide_cli_api_client
+def connections_get(args, cli_api_client=NEW_CLI_API_CLIENT):
"""Get a connection."""
- try:
- conn = BaseHook.get_connection(args.conn_id)
- except AirflowNotFoundException:
- raise SystemExit("Connection not found.")
Review Comment:
Added them back while throwing from inner methods.
##########
airflow/cli/commands/remote_commands/auth_command.py:
##########
@@ -0,0 +1,45 @@
+#
+# 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.
+
+from __future__ import annotations
+
+import os
+import sys
+
+import rich
+
+from airflow.cli.api.cli_api_client import Credentials
+from airflow.utils import cli as cli_utils
+
+
+@cli_utils.action_cli
+def login(args) -> None:
+ """Login to a provider."""
+ if not args.api_token and not os.environ.get("APACHE_AIRFLOW_CLI_TOKEN"):
+ # Exit
+ rich.print("[red]No token found.")
+ rich.print(
+ "[green]Please pass:[/green] [blue]--api-token[/blue] or set "
+ "[blue]APACHE_AIRFLOW_CLI_TOKEN[/blue] environment variable to login."
+ )
+ sys.exit(1)
+ Credentials(
+ api_url=args.api_url,
+ api_token=args.api_token or os.getenv("APACHE_AIRFLOW_CLI_TOKEN"),
Review Comment:
Updated as suggested
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996413052
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,264 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import sys
+from functools import wraps
+from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
+
+import httpx
+import keyring
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.exceptions import AirflowNotFoundException
+from airflow.typing_compat import ParamSpec
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
Review Comment:
It was raised earlier in the PR. I agree instance URL is unique but the URLs aren't changing that much so I persist under a file and aimed to separate with using multiple files. In the current state, maybe it does not bring any value but I think we can store more configs locally in the file in the future to make this more usable.
What is your suggestion for the unique URL? Should the user use the URL in CLI or just set an env var?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726819365
> As long as we are able to prove out that the interaction with the api, and foundational pieces that are in core, are good by feature freeze, we are golden. This new cli package wouldn't fall under the freeze :)
Agreed. I also like your idea @jedcunningham of keeping current commands without auth and a separate package for remote stuff. We can re-use `airflowctl` name too since I own that. Naming aside, I like the idea
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726849569
> > > As long as we are able to prove out that the interaction with the api, and foundational pieces that are in core, are good by feature freeze, we are golden. This new cli package wouldn't fall under the freeze :)
> >
> >
> > Agreed. I also like your idea @jedcunningham of keeping current commands without auth and a separate package for remote stuff. We can re-use `airflowctl` name too since I own that. Naming aside, I like the idea
>
> We could later **actually** incorporate `airflowctl` into that new package @kaxil -> I see no issue with that if you are willing to contribute it still :D
I am also up for that :raised_hands:
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "vikramkoka (via GitHub)" <gi...@apache.org>.
vikramkoka commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2727230250
Love the evolution here
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996635145
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,487 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkActionResponse,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolBulkActionResponse,
+ PoolBulkBody,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableBulkActionResponse,
+ VariableBulkBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
Review Comment:
```suggestion
```
No need to do this. At first I thought you might have been adding typing, or forcing kwargsonly, but it's already like this upstream.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 - API Communication Mechanism [airflow]
Posted by "jason810496 (via GitHub)" <gi...@apache.org>.
jason810496 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2742628320
Hi @bugraoz93, since this PR has been merged, I think we can start working on the https://github.com/apache/airflow/issues/45661 meta issue, right? Or are there any other dependencies that need to be completed first?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "perry2of5 (via GitHub)" <gi...@apache.org>.
perry2of5 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1900278576
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,675 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolPostBulkBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
+
+ # def_
+
+ @classmethod
+ def from_response(cls, response: httpx.Response) -> ServerResponseError | None:
+ if response.status_code < 400:
+ return None
+
+ if response.headers.get("content-type") != "application/json":
+ return None
+
+ if 400 <= response.status_code < 500:
+ response.read()
+ return cls(
+ message=f"Client error message: {response.json()}",
+ request=response.request,
+ response=response,
+ )
+
+ msg = response.json()
+
+ self = cls(message=msg, request=response.request, response=response)
+ return self
+
+
+# Decorator to apply methods to all operations, this is initiated at __init_subclass__ on BaseOperations
+SERVER_CONNECTION_REFUSED_ERROR: str = "API Server is not running, please contact your administrator."
+
+
+def _check_flag_and_exit_if_server_response_error(func):
+ """Return decorator to check for ServerResponseError and exit if the server is not running."""
+
+ def _exit_if_server_response_error(response: Any | ServerResponseError):
+ if isinstance(response, ServerResponseError):
+ rich.print(f"[bold red]Error:[/bold red] {response.response.json()}")
+ sys.exit(1)
+ return response
+
+ def wrapped(self, *args, **kwargs):
+ try:
+ if self.exit_in_error:
+ return _exit_if_server_response_error(response=func(self, *args, **kwargs))
+ else:
+ return func(self, *args, **kwargs)
+ except httpx.ConnectError:
+ rich.print(f"[bold red]{SERVER_CONNECTION_REFUSED_ERROR}[/bold red]")
+ sys.exit(1)
+
+ return wrapped
+
+
+class BaseOperations:
+ """
+ Base class for operations.
+
+ This class is used to decorate all callable methods with a check for ServerResponseError.
+ Set exit_in_error false to not exit.
+ """
+
+ __slots__ = ("client", "response", "exit_in_error")
+
+ def __init__(self, client: Client, response=None, exit_in_error: bool = True):
+ self.client = client
+ self.response = response
+ self.exit_in_error = exit_in_error
+
+ def __init_subclass__(cls, **kwargs):
+ """Decorate all callable methods with a check for ServerResponseError and exit if the server is not running."""
+ super().__init_subclass__(**kwargs)
+ for attr, value in cls.__dict__.items():
+ if callable(value):
+ setattr(cls, attr, _check_flag_and_exit_if_server_response_error(value))
+
+
+# Operations
+# TODO: Get all with limit and offset to overcome default 100 limit for all list operations
Review Comment:
Would paging the results be better than getting all? Perhaps the XxxxCollectionResponse could track the limit and offset of the current collection and have next_page() and prev_page() methods. This would require the XxxxCollectionResponse contain a link back to the operator I suppose. This seems a little cleaner than having the consumer manipulate the limit and offset locally to page the results. I'm wary of getting all in a single call since the result size could be large. Probably not an actual issue in this context.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1992268958
##########
hatch_build.py:
##########
@@ -225,6 +225,8 @@
"itsdangerous>=2.0",
"jinja2>=3.0.0",
"jsonschema>=4.18.0",
+ # Added for CLI
+ "keyring>=25.6.0",
Review Comment:
I have added the `keyring.alt` earlier for development purposes for the required part. This is only recommended for development. So this will be enough to test. Surely production use cases should be recommended. Closing this thread for now, I will tag you on the docs so we can continue there. Thanks again Ash for your time on this one!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2719299572
> Thanks for the major rework and updates. Looked at the code and this is okay.
>
> I wanted to test interactively and failed miserably because... when calling `airflow auth...` it seems I need an API token. `--help` was not able to help me, no docs are added. Also no PR hints. Where can I (and a potential user in future) create an API token? Via CLI? Either I am too stupid to read, lost the context... or we need to add some docs such that users also would know how... or some more hints needed in `--help` giving hints to generate an API-Token. I expected to be able to pass user+password (admin/admin)...
Thanks a lot for your review and comment Jens! Maybe a bit more context could help with these. I created this doc earlier and shared it in the dev call+dev channel. Please take a look if you have time. Considering deadlines and simplicity the decision was to pass the token to CLI which will be taken from the profile page. I think we should provide that but not sure we should include it in this huge PR or even in 3.0. I would be happy to implement that. I created a follow-up #47703. If you think this would be crucial for the users, I can try to implement it within 3.0 via including into AIP-81.
https://docs.google.com/document/d/1BSEQxKEOArPRCclfCrAjAN5hjC56vG0R5nZPc3pxF9Y/edit?usp=sharing
I know the docs are missing for the user side.
For the documentation, I agree we should include clear guidelines on usage. I don't want to blow this PR more so I created a follow-up for that and already started working on it :) #47537 Hope this fills the gaps and addresses your concerns.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2722637124
Okay, attempted (again) and... there is no "profile" page. Attempted to grab the "token" from the browser inspector:

...but this was not working, `airflow login auth` was accepting. But then got a 403 when attempting to `airflow connections list`. So
(1) Still even after re-reading the Google spec doc I am not able to find the right token. Some description is needed, else almost nobody can use the CLI. (Hope it is not an individual short-coming just in front of my keyboard)
(2) I would encourage that if a user calls `airflow auth login --api-token <something>` that the token is also validated. It seems it was "just" stored but was not working. Or the `airflow connections list` call is broken.
(3) With every call I was asked for the keystore password. Is there a way to temporarily store this in the session? Would be tideous to enter the passphrase of the keystore every time. (Or is this a specific shortcoming of the breeze container?)
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1990149036
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,684 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkActionResponse,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolBulkActionResponse,
+ PoolBulkBody,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableBulkActionResponse,
+ VariableBulkBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
+
+ # def_
+
+ @classmethod
+ def from_response(cls, response: httpx.Response) -> ServerResponseError | None:
+ if response.status_code < 400:
+ return None
+
+ if response.headers.get("content-type") != "application/json":
+ return None
+
+ if 400 <= response.status_code < 500:
+ response.read()
+ return cls(
+ message=f"Client error message: {response.json()}",
+ request=response.request,
+ response=response,
+ )
+
+ msg = response.json()
+
+ self = cls(message=msg, request=response.request, response=response)
+ return self
+
+
+# Decorator to apply methods to all operations, this is initiated at __init_subclass__ on BaseOperations
+SERVER_CONNECTION_REFUSED_ERROR: str = "API Server is not running, please contact your administrator."
+
+
+def _check_flag_and_exit_if_server_response_error(func):
+ """Return decorator to check for ServerResponseError and exit if the server is not running."""
+
+ def _exit_if_server_response_error(response: Any | ServerResponseError):
+ if isinstance(response, ServerResponseError):
+ rich.print(f"[bold red]Error:[/bold red] {response.response.json()}")
+ sys.exit(1)
+ return response
+
+ def wrapped(self, *args, **kwargs):
+ try:
+ if self.exit_in_error:
+ return _exit_if_server_response_error(response=func(self, *args, **kwargs))
+ else:
+ return func(self, *args, **kwargs)
+ except httpx.ConnectError as e:
+ rich.print(f"error: {e}")
+ rich.print(f"[bold red]{SERVER_CONNECTION_REFUSED_ERROR}[/bold red]")
+ sys.exit(1)
Review Comment:
Removed and raised the exception from inner parts
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1981833246
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,244 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
Review Comment:
This handler doesn't make any sense for the CLI
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1981839251
##########
airflow/cli/api/datamodels/_generated.py:
##########
Review Comment:
There should probably be auto-generated via pre-commit, which I've now finally done in the TaskSDK if you want to copy that
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2702104198
Thanks, Ash for your review! Updated the code accordingly.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1978278986
##########
airflow/cli/commands/remote_commands/connection_command.py:
##########
@@ -108,18 +110,54 @@ def _connection_to_dict(conn: Connection) -> dict:
}
-def create_default_connections(args):
- db_create_default_connections()
+@provide_cli_api_client
+def create_default_connections(args, cli_api_client=NEW_CLI_API_CLIENT):
+ """Create default connections."""
+ cli_api_client.connections.create_defaults()
+ print("Default connections have been created.")
+
+
+def _response_to_connection(response: ConnectionResponse) -> Connection:
+ # TODO: Return is_encrypted from API to properly convert to Connection, otherwise it will be None
Review Comment:
`is_encrypted` is a column in the database and a parameter for `connection`. Normally, the direct database call returns this but we need to include this functionality if we want to bring back `is_encrypted`. This TODO is making that happen after this PR. I have updated the TODO to be more clear :)
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726706326
So, after sleeping on this idea, I want to pitch it...
Have you considered having this new api-driven cli be completely standalone and in its own package from day 1? This would leave the existing db-backed cli as-is and functional. The vast majority of this PR is still usable, it'd just not be in `airflow` and not whack the old command.
I'm imagining the scenario where I'm trying to troubleshoot in a remote deployment, jump into the scheduler pod, and try to run `airflow config get-value x y`. Having to auth not on my machine, where other people could also have access and grab my token, then clean up when I'm done isn't ideal. Effectively it'd have to do my troubleshooting remotely, which could be bit a bit cumbersome.
Basically, this new api-driven command could be more like kubectl, airflowctl.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726800317
> Speaking of what we are going to release - we should be able to release a separate "apache-airflow-cli" distribution and only that distribution should have`keyring` as paraemeter and should authenticate with the server.
>
> Now - we need to figure out how to keep the `remote` commands still working remotely in a separate package, while also have them available as airflow commands in `apache-airflow-core` distribution (without the keyring).
>
> That is a bit tricky, but I am sure we can work it out.
Thanks Jarek! How about I remove the connection command integration from the PR? Let's merge the API integration without integrating into any command so that maintaining that part would be a lot easier even while moving out of the package. I then make the split into `apache-airflow-cli` and add this connection integration there. From there we start the transition to other remote commands.
For the having all in the `apache-airflow-core` too is indeed tricky. We should come up with something that shouldn't need duplicate work for API and DB calls separately for each command if we don't want to remove remote commands from `apache-airflow-core`.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726787899
Yeah. I am here with @jedcunningham -> all the commands should work "as is" without keyring installation and authentication
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2725970238
> Might the failure that I had in (2) be related with #47754 ?
>
> If (3) is only happening with breeze but a "normal" OS keeps the passphrase then it is okay.
>
> Yeah and understand the aim. Supporting this and overall otherwise I am happy with the PR!
I couldn't check in details but I will now tag this as 3.x.x (3.1.0 :eyes:) since Monday is feature freeze. Until Monday, I will focus on fixing bugs and help as much as I can to 3.0. I will come back to this in a couple of days.
(2) Not sure, seems an unrelated thought. I will check this and either fix or check what is changed or not working. The API will also get its more stable state with all bug fixes and auth finalisation and it will be a lot more stable.
(3) I will test it in a different OS and ensure that is not the case otherwise, I will include a safe way to persist.
Thanks Jens!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1996403211
##########
airflow/cli/api/operations.py:
##########
@@ -0,0 +1,487 @@
+# 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.
+
+from __future__ import annotations
+
+import datetime
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import structlog
+
+from airflow.cli.api.datamodels._generated import (
+ AssetAliasCollectionResponse,
+ AssetAliasResponse,
+ AssetCollectionResponse,
+ AssetResponse,
+ BackfillPostBody,
+ BackfillResponse,
+ Config,
+ ConnectionBody,
+ ConnectionBulkActionResponse,
+ ConnectionBulkBody,
+ ConnectionCollectionResponse,
+ ConnectionResponse,
+ ConnectionTestResponse,
+ DAGDetailsResponse,
+ DAGResponse,
+ DAGRunCollectionResponse,
+ DAGRunResponse,
+ JobCollectionResponse,
+ PoolBulkActionResponse,
+ PoolBulkBody,
+ PoolCollectionResponse,
+ PoolPatchBody,
+ PoolPostBody,
+ PoolResponse,
+ ProviderCollectionResponse,
+ TriggerDAGRunPostBody,
+ VariableBody,
+ VariableBulkActionResponse,
+ VariableBulkBody,
+ VariableCollectionResponse,
+ VariableResponse,
+ VersionInfo,
+)
+
+if TYPE_CHECKING:
+ from airflow.cli.api.client import Client
+ from airflow.utils.state import DagRunState
+
+log = structlog.get_logger(logger_name=__name__)
+
+
+# Generic Server Response Error
+class ServerResponseError(httpx.HTTPStatusError):
+ """Server response error (Generic)."""
+
+ def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response):
+ super().__init__(message, request=request, response=response)
+
+ # def_
+
Review Comment:
Thanks, this one missed my eyes! I will delete this
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2727386603
> Love the evolution here
Amazing collaboration! I am thrilled with what it has become.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2566759853
Note: As PR #45312 has been merged, the code formatting rules have changed for new UI. Please rebase and re-run pre-commit checks to ensure that formatting in folder airflow/ui is adjusted.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 - API Communication Mechanism [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r2004388821
##########
pyproject.toml:
##########
@@ -317,6 +317,9 @@ testing = ["dev", "providers.tests", "tests_common", "tests"]
"providers/cncf/*/src/airflow/providers/cncf/__init__.py" = ["I002"]
"providers/dbt/*/src/airflow/providers/dbt/__init__.py" = ["I002"]
"providers/microsoft/*/src/airflow/providers/microsoft/__init__.py" = ["I002"]
+"providers/tests/__init__.py" = ["I002"]
+"providers/__init__.py" = ["I002"]
Review Comment:
Thanks! They weren't intentional and missed after the rebase. I rebased again and removed these additions.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 - API Communication Mechanism [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2738494507
#protm
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1981832128
##########
airflow/cli/api/cli_api_client.py:
##########
@@ -0,0 +1,72 @@
+# 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.
+
+from __future__ import annotations
+
+import contextlib
+from functools import wraps
+from typing import Callable, TypeVar, cast
+
+import httpx
+
+from airflow.cli.api.client import Client, Credentials
+from airflow.typing_compat import ParamSpec
+
+PS = ParamSpec("PS")
+RT = TypeVar("RT")
+
+
+@contextlib.contextmanager
+def get_client():
+ """Get CLI API client."""
+ cli_api_client = None
+ try:
+ credentials = Credentials().load()
+ limits = httpx.Limits(max_keepalive_connections=1, max_connections=10)
Review Comment:
10 concurrent connections seems high for a cli. Should this be
```suggestion
limits = httpx.Limits(max_keepalive_connections=1, max_connections=1)
```
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1981844050
##########
airflow/cli/commands/remote_commands/auth_command.py:
##########
@@ -0,0 +1,44 @@
+#
+# 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.
+
+from __future__ import annotations
+
+import os
+import sys
+
+import rich
+
+from airflow.cli.api.cli_api_client import Credentials
+from airflow.utils import cli as cli_utils
+
+
+@cli_utils.action_cli
+def login(args) -> None:
+ """Login to a provider."""
+ if not args.api_token and not os.environ.get("APACHE_AIRFLOW_CLI_TOKEN"):
+ # Exit
+ rich.print("[red]No token found.")
+ rich.print(
+ "[green]Please pass: [blue]--api-token or set APACHE_AIRFLOW_CLI_TOKEN environment variable to login."
Review Comment:
These color tags should be closed I think?
```suggestion
"[green]Please pass: [blue]--api-token[/blue] or set APACHE_AIRFLOW_CLI_TOKEN environment variable to login."
```
(I'm guessing)
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2723689995
Might the failure that I had in (2) be related with https://github.com/apache/airflow/pull/47754 ?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2726768579
> The idea is indeed to have this as a separate package for sure. We can think of all remote commands that will be in the new CLI package.
Makes sense, but I think these should _also_ be remote commands, not _just_ remote commands. That's the crux of my point.
e.g. thinking in context of the docker compose example we publish, I doubt we want to add a keyring backend into the official docker images. So users either 1) need to modify the image before half the cli is usable or 2) install the cli separately out on their host, which isn't very a "docker compose" friendly pattern.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1985466478
##########
airflow/cli/api/datamodels/_generated.py:
##########
Review Comment:
Created a follow-up for it #47509. Will do it there, resolving this thanks!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1945092599
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,228 @@
+# 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.
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import rich
+import structlog
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.utils.types import DagRunType
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+def noop_handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ log.debug("Dry-run request", method=request.method, path=path)
+ # TODO change for test
+ if path.startswith("/task-instances/") and path.endswith("/run"):
+ # Return a fake context
+ return httpx.Response(
+ 200,
+ json={
+ "dag_run": {
+ "dag_id": "test_dag",
+ "run_id": "test_run",
+ "logical_date": "2021-01-01T00:00:00Z",
+ "start_date": "2021-01-01T00:00:00Z",
+ "run_type": DagRunType.MANUAL,
+ },
+ },
+ )
+ return httpx.Response(200, json={"text": "Hello, world!"})
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str
+ api_token: str
+
+ def __init__(self, api_url: str, api_token: str = "NO_TOKEN"):
+ self.api_url = api_url
+ self.api_token = api_token
+
+ def save(self):
+ """Save the credentials."""
+ default_config_dir = os.path.expanduser("~/.config/airflow")
+ print(f"Saving credentials to {default_config_dir}")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, "credentials.json"), "w") as f:
Review Comment:
We should ensure these aren't world readable.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1945084743
##########
airflow/cli/api/__init__.py:
##########
Review Comment:
@potiuk Do you think we should have this as a separate stand-alone dist, not part to of "core" airflow?
If so this should be `airflow-cli/src/airflow/cli/api/__init__.py` etc.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1990134994
##########
hatch_build.py:
##########
@@ -225,6 +225,8 @@
"itsdangerous>=2.0",
"jinja2>=3.0.0",
"jsonschema>=4.18.0",
+ # Added for CLI
Review Comment:
I added not to forget while moving out CLI but we can identify at that time. Removed.
##########
hatch_build.py:
##########
@@ -238,6 +240,8 @@
"opentelemetry-exporter-otlp>=1.24.0",
"packaging>=23.2",
"pathspec>=0.9.0",
+ # Added for CLI
Review Comment:
Removed.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1990149382
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,226 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.api_environment = os.getenv("APACHE_AIRFLOW_CLI_ENVIRONMENT") or api_environment
+
+ @property
+ def input_cli_config_file(self) -> str:
+ """Generate path and always generate that path but let's not world readable."""
+ return f"{self.api_environment}.json"
+
+ def save(self):
+ """Save the credentials to keyring and URL to disk as a file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, self.input_cli_config_file), "w") as f:
+ json.dump({"api_url": self.api_url}, f)
+ keyring.set_password("airflow-cli", f"api_token-{self.api_environment}", self.api_token)
+
+ def load(self) -> Credentials:
+ """Load the credentials from keyring and URL from disk file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if os.path.exists(default_config_dir):
+ with open(os.path.join(default_config_dir, self.input_cli_config_file)) as f:
+ credentials = json.load(f)
+ self.api_url = credentials["api_url"]
+ self.api_token = keyring.get_password("airflow-cli", f"api_token-{self.api_environment}")
+ return self
+ else:
+ rich.print("[red]No credentials found.")
+ rich.print("[green]Please run: [blue]airflow auth login")
+ sys.exit(1)
+
+
+class BearerAuth(httpx.Auth):
+ def __init__(self, token: str):
+ self.token: str = token
+
+ def auth_flow(self, request: httpx.Request):
+ if self.token:
+ request.headers["Authorization"] = "Bearer " + self.token
+ yield request
+
+
+class Client(httpx.Client):
+ """Client for the Airflow REST API."""
+
+ def __init__(self, *, base_url: str | None, dry_run: bool = False, token: str, **kwargs: Any):
+ if (not base_url) ^ dry_run:
+ raise ValueError(f"Can only specify one of {base_url=} or {dry_run=}")
+ auth = BearerAuth(token)
+
+ if dry_run:
+ # If dry run is requested, install a no op handler so that simple tasks can "heartbeat" using a
+ # real client, but just don't make any HTTP requests
+ kwargs["base_url"] = "dry-run://server"
+ else:
+ kwargs["base_url"] = f"{base_url}/public"
Review Comment:
Yes, updated as suggested
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1990150027
##########
airflow/cli/api/client.py:
##########
@@ -0,0 +1,226 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from typing import TYPE_CHECKING, Any
+
+import httpx
+import keyring
+import rich
+import structlog
+from platformdirs import user_config_path
+from uuid6 import uuid7
+
+from airflow.cli.api.operations import (
+ AssetsOperations,
+ BackfillsOperations,
+ ConfigOperations,
+ ConnectionsOperations,
+ DagOperations,
+ DagRunOperations,
+ JobsOperations,
+ PoolsOperations,
+ ProvidersOperations,
+ ServerResponseError,
+ VariablesOperations,
+ VersionOperations,
+)
+from airflow.version import version
+
+if TYPE_CHECKING:
+ # # methodtools doesn't have typestubs, so give a stub
+ def lru_cache(maxsize: int | None = 128):
+ def wrapper(f):
+ return f
+
+ return wrapper
+else:
+ from methodtools import lru_cache
+
+log = structlog.get_logger(logger_name=__name__)
+
+__all__ = [
+ "Client",
+ "Credentials",
+]
+
+
+def add_correlation_id(request: httpx.Request):
+ request.headers["correlation-id"] = str(uuid7())
+
+
+def get_json_error(response: httpx.Response):
+ """Raise a ServerResponseError if we can extract error info from the error."""
+ err = ServerResponseError.from_response(response)
+ if err:
+ log.warning("Server error ", extra=dict(err.response.json()))
+ raise err
+
+
+def raise_on_4xx_5xx(response: httpx.Response):
+ return get_json_error(response) or response.raise_for_status()
+
+
+# Credentials for the API
+class Credentials:
+ """Credentials for the API."""
+
+ api_url: str | None
+ api_token: str | None
+ api_environment: str
+
+ def __init__(
+ self,
+ api_url: str | None = None,
+ api_token: str | None = None,
+ api_environment: str = "production",
+ ):
+ self.api_url = api_url
+ self.api_token = api_token
+ self.api_environment = os.getenv("APACHE_AIRFLOW_CLI_ENVIRONMENT") or api_environment
+
+ @property
+ def input_cli_config_file(self) -> str:
+ """Generate path and always generate that path but let's not world readable."""
+ return f"{self.api_environment}.json"
+
+ def save(self):
+ """Save the credentials to keyring and URL to disk as a file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if not os.path.exists(default_config_dir):
+ os.makedirs(default_config_dir)
+ with open(os.path.join(default_config_dir, self.input_cli_config_file), "w") as f:
+ json.dump({"api_url": self.api_url}, f)
+ keyring.set_password("airflow-cli", f"api_token-{self.api_environment}", self.api_token)
+
+ def load(self) -> Credentials:
+ """Load the credentials from keyring and URL from disk file."""
+ default_config_dir = user_config_path("airflow", "Apache Software Foundation")
+ if os.path.exists(default_config_dir):
+ with open(os.path.join(default_config_dir, self.input_cli_config_file)) as f:
+ credentials = json.load(f)
+ self.api_url = credentials["api_url"]
+ self.api_token = keyring.get_password("airflow-cli", f"api_token-{self.api_environment}")
+ return self
+ else:
+ rich.print("[red]No credentials found.")
+ rich.print("[green]Please run: [blue]airflow auth login")
+ sys.exit(1)
Review Comment:
Moved them to the CLI layer, and everything is now just throwing the exceptions
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on code in PR #45300:
URL: https://github.com/apache/airflow/pull/45300#discussion_r1990143702
##########
hatch_build.py:
##########
@@ -225,6 +225,8 @@
"itsdangerous>=2.0",
"jinja2>=3.0.0",
"jsonschema>=4.18.0",
+ # Added for CLI
+ "keyring>=25.6.0",
Review Comment:
Yes, the library offers a variety of support, including third-party backends. I will include them here #47537.
I think we should follow the same recommendation. For example, Keyrings and Windows Credential Locker are already native libraries. Maybe depends on the Linux distro, there could be changes but KDE seems legit. Do you have anything in your mind?
> These recommended keyring backends are supported:
macOS [Keychain](https://en.wikipedia.org/wiki/Keychain_%28software%29)
Freedesktop [Secret Service](http://standards.freedesktop.org/secret-service/) supports many DE including GNOME (requires [secretstorage](https://pypi.python.org/pypi/secretstorage))
KDE4 & KDE5 [KWallet](https://en.wikipedia.org/wiki/KWallet) (requires [dbus](https://pypi.python.org/pypi/dbus-python))
[Windows Credential Locker](https://docs.microsoft.com/en-us/windows/uwp/security/credential-locker)
Other keyring implementations are available through [Third-Party Backends](https://github.com/jaraco/keyring#third-party-backends).
**&TLDR**
I will also include they can still leverage the support for 3rd party backends stated here
https://github.com/jaraco/keyring?tab=readme-ov-file#third-party-backends
>In addition to the backends provided by the core keyring package for the most common and secure use cases, there are additional keyring backend implementations available for other use cases. Simply install them to make them available:
[keyrings.cryptfile](https://pypi.org/project/keyrings.cryptfile) - Encrypted text file storage.
[keyrings.alt](https://pypi.org/project/keyrings.alt) - "alternate", possibly-insecure backends, originally part of the core package, but available for opt-in.
[gsheet-keyring](https://pypi.org/project/gsheet-keyring) - a backend that stores secrets in a Google Sheet. For use with [ipython-secrets](https://pypi.org/project/ipython-secrets).
[bitwarden-keyring](https://pypi.org/project/bitwarden-keyring/) - a backend that stores secrets in the [BitWarden](https://bitwarden.com/) password manager.
[onepassword-keyring](https://pypi.org/project/onepassword-keyring/) - a backend that stores secrets in the [1Password](https://1password.com/) password manager.
[sagecipher](https://pypi.org/project/sagecipher) - an encryption backend which uses the ssh agent protocol's signature operation to derive the cipher key.
[keyrings.osx_keychain_keys](https://pypi.org/project/keyrings.osx-keychain-keys) - OSX keychain key-management, for private, public, and symmetric keys.
[keyring_pass.PasswordStoreBackend](https://github.com/nazarewk/keyring_pass)
Password Store (pass) backend for python's keyring
[keyring_jeepney](https://pypi.org/project/keyring_jeepney) - a pure Python backend using the secret service DBus API for desktop Linux (requires keyring<24).
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] AIP-81 Central API Communication Mechanism for CLI and Connection Command Integration [airflow]
Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #45300:
URL: https://github.com/apache/airflow/pull/45300#issuecomment-2715759512
> I think error handling needs some work -- returning an error feels wrong to me
Thanks for the review, Ash! I updated the code according to the comments.
I aimed to directly cascade API-related errors to the user since there are good messages on API for each exception to reduce the code repetition, however, there could be cases where behaviour should be different in API and CLI cases. So updated all exceptions to raise it and not return while letting the caller decide the behaviour.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org