asset.py 3.2 KB

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