1
0
Fork 0
mirror of https://github.com/yavook/kiwi-scp.git synced 2025-12-07 09:03:06 +00:00
kiwi-scp/src/kiwi/subcommands/utils/dockercommand.py

68 lines
2.1 KiB
Python
Raw Normal View History

2020-08-12 15:46:50 +00:00
# system
2020-08-13 09:34:30 +00:00
import logging
import subprocess
2020-08-12 15:46:50 +00:00
# local
from ..._constants import CONF_DIRECTORY_NAME
from .executable import Executable
2020-08-17 12:13:42 +00:00
from .project import *
2020-08-13 09:34:30 +00:00
def _update_kwargs(config, args, **kwargs):
2020-08-17 12:13:42 +00:00
# project given in args: command affects a project in this instance
project_name = get_project_name(args)
if project_name is not None:
# execute command in project directory
kwargs['cwd'] = get_project_dir(config, project_name)
2020-08-13 09:34:30 +00:00
2020-08-17 12:13:42 +00:00
# ensure there is an environment
2020-08-17 09:57:08 +00:00
if 'env' not in kwargs:
kwargs['env'] = {}
2020-08-13 09:34:30 +00:00
2020-08-17 12:13:42 +00:00
# create environment variables for docker commands
2020-08-17 09:57:08 +00:00
kwargs['env'].update({
'COMPOSE_PROJECT_NAME': project_name,
2020-08-17 12:13:42 +00:00
'KIWI_HUB_NAME': config['network:name'],
'CONFDIR': os.path.join(config['runtime:storage'], CONF_DIRECTORY_NAME),
2020-08-17 12:13:42 +00:00
'TARGETDIR': os.path.join(config['runtime:storage'], get_project_dir(config, project_name))
2020-08-17 09:57:08 +00:00
})
logging.debug(f"kwargs updated: {kwargs}")
2020-08-13 09:34:30 +00:00
return kwargs
2020-08-12 15:39:55 +00:00
class DockerCommand(Executable):
2020-08-17 14:58:12 +00:00
__has_tried = False
def __init__(self, exe_name):
2020-08-12 15:39:55 +00:00
super().__init__(exe_name)
2020-08-17 14:58:12 +00:00
if not DockerCommand.__has_tried:
try:
Executable('docker').run(
2020-08-12 15:39:55 +00:00
['ps'],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
2020-08-17 14:58:12 +00:00
DockerCommand.__has_tried = True
except subprocess.CalledProcessError:
2020-08-17 14:58:12 +00:00
raise PermissionError("Cannot access docker, please get into the docker group or run as root!")
2020-08-13 09:34:30 +00:00
def run(self, config, args, process_args, **kwargs):
kwargs = _update_kwargs(config, args, **kwargs)
2020-08-12 15:39:55 +00:00
# equivalent to 'super().run' but agnostic of nested class construct
2020-08-17 09:57:08 +00:00
return super().__getattr__("run")(
2020-08-17 14:58:12 +00:00
process_args, config,
2020-08-12 15:39:55 +00:00
**kwargs
)
2020-08-13 09:34:30 +00:00
def run_less(self, config, args, process_args, **kwargs):
kwargs = _update_kwargs(config, args, **kwargs)
2020-08-17 09:57:08 +00:00
return super().__getattr__("run_less")(
2020-08-17 14:58:12 +00:00
process_args, config,
2020-08-13 09:34:30 +00:00
**kwargs
)