1
0
Fork 0
mirror of https://github.com/yavook/kiwi-scp.git synced 2024-11-22 21:03:00 +00:00
kiwi-scp/kiwi_scp/commands/cmd_shell.py

74 lines
2.2 KiB
Python
Raw Normal View History

2021-12-02 17:58:08 +00:00
import logging
from typing import List, Optional
import click
from .cmd import KiwiCommandType, KiwiCommand
from .decorators import kiwi_command
from ..executable import COMPOSE_EXE
from ..instance import Instance
from ..project import Project
from ..services import Services
_logger = logging.getLogger(__name__)
@click.option(
"-s", "--shell",
help="shell to spawn",
type=str,
)
@click.option(
"-u", "--user",
help="container user to run shell",
type=str,
)
@kiwi_command(
short_help="Spawn shell",
)
class ShellCommand(KiwiCommand):
"""Spawn shell inside a project's service"""
type = KiwiCommandType.SERVICES
enabled_only = True
@classmethod
def run_for_filtered_services(cls, instance: Instance, project: Project, services: Services,
new_service_names: List[str], shell: Optional[str] = None,
user: Optional[str] = None) -> None:
2021-12-03 13:43:03 +00:00
# shells from KiwiConfig
shells = [
*(str(path) for path in instance.config.shells),
2022-01-27 16:57:35 +00:00
# as a last resort, fall back to "/bin/sh" and "sh"
2021-12-03 13:43:03 +00:00
"/bin/sh", "sh",
]
2021-12-02 17:58:08 +00:00
# add shell from argument
if shell is not None:
2021-12-03 13:43:03 +00:00
shells.insert(0, shell)
2021-12-02 17:58:08 +00:00
user_args = ["-u", user] if user is not None else []
for service in services.content:
try:
2021-12-03 13:43:03 +00:00
use_shell = next(service.existing_executables(shells))
2021-12-02 17:58:08 +00:00
_logger.debug(f"Using shell {use_shell!r}")
except StopIteration:
if shell is not None:
use_shell = shell
_logger.warning(
2021-12-02 18:04:37 +00:00
"Could not find a working shell in this container. "
f"Launching provided shell {use_shell!r} nevertheless. This might fail!"
2021-12-02 17:58:08 +00:00
)
else:
_logger.warning(
f"Could not find any working shell among {shells!r} in this container. "
"Please suggest a shell using the '-s SHELL' command line option!"
)
2021-12-02 18:04:37 +00:00
continue
2021-12-02 17:58:08 +00:00
# spawn shell
COMPOSE_EXE.run(['exec', *user_args, service.name, use_shell], **project.process_kwargs)