From 7aa199afc08420380683a64901957dd9f0d1d3cd Mon Sep 17 00:00:00 2001 From: Rob Berwick Date: Sat, 27 Jul 2024 20:05:41 +0100 Subject: [PATCH] Add docker based grype backend --- pygrype/__init__.py | 1 + pygrype/core/backends/docker.py | 50 +++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 pygrype/core/backends/docker.py diff --git a/pygrype/__init__.py b/pygrype/__init__.py index ae61536..b69333a 100644 --- a/pygrype/__init__.py +++ b/pygrype/__init__.py @@ -1,3 +1,4 @@ from .grype import Grype from .core.backends.binary import GrypeBinaryBackend +from .core.backends.docker import GrypeDockerBackend diff --git a/pygrype/core/backends/docker.py b/pygrype/core/backends/docker.py new file mode 100644 index 0000000..d1e977f --- /dev/null +++ b/pygrype/core/backends/docker.py @@ -0,0 +1,50 @@ +import subprocess +from subprocess import CompletedProcess + +from pygrype.core.backends.base import GrypeBackend + + +DOCKER_EXE = 'docker' +IMAGE_NAME = 'anchore/grype' + + +class GrypeDockerBackend(GrypeBackend): + + def __init__(self, tag: str = "latest") -> None: + self.tag: str = tag + super().__init__() + + @property + def docker_image(self) -> str: + return f"{IMAGE_NAME}:{self.tag}" + + def ensure_backend(self): + try: + # Check if Docker is installed + subprocess.run( + [DOCKER_EXE, '--version'], + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE + ) + except subprocess.CalledProcessError: + raise Exception("Docker is not installed or not available in the PATH.") + + try: + # Ensure the required Docker image is available + subprocess.run( + [DOCKER_EXE, 'pull', self.docker_image], + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE + ) + except subprocess.CalledProcessError: + raise Exception(f"Failed to pull the required Docker image '{self.docker_image}'.") + + @property + def executable_string(self) -> str: + return DOCKER_EXE + + def execute(self, *args) -> CompletedProcess: + docker_args = ['run', '--rm', self.docker_image] + list(args) + return super().execute(*docker_args)