1*9903217aSDaniel P. Berrangé# Test utilities for fetching & caching assets
2*9903217aSDaniel P. Berrangé#
3*9903217aSDaniel P. Berrangé# Copyright 2024 Red Hat, Inc.
4*9903217aSDaniel P. Berrangé#
5*9903217aSDaniel P. Berrangé# This work is licensed under the terms of the GNU GPL, version 2 or
6*9903217aSDaniel P. Berrangé# later.  See the COPYING file in the top-level directory.
7*9903217aSDaniel P. Berrangé
8*9903217aSDaniel P. Berrangéimport hashlib
9*9903217aSDaniel P. Berrangéimport logging
10*9903217aSDaniel P. Berrangéimport os
11*9903217aSDaniel P. Berrangéimport subprocess
12*9903217aSDaniel P. Berrangéimport urllib.request
13*9903217aSDaniel P. Berrangéfrom pathlib import Path
14*9903217aSDaniel P. Berrangéfrom shutil import copyfileobj
15*9903217aSDaniel P. Berrangé
16*9903217aSDaniel P. Berrangé
17*9903217aSDaniel P. Berrangé# Instances of this class must be declared as class level variables
18*9903217aSDaniel P. Berrangé# starting with a name "ASSET_". This enables the pre-caching logic
19*9903217aSDaniel P. Berrangé# to easily find all referenced assets and download them prior to
20*9903217aSDaniel P. Berrangé# execution of the tests.
21*9903217aSDaniel P. Berrangéclass Asset:
22*9903217aSDaniel P. Berrangé
23*9903217aSDaniel P. Berrangé    def __init__(self, url, hashsum):
24*9903217aSDaniel P. Berrangé        self.url = url
25*9903217aSDaniel P. Berrangé        self.hash = hashsum
26*9903217aSDaniel P. Berrangé        cache_dir_env = os.getenv('QEMU_TEST_CACHE_DIR')
27*9903217aSDaniel P. Berrangé        if cache_dir_env:
28*9903217aSDaniel P. Berrangé            self.cache_dir = Path(cache_dir_env, "download")
29*9903217aSDaniel P. Berrangé        else:
30*9903217aSDaniel P. Berrangé            self.cache_dir = Path(Path("~").expanduser(),
31*9903217aSDaniel P. Berrangé                                  ".cache", "qemu", "download")
32*9903217aSDaniel P. Berrangé        self.cache_file = Path(self.cache_dir, hashsum)
33*9903217aSDaniel P. Berrangé        self.log = logging.getLogger('qemu-test')
34*9903217aSDaniel P. Berrangé
35*9903217aSDaniel P. Berrangé    def __repr__(self):
36*9903217aSDaniel P. Berrangé        return "Asset: url=%s hash=%s cache=%s" % (
37*9903217aSDaniel P. Berrangé            self.url, self.hash, self.cache_file)
38*9903217aSDaniel P. Berrangé
39*9903217aSDaniel P. Berrangé    def _check(self, cache_file):
40*9903217aSDaniel P. Berrangé        if self.hash is None:
41*9903217aSDaniel P. Berrangé            return True
42*9903217aSDaniel P. Berrangé        if len(self.hash) == 64:
43*9903217aSDaniel P. Berrangé            sum_prog = 'sha256sum'
44*9903217aSDaniel P. Berrangé        elif len(self.hash) == 128:
45*9903217aSDaniel P. Berrangé            sum_prog = 'sha512sum'
46*9903217aSDaniel P. Berrangé        else:
47*9903217aSDaniel P. Berrangé            raise Exception("unknown hash type")
48*9903217aSDaniel P. Berrangé
49*9903217aSDaniel P. Berrangé        checksum = subprocess.check_output(
50*9903217aSDaniel P. Berrangé            [sum_prog, str(cache_file)]).split()[0]
51*9903217aSDaniel P. Berrangé        return self.hash == checksum.decode("utf-8")
52*9903217aSDaniel P. Berrangé
53*9903217aSDaniel P. Berrangé    def valid(self):
54*9903217aSDaniel P. Berrangé        return self.cache_file.exists() and self._check(self.cache_file)
55*9903217aSDaniel P. Berrangé
56*9903217aSDaniel P. Berrangé    def fetch(self):
57*9903217aSDaniel P. Berrangé        if not self.cache_dir.exists():
58*9903217aSDaniel P. Berrangé            self.cache_dir.mkdir(parents=True, exist_ok=True)
59*9903217aSDaniel P. Berrangé
60*9903217aSDaniel P. Berrangé        if self.valid():
61*9903217aSDaniel P. Berrangé            self.log.debug("Using cached asset %s for %s",
62*9903217aSDaniel P. Berrangé                           self.cache_file, self.url)
63*9903217aSDaniel P. Berrangé            return str(self.cache_file)
64*9903217aSDaniel P. Berrangé
65*9903217aSDaniel P. Berrangé        self.log.info("Downloading %s to %s...", self.url, self.cache_file)
66*9903217aSDaniel P. Berrangé        tmp_cache_file = self.cache_file.with_suffix(".download")
67*9903217aSDaniel P. Berrangé
68*9903217aSDaniel P. Berrangé        try:
69*9903217aSDaniel P. Berrangé            resp = urllib.request.urlopen(self.url)
70*9903217aSDaniel P. Berrangé        except Exception as e:
71*9903217aSDaniel P. Berrangé            self.log.error("Unable to download %s: %s", self.url, e)
72*9903217aSDaniel P. Berrangé            raise
73*9903217aSDaniel P. Berrangé
74*9903217aSDaniel P. Berrangé        try:
75*9903217aSDaniel P. Berrangé            with tmp_cache_file.open("wb+") as dst:
76*9903217aSDaniel P. Berrangé                copyfileobj(resp, dst)
77*9903217aSDaniel P. Berrangé        except:
78*9903217aSDaniel P. Berrangé            tmp_cache_file.unlink()
79*9903217aSDaniel P. Berrangé            raise
80*9903217aSDaniel P. Berrangé        try:
81*9903217aSDaniel P. Berrangé            # Set these just for informational purposes
82*9903217aSDaniel P. Berrangé            os.setxattr(str(tmp_cache_file), "user.qemu-asset-url",
83*9903217aSDaniel P. Berrangé                        self.url.encode('utf8'))
84*9903217aSDaniel P. Berrangé            os.setxattr(str(tmp_cache_file), "user.qemu-asset-hash",
85*9903217aSDaniel P. Berrangé                        self.hash.encode('utf8'))
86*9903217aSDaniel P. Berrangé        except Exception as e:
87*9903217aSDaniel P. Berrangé            self.log.debug("Unable to set xattr on %s: %s", tmp_cache_file, e)
88*9903217aSDaniel P. Berrangé            pass
89*9903217aSDaniel P. Berrangé
90*9903217aSDaniel P. Berrangé        if not self._check(tmp_cache_file):
91*9903217aSDaniel P. Berrangé            tmp_cache_file.unlink()
92*9903217aSDaniel P. Berrangé            raise Exception("Hash of %s does not match %s" %
93*9903217aSDaniel P. Berrangé                            (self.url, self.hash))
94*9903217aSDaniel P. Berrangé        tmp_cache_file.replace(self.cache_file)
95*9903217aSDaniel P. Berrangé
96*9903217aSDaniel P. Berrangé        self.log.info("Cached %s at %s" % (self.url, self.cache_file))
97*9903217aSDaniel P. Berrangé        return str(self.cache_file)
98