task_instance_session.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from __future__ import annotations
  18. import contextlib
  19. import logging
  20. import traceback
  21. from typing import TYPE_CHECKING
  22. from airflow import settings
  23. from airflow.api_internal.internal_api_call import InternalApiConfig
  24. from airflow.settings import TracebackSession
  25. if TYPE_CHECKING:
  26. from sqlalchemy.orm import Session
  27. __current_task_instance_session: Session | None = None
  28. log = logging.getLogger(__name__)
  29. def get_current_task_instance_session() -> Session:
  30. global __current_task_instance_session
  31. if not __current_task_instance_session:
  32. if InternalApiConfig.get_use_internal_api():
  33. __current_task_instance_session = TracebackSession()
  34. return __current_task_instance_session
  35. log.warning("No task session set for this task. Continuing but this likely causes a resource leak.")
  36. log.warning("Please report this and stacktrace below to https://github.com/apache/airflow/issues")
  37. for filename, line_number, name, line in traceback.extract_stack():
  38. log.warning('File: "%s", %s , in %s', filename, line_number, name)
  39. if line:
  40. log.warning(" %s", line.strip())
  41. __current_task_instance_session = settings.Session()
  42. return __current_task_instance_session
  43. @contextlib.contextmanager
  44. def set_current_task_instance_session(session: Session):
  45. if InternalApiConfig.get_use_internal_api():
  46. yield
  47. return
  48. global __current_task_instance_session
  49. if __current_task_instance_session:
  50. raise RuntimeError(
  51. "Session already set for this task. "
  52. "You can only have one 'set_current_task_session' context manager active at a time."
  53. )
  54. __current_task_instance_session = session
  55. try:
  56. yield
  57. finally:
  58. __current_task_instance_session = None