Unverified Commit 7de07fde authored by schnee's avatar schnee Committed by GitHub
Browse files

Merge pull request #1320 from dellkeji/add_cache_validate

feat: invalidate cluster context cache
parents 150ea3e9 6abbcedf
Showing with 17 additions and 5 deletions
+17 -5
......@@ -12,6 +12,7 @@ Unless required by applicable law or agreed to in writing, software distributed
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.
"""
import logging
from typing import Dict
from cachetools import LRUCache, cached
......@@ -23,9 +24,14 @@ from kubernetes import client
from backend.components.bcs import BCSClientBase, resources
from backend.components.utils import http_get
logger = logging.getLogger(__name__)
# 获取cluster context使用的缓存策略
cluster_context_cache_policy = LRUCache(maxsize=128)
@cached(
cache=LRUCache(maxsize=128),
cache=cluster_context_cache_policy,
key=lambda url_prefix, access_token, project_id, cluster_id: hashkey(url_prefix, project_id, cluster_id),
)
def make_cluster_context(url_prefix: str, access_token: str, project_id: str, cluster_id: str) -> Dict:
......@@ -55,12 +61,18 @@ class K8SAPIClient(BCSClientBase):
@cached_property
def api_client(self):
context = make_cluster_context(self.rest_host, self.access_token, self.project_id, self.cluster_id)
configure = client.Configuration()
configure.verify_ssl = False
configure.host = f"{self._bcs_server_host}{context['server_address_path']}".rstrip("/")
configure.api_key = {"authorization": f"Bearer {context['user_token']}"}
# 获取集群context,如果调用接口或者其它异常导致失败,需要主动使缓存失效
try:
context = make_cluster_context(self.rest_host, self.access_token, self.project_id, self.cluster_id)
configure.host = f"{self._bcs_server_host}{context['server_address_path']}".rstrip("/")
configure.api_key = {"authorization": f"Bearer {context['user_token']}"}
except Exception as e:
logger.exception("make cluster context error, %s", e)
# 当出现异常时,需要清空缓存
cluster_context_cache_policy.clear()
raise
api_client = client.ApiClient(configure)
return api_client
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment