ephraimbuddy commented on code in PR #74370: URL: https://github.com/apache/airflow/pull/74370#discussion_r4228180065
########## airflow-core/src/airflow/api_fastapi/execution_api/routes/jobs.py: ########## @@ -0,0 +1,295 @@ +# 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 typing import TYPE_CHECKING + +import svcs +from cadwyn import VersionedAPIRouter +from fastapi import HTTPException, Security, status +from sqlalchemy import insert, select, update +from sqlalchemy.exc import IntegrityError + +from airflow._shared.timezones import timezone +from airflow.api_fastapi.auth.tokens import JWTGenerator +from airflow.api_fastapi.common.db.common import SessionDep +from airflow.api_fastapi.core_api.openapi.exceptions import create_openapi_http_exception_doc +from airflow.api_fastapi.execution_api.dag_processor_tokens import ( + ExpiredDagProcessorToken, + generate_dag_parse_token, + generate_dag_processor_token, +) +from airflow.api_fastapi.execution_api.datamodels.job import ( + DagParseTokenBody, + DagParseTokenResponse, + JobCompleteBody, + JobHeartbeatResponse, + JobRegisterBody, + JobRegisterResponse, +) +from airflow.api_fastapi.execution_api.datamodels.token import DagProcessorSessionToken, DagProcessorToken +from airflow.api_fastapi.execution_api.deps import DepContainer +from airflow.api_fastapi.execution_api.security import ( + JOB_UNCHECKED_SCOPE, + CurrentDagProcessorSessionToken, + CurrentDagProcessorToken, + ExecutionAPIRoute, + require_auth, +) +from airflow.configuration import conf +from airflow.jobs.dag_processor_job_runner import DagProcessorJobRunner +from airflow.jobs.job import Job, JobState +from airflow.models.dagbundle import DagBundleModel +from airflow.models.team import JobTeam + +if TYPE_CHECKING: + from uuid import UUID + + from sqlalchemy.orm import Session + +router = VersionedAPIRouter(route_class=ExecutionAPIRoute) + +_JOB_NOT_FOUND = create_openapi_http_exception_doc( + [(status.HTTP_404_NOT_FOUND, "Job not found for this token")] +) + + +def _check_token_job(job_id: int, token: DagProcessorToken) -> None: + if job_id != token.claims.job_id: + raise HTTPException( + status.HTTP_404_NOT_FOUND, + detail={"reason": "not_found", "message": f"Job {job_id} not found for this token"}, + ) + + +def _get_registered_job(registration_id: UUID, *, session: Session) -> Job | None: + return session.scalar(select(Job).where(Job.registration_id == registration_id).with_for_update()) + + +def _build_registration_response( + job_id: int, bundle_names: list[str], token: DagProcessorSessionToken, services: svcs.Container +) -> JobRegisterResponse: + try: + credential = generate_dag_processor_token( + services.get(JWTGenerator), + session_id=token.id, + job_id=job_id, + bundle_names=bundle_names, + session_expiry=token.claims.exp, + ) + except ExpiredDagProcessorToken as error: + raise HTTPException(status.HTTP_403_FORBIDDEN, detail=str(error)) from error + return JobRegisterResponse(job_id=job_id, token=credential) + + +def _resume_registration( + job: Job, + body: JobRegisterBody, + bundle_names: list[str], + token: DagProcessorSessionToken, + services: svcs.Container, +) -> JobRegisterResponse: + """Return the Job an earlier registration created, with a fresh token, if that Job is still the session's.""" + if job.session_id != token.id or job.end_date is not None: + raise HTTPException( + status.HTTP_409_CONFLICT, + detail={ + "reason": "registration_retired", + "message": f"Registration {body.registration_id} has ended; a restarted processor uses a new one", + }, + ) + if (job.hostname, job.unixname, job.bundle_names) != (body.hostname, body.unixname, bundle_names): + raise HTTPException( + status.HTTP_409_CONFLICT, + detail={ + "reason": "registration_conflict", + "message": f"Registration {body.registration_id} was made with different details", + }, + ) + return _build_registration_response(job.id, bundle_names, token, services) + + [email protected]( + "", + status_code=status.HTTP_201_CREATED, + dependencies=[Security(require_auth, scopes=["token:dag_processor_session"])], + responses=create_openapi_http_exception_doc( + [ + ( + status.HTTP_403_FORBIDDEN, + "A requested bundle is not granted to the session, or its credential has expired", + ), + ( + status.HTTP_409_CONFLICT, + "The registration has ended, conflicts with an earlier one, or another process's Job is running", + ), + ] + ), +) +def register_job( + body: JobRegisterBody, + session: SessionDep, + token: DagProcessorSessionToken = CurrentDagProcessorSessionToken, + services: svcs.Container = DepContainer, +) -> JobRegisterResponse: + """ + Register the Job of a Dag processor session in exchange for its management credential. + + A registration creates one Job. Repeating it while that Job is open returns the Job with a fresh token; + once the Job completes or is replaced, the registration is refused for good. A new registration is + refused while the session's Job is alive, and otherwise ends and replaces it, which ends every token + issued for the replaced Job. + """ + requested = token.claims.dag_bundles if body.bundle_names is None else set(body.bundle_names) + if ungranted := requested - token.claims.dag_bundles: + raise HTTPException( + status.HTTP_403_FORBIDDEN, + detail={"reason": "bundle_not_granted", "message": f"Bundles not granted: {sorted(ungranted)}"}, + ) + bundle_names = sorted(requested) + + if registered := _get_registered_job(body.registration_id, session=session): + return _resume_registration(registered, body, bundle_names, token, services) + + now = timezone.utcnow() + previous = session.scalar(select(Job).where(Job.session_id == token.id).with_for_update()) + if previous is not None: + if previous.end_date is None and previous.is_alive(): + raise HTTPException( + status.HTTP_409_CONFLICT, + detail={"reason": "job_running", "message": f"Session already has running Job {previous.id}"}, + ) + if previous.end_date is None: + previous.state = JobState.FAILED + previous.end_date = now + previous.session_id = None + session.flush() + + try: + with session.begin_nested(): + # A core insert: Job.__init__ would stamp the API server's host and user and fire listeners. + session.execute( + insert(Job).values( + job_type=DagProcessorJobRunner.job_type, Review Comment: I’d keep `/jobs` as the shared lifecycle resource. Supporting another component could add a scope and request model while preserving the existing Dag processor contract. The column names reflect separate lifetimes: `session_id` identifies the provisioned session, and `registration_id` identifies one process start and makes its retries idempotent. My preference is to retain these names. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
