Skip to content

Commit

Permalink
vmtest.githubapi: add environment variable for trusting cache
Browse files Browse the repository at this point in the history
Specifying a vmtest kernel version that isn't an exact match (e.g., with
a wildcard) currently always makes a GitHub API request to get the
vmtest release list. This is annoying if you have no or slow network
connectivity and don't want to check what the exact version is
(especially if you just downloaded it). Add a hack to bypass this
request by setting VMTEST_TRUST_CACHE=1 in the environment.

Signed-off-by: Omar Sandoval <[email protected]>
  • Loading branch information
osandov committed Sep 27, 2024
1 parent 608fbdd commit 2150a90
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions vmtest/githubapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# SPDX-License-Identifier: LGPL-2.1-or-later

import json
import os
from pathlib import Path
import typing
from typing import Any, Dict, Mapping, Optional, Union
Expand Down Expand Up @@ -68,6 +69,15 @@ def _cached_get_headers(
return {**self._headers, "If-Modified-Since": cached["last_modified"]}
return self._headers

@staticmethod
def _trust_cache(cached: Any) -> bool:
# If the request was cached and the VMTEST_TRUST_CACHE environment
# variable is non-zero, assume the cache is still valid.
try:
return cached is not None and int(os.getenv("VMTEST_TRUST_CACHE", "0")) != 0
except ValueError:
return False

def _write_cache(
self, cache: _CACHE, body: Any, headers: Mapping[str, str]
) -> None:
Expand Down Expand Up @@ -122,6 +132,8 @@ def _request(

def _cached_get_json(self, endpoint: str, cache: _CACHE) -> Any:
cached = self._read_cache(cache)
if self._trust_cache(cached):
return cached["body"]
try:
with urllib.request.urlopen(
urllib.request.Request(
Expand Down Expand Up @@ -164,6 +176,8 @@ def _request(

async def _cached_get_json(self, endpoint: str, cache: _CACHE) -> Any:
cached = self._read_cache(cache)
if self._trust_cache(cached):
return cached["body"]
async with self._session.get(
self._HOST + "/" + endpoint,
headers=self._cached_get_headers(cached),
Expand Down

0 comments on commit 2150a90

Please sign in to comment.