-
Notifications
You must be signed in to change notification settings - Fork 16.5k
Add a cache to Variable and Connection when called at dag parsing time
#30259
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
Changes from all commits
c09b83d
215ce99
a9fdb7a
0e99bb0
5f69849
2b5a178
416cda9
643d1d9
37c59e8
a66142b
e3a0eb9
cae3818
717567c
041bd80
2807825
8b6ed39
65e9aab
3340e32
2db7bd1
b0d9d34
27ca59c
8dc1812
83eea27
1f1e586
13b4041
ff89eb2
3b8d178
cba8b8d
c7ee505
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -1090,6 +1090,31 @@ secrets: | |||||||||
| sensitive: true | ||||||||||
| example: ~ | ||||||||||
| default: "" | ||||||||||
| use_cache: | ||||||||||
| description: | | ||||||||||
| .. note:: |experimental| | ||||||||||
|
|
||||||||||
| Enables local caching of Variables, when parsing DAGs only. | ||||||||||
| Using this option can make dag parsing faster if Variables are used in top level code, at the expense | ||||||||||
| of longer propagation time for changes. | ||||||||||
| Please note that this cache concerns only the DAG parsing step. There is no caching in place when DAG | ||||||||||
| tasks are run. | ||||||||||
| version_added: 2.6.0 | ||||||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| type: boolean | ||||||||||
| example: ~ | ||||||||||
| default: "False" | ||||||||||
| cache_ttl_seconds: | ||||||||||
| description: | | ||||||||||
| .. note:: |experimental| | ||||||||||
|
|
||||||||||
| When the cache is enabled, this is the duration for which we consider an entry in the cache to be | ||||||||||
| valid. Entries are refreshed if they are older than this many seconds. | ||||||||||
| It means that when the cache is enabled, this is the maximum amount of time you need to wait to see a | ||||||||||
| Variable change take effect. | ||||||||||
| version_added: 2.6.0 | ||||||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
| type: integer | ||||||||||
| example: ~ | ||||||||||
| default: "900" | ||||||||||
| cli: | ||||||||||
| description: ~ | ||||||||||
| options: | ||||||||||
|
|
||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| # | ||
| # 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 multiprocessing | ||
|
|
||
| from airflow.configuration import conf | ||
|
|
||
|
|
||
| class SecretCache: | ||
| """A static class to manage the global secret cache.""" | ||
|
|
||
| __manager: multiprocessing.managers.SyncManager | None = None | ||
| _cache: dict[str, _CacheValue] | None = None | ||
| _ttl: datetime.timedelta | ||
|
|
||
| class NotPresentException(Exception): | ||
| """Raised when a key is not present in the cache.""" | ||
|
|
||
| class _CacheValue: | ||
| def __init__(self, value: str | None) -> None: | ||
| self.value = value | ||
| self.date = datetime.datetime.utcnow() | ||
|
|
||
| def is_expired(self, ttl: datetime.timedelta) -> bool: | ||
| return datetime.datetime.utcnow() - self.date > ttl | ||
|
|
||
| _VARIABLE_PREFIX = "__v_" | ||
| _CONNECTION_PREFIX = "__c_" | ||
|
|
||
| @classmethod | ||
| def init(cls): | ||
| """Initializes the cache, provided the configuration allows it. Safe to call several times.""" | ||
| if cls._cache is not None: | ||
| return | ||
| use_cache = conf.getboolean(section="secrets", key="use_cache", fallback=False) | ||
| if not use_cache: | ||
| return | ||
| if cls.__manager is None: | ||
| # it is not really necessary to save the manager, but doing so allows to reuse it between tests, | ||
| # making them run a lot faster because this operation takes ~300ms each time | ||
| cls.__manager = multiprocessing.Manager() | ||
| cls._cache = cls.__manager.dict() | ||
| ttl_seconds = conf.getint(section="secrets", key="cache_ttl_seconds", fallback=15 * 60) | ||
| cls._ttl = datetime.timedelta(seconds=ttl_seconds) | ||
|
|
||
| @classmethod | ||
| def reset(cls): | ||
| """For test purposes only.""" | ||
| cls._cache = None | ||
|
|
||
| @classmethod | ||
| def get_variable(cls, key: str) -> str | None: | ||
| """ | ||
| Tries to get the value associated with the key from the cache. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: some parameters are missing from the docstring
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I can add it, but it'd look like |
||
|
|
||
| :return: The saved value (which can be None) if present in cache and not expired, | ||
| a NotPresent exception otherwise. | ||
| """ | ||
| return cls._get(key, cls._VARIABLE_PREFIX) | ||
|
|
||
| @classmethod | ||
| def get_connection_uri(cls, conn_id: str) -> str: | ||
| """ | ||
| Tries to get the uri associated with the conn_id from the cache. | ||
|
|
||
| :return: The saved uri if present in cache and not expired, | ||
| a NotPresent exception otherwise. | ||
| """ | ||
| val = cls._get(conn_id, cls._CONNECTION_PREFIX) | ||
| if val: # there shouldn't be any empty entries in the connections cache, but we enforce it here. | ||
| return val | ||
| raise cls.NotPresentException | ||
|
|
||
| @classmethod | ||
| def _get(cls, key: str, prefix: str) -> str | None: | ||
| if cls._cache is None: | ||
| # using an exception for misses allow to meaningfully cache None values | ||
| raise cls.NotPresentException | ||
|
|
||
| val = cls._cache.get(f"{prefix}{key}") | ||
| if val and not val.is_expired(cls._ttl): | ||
| return val.value | ||
| raise cls.NotPresentException | ||
|
|
||
| @classmethod | ||
| def save_variable(cls, key: str, value: str | None): | ||
| """Saves the value for that key in the cache, if initialized.""" | ||
| cls._save(key, value, cls._VARIABLE_PREFIX) | ||
|
|
||
| @classmethod | ||
| def save_connection_uri(cls, conn_id: str, uri: str): | ||
| """Saves the uri representation for that connection in the cache, if initialized.""" | ||
| if uri is None: | ||
| # connections raise exceptions if not present, so we shouldn't have any None value to save. | ||
| return | ||
| cls._save(conn_id, uri, cls._CONNECTION_PREFIX) | ||
|
|
||
| @classmethod | ||
| def _save(cls, key: str, value: str | None, prefix: str): | ||
| if cls._cache is not None: | ||
| cls._cache[f"{prefix}{key}"] = cls._CacheValue(value) | ||
|
|
||
| @classmethod | ||
| def invalidate_variable(cls, key: str): | ||
| """Invalidates (actually removes) the value stored in the cache for that Variable.""" | ||
| if cls._cache is not None: | ||
| # second arg ensures no exception if key is absent | ||
| cls._cache.pop(f"{cls._VARIABLE_PREFIX}{key}", None) | ||
Uh oh!
There was an error while loading. Please reload this page.