-
Notifications
You must be signed in to change notification settings - Fork 17.3k
AIP-84: Migrate get_log endpoint #44238
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
8fb5f5b
Migrate log endpoint
utkarsharma2 6996c71
Remove debug commit
utkarsharma2 e74af39
Merge branch 'main' into migrate_log_endpoint
utkarsharma2 7dcc42f
Update tests/api_fastapi/core_api/routes/public/test_task_instances.py
utkarsharma2 fdbc27d
Update tests/api_fastapi/core_api/routes/public/test_task_instances.py
utkarsharma2 c158b20
Update airflow/api_fastapi/core_api/datamodels/task_instances.py
utkarsharma2 d0813ca
Update tests/api_fastapi/core_api/routes/public/test_task_instances.py
utkarsharma2 2732061
Remove code comments
utkarsharma2 c3d4a22
Address PR comments
utkarsharma2 613db85
Remove unwanted code
utkarsharma2 2a1715a
Address PR comments
utkarsharma2 b0b2dc9
Update airflow/api_fastapi/core_api/routes/public/log.py
utkarsharma2 c374d76
Update airflow/api_fastapi/core_api/datamodels/log.py
utkarsharma2 b65270d
Fix static check
utkarsharma2 320b022
Address PR comments
utkarsharma2 f9bdf6e
Address PR comments
utkarsharma2 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| # 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 | ||
|
|
||
| from pydantic import BaseModel | ||
|
|
||
|
|
||
| class TaskInstancesLogResponse(BaseModel): | ||
| """Log serializer for responses.""" | ||
|
|
||
| content: str | ||
| continuation_token: str | None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| # 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 textwrap | ||
| from typing import Annotated, Any | ||
|
|
||
| from fastapi import Depends, HTTPException, Request, Response, status | ||
| from itsdangerous import BadSignature, URLSafeSerializer | ||
| from pydantic import PositiveInt | ||
| from sqlalchemy.orm import Session, joinedload | ||
| from sqlalchemy.sql import select | ||
|
|
||
| from airflow.api_fastapi.common.db.common import get_session | ||
| from airflow.api_fastapi.common.headers import HeaderAcceptJsonOrText | ||
| from airflow.api_fastapi.common.router import AirflowRouter | ||
| from airflow.api_fastapi.common.types import Mimetype | ||
| from airflow.api_fastapi.core_api.datamodels.log import TaskInstancesLogResponse | ||
| from airflow.api_fastapi.core_api.openapi.exceptions import create_openapi_http_exception_doc | ||
| from airflow.exceptions import TaskNotFound | ||
| from airflow.models import TaskInstance, Trigger | ||
| from airflow.models.taskinstancehistory import TaskInstanceHistory | ||
| from airflow.utils.log.log_reader import TaskLogReader | ||
|
|
||
| task_instances_log_router = AirflowRouter( | ||
| tags=["Task Instance"], prefix="/dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances" | ||
| ) | ||
|
|
||
| text_example_response_for_get_log = { | ||
| Mimetype.TEXT: { | ||
| "schema": { | ||
| "type": "string", | ||
| "example": textwrap.dedent( | ||
| """\ | ||
| content | ||
| """ | ||
| ), | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| @task_instances_log_router.get( | ||
| "/{task_id}/logs/{try_number}", | ||
| responses={ | ||
| **create_openapi_http_exception_doc([status.HTTP_404_NOT_FOUND]), | ||
| status.HTTP_200_OK: { | ||
| "description": "Successful Response", | ||
| "content": text_example_response_for_get_log, | ||
| }, | ||
| }, | ||
| response_model=TaskInstancesLogResponse, | ||
| ) | ||
| def get_log( | ||
| dag_id: str, | ||
| dag_run_id: str, | ||
| task_id: str, | ||
| try_number: PositiveInt, | ||
| accept: HeaderAcceptJsonOrText, | ||
| request: Request, | ||
| session: Annotated[Session, Depends(get_session)], | ||
| full_content: bool = False, | ||
| map_index: int = -1, | ||
| token: str | None = None, | ||
| ): | ||
| """Get logs for a specific task instance.""" | ||
| if not token: | ||
| metadata = {} | ||
| else: | ||
| try: | ||
| metadata = URLSafeSerializer(request.app.state.secret_key).loads(token) | ||
| except BadSignature: | ||
| raise HTTPException( | ||
| status.HTTP_400_BAD_REQUEST, "Bad Signature. Please use only the tokens provided by the API." | ||
|
pierrejeambrun marked this conversation as resolved.
|
||
| ) | ||
|
|
||
| if metadata.get("download_logs") and metadata["download_logs"]: | ||
| full_content = True | ||
|
|
||
| if full_content: | ||
| metadata["download_logs"] = True | ||
| else: | ||
| metadata["download_logs"] = False | ||
|
pierrejeambrun marked this conversation as resolved.
|
||
|
|
||
| task_log_reader = TaskLogReader() | ||
|
|
||
| if not task_log_reader.supports_read: | ||
| raise HTTPException(status.HTTP_400_BAD_REQUEST, "Task log handler does not support read logs.") | ||
|
|
||
| query = ( | ||
| select(TaskInstance) | ||
| .where( | ||
| TaskInstance.task_id == task_id, | ||
| TaskInstance.dag_id == dag_id, | ||
| TaskInstance.run_id == dag_run_id, | ||
| TaskInstance.map_index == map_index, | ||
| ) | ||
| .join(TaskInstance.dag_run) | ||
| .options(joinedload(TaskInstance.trigger).joinedload(Trigger.triggerer_job)) | ||
| ) | ||
| ti = session.scalar(query) | ||
| if ti is None: | ||
| query = select(TaskInstanceHistory).where( | ||
| TaskInstanceHistory.task_id == task_id, | ||
| TaskInstanceHistory.dag_id == dag_id, | ||
| TaskInstanceHistory.run_id == dag_run_id, | ||
| TaskInstanceHistory.map_index == map_index, | ||
| TaskInstanceHistory.try_number == try_number, | ||
| ) | ||
| ti = session.scalar(query) | ||
|
|
||
| if ti is None: | ||
| metadata["end_of_log"] = True | ||
| raise HTTPException(status.HTTP_404_NOT_FOUND, "TaskInstance not found") | ||
|
|
||
| dag = request.app.state.dag_bag.get_dag(dag_id) | ||
| if dag: | ||
| try: | ||
| ti.task = dag.get_task(ti.task_id) | ||
| except TaskNotFound: | ||
| pass | ||
|
|
||
| logs: Any | ||
| if accept == Mimetype.JSON or accept == Mimetype.ANY: # default | ||
| logs, metadata = task_log_reader.read_log_chunks(ti, try_number, metadata) | ||
| # we must have token here, so we can safely ignore it | ||
| token = URLSafeSerializer(request.app.state.secret_key).dumps(metadata) # type: ignore[assignment] | ||
| return TaskInstancesLogResponse(continuation_token=token, content=str(logs[0])).model_dump() | ||
| # text/plain. Stream | ||
| logs = task_log_reader.read_log_stream(ti, try_number, metadata) | ||
| return Response(media_type=accept, content="".join(list(logs))) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.