1
0
Fork 0
mirror of https://github.com/yavook/kiwi-scp.git synced 2024-11-25 14:03:00 +00:00
kiwi-scp/kiwi_scp/rootkit.py

79 lines
2.5 KiB
Python
Raw Normal View History

2021-11-04 20:59:17 +00:00
import functools
import logging
import subprocess
2021-11-04 20:59:17 +00:00
from pathlib import Path
from typing import Optional, TypeVar, Union, List
import attr
2020-08-19 15:15:00 +00:00
from ._constants import IMAGES_DIRECTORY_NAME, LOCAL_IMAGES_NAME, DEFAULT_IMAGE_NAME
2021-11-13 02:26:32 +00:00
from .executable import DOCKER_EXE
2021-11-04 20:59:17 +00:00
_logger = logging.getLogger(__name__)
2021-11-04 20:59:17 +00:00
PSL = TypeVar("PSL", Union[Path, str], List[Union[Path, str]])
2021-11-04 20:59:17 +00:00
def prefix_path(path: PSL, prefix: Path = Path("/mnt")) -> PSL:
if isinstance(path, Path):
return prefix.joinpath(path.absolute())
2021-11-04 20:59:17 +00:00
if isinstance(path, str):
return prefix_path(Path(path), prefix)
2021-11-04 20:59:17 +00:00
elif isinstance(path, list):
return [prefix_path(prefix, p) for p in path]
2021-11-04 20:59:17 +00:00
@attr.s
class Rootkit:
2021-11-04 20:59:17 +00:00
image_tag: str = attr.ib()
@staticmethod
@functools.lru_cache(maxsize=None)
def __image_name(image_tag: Optional[str]) -> str:
if image_tag is not None:
return f"{LOCAL_IMAGES_NAME}:{image_tag}"
else:
return DEFAULT_IMAGE_NAME
@staticmethod
@functools.lru_cache(maxsize=None)
def __exists(image_tag: str) -> bool:
2021-11-13 02:26:32 +00:00
ps = DOCKER_EXE.run([
2021-11-04 20:59:17 +00:00
'images',
'--filter', f"reference={Rootkit.__image_name(image_tag)}",
'--format', '{{.Repository}}:{{.Tag}}'
], stdout=subprocess.PIPE)
return str(ps.stdout, 'utf-8').strip() == Rootkit.__image_name(image_tag)
def __build_image(self) -> None:
if Rootkit.__exists(self.image_tag):
_logger.info(f"Using image {Rootkit.__image_name(self.image_tag)}")
else:
if self.image_tag is None:
_logger.info(f"Pulling image {Rootkit.__image_name(self.image_tag)}")
2021-11-13 02:26:32 +00:00
DOCKER_EXE.run([
2021-11-04 20:59:17 +00:00
'pull', Rootkit.__image_name(self.image_tag)
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
2021-11-04 20:59:17 +00:00
_logger.info(f"Building image {Rootkit.__image_name(self.image_tag)}")
2021-11-13 02:26:32 +00:00
DOCKER_EXE.run([
2021-11-04 20:59:17 +00:00
'build',
'-t', Rootkit.__image_name(self.image_tag),
'-f', f"{IMAGES_DIRECTORY_NAME}/{self.image_tag}.Dockerfile",
f"{IMAGES_DIRECTORY_NAME}"
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def run(self, process_args, **kwargs):
self.__build_image()
2021-11-13 02:26:32 +00:00
DOCKER_EXE.run([
2021-11-04 20:59:17 +00:00
'run', '--rm',
'-v', '/:/mnt',
'-u', 'root',
Rootkit.__image_name(self.image_tag),
*process_args
], **kwargs)