CLI commands cleanup

This commit is contained in:
Jörn-Michael Miehe 2020-08-20 14:15:38 +02:00
parent 3a28af7f7e
commit 3ccdffe737
10 changed files with 175 additions and 173 deletions

View file

@ -1,27 +1,30 @@
COMMANDS COMMANDS
======== ========
init -> config # operation
show -> config --show
config
up up
down down
update update
clean
# management
new new
enable enable
disable disable
list -> show
logs
sh
cmd cmd
purge
# inspection
inspect
logs
shell
# imaging
build build
pull pull
push push
net-up
net-down
conf-copy (hide)
conf-purge (hide)
conf-clean -> clean

View file

@ -1,41 +1,42 @@
# local # local
from ._hidden import ConfCopyCommand, ConfPurgeCommand, NetUpCommand
from .build import BuildCommand from .build import BuildCommand
from .clean import CleanCommand
from .cmd import CmdCommand from .cmd import CmdCommand
from .conf import ConfCopyCommand, ConfPurgeCommand, ConfCleanCommand from .config import ConfigCommand
from .disable import DisableCommand from .disable import DisableCommand
from .down import DownCommand from .down import DownCommand
from .enable import EnableCommand from .enable import EnableCommand
from .init import InitCommand from .inspect import InspectCommand
from .list import ListCommand
from .logs import LogsCommand from .logs import LogsCommand
from .net import NetUpCommand, NetDownCommand
from .new import NewCommand from .new import NewCommand
from .pull import PullCommand from .pull import PullCommand
from .purge import PurgeCommand
from .push import PushCommand from .push import PushCommand
from .sh import ShCommand from .shell import ShellCommand
from .show import ShowCommand
from .up import UpCommand from .up import UpCommand
from .update import UpdateCommand from .update import UpdateCommand
__all__ = [ __all__ = [
'BuildCommand',
'CmdCommand',
'ConfCopyCommand', 'ConfCopyCommand',
'ConfPurgeCommand', 'ConfPurgeCommand',
'ConfCleanCommand', 'NetUpCommand',
'BuildCommand',
'CleanCommand',
'CmdCommand',
'ConfigCommand',
'DisableCommand', 'DisableCommand',
'DownCommand', 'DownCommand',
'EnableCommand', 'EnableCommand',
'InitCommand', 'InspectCommand',
'ListCommand',
'LogsCommand', 'LogsCommand',
'NetUpCommand',
'NetDownCommand',
'NewCommand', 'NewCommand',
'PullCommand', 'PullCommand',
'PurgeCommand',
'PushCommand', 'PushCommand',
'ShCommand', 'ShellCommand',
'ShowCommand',
'UpCommand', 'UpCommand',
'UpdateCommand', 'UpdateCommand',
] ]

View file

@ -4,6 +4,7 @@ import subprocess
# local # local
from .._constants import CONF_DIRECTORY_NAME from .._constants import CONF_DIRECTORY_NAME
from ..executable import Executable
from ..subcommand import SubCommand from ..subcommand import SubCommand
from ..config import LoadedConfig from ..config import LoadedConfig
from ..projects import Projects from ..projects import Projects
@ -16,7 +17,7 @@ class ConfCopyCommand(SubCommand):
def __init__(self): def __init__(self):
super().__init__( super().__init__(
'conf-copy', 'conf-copy',
action="Syncing all configs for", action="Syncing all configs for", add_parser=False,
description="Synchronize all config files to target directory" description="Synchronize all config files to target directory"
) )
@ -44,7 +45,7 @@ class ConfPurgeCommand(SubCommand):
def __init__(self): def __init__(self):
super().__init__( super().__init__(
'conf-purge', 'conf-purge',
action="Removing all configs for", action="Removing all configs for", add_parser=False,
description="Remove all config files in target directory" description="Remove all config files in target directory"
) )
@ -59,36 +60,47 @@ class ConfPurgeCommand(SubCommand):
return True return True
class ConfCleanCommand(SubCommand): def _find_net(net_name):
"""kiwi conf-clean""" ps = Executable('docker').run([
'network', 'ls', '--filter', f"name={net_name}", '--format', '{{.Name}}'
], stdout=subprocess.PIPE)
net_found = str(ps.stdout, 'utf-8').strip()
return net_found == net_name
class NetUpCommand(SubCommand):
"""kiwi net-up"""
def __init__(self): def __init__(self):
super().__init__( super().__init__(
'conf-clean', 'net-up',
action="Cleaning all configs for", action="Creating the local network hub for", add_parser=False,
description="Cleanly sync all configs to target folder, relaunch affected projects" description="Create the local network hub for this instance"
) )
def _run_instance(self, runner, args): def _run_instance(self, runner, args):
result = True config = LoadedConfig.get()
net_name = config['network:name']
net_cidr = config['network:cidr']
affected_projects = [ if _find_net(net_name):
project.get_name() logging.info(f"Network '{net_name}' already exists")
for project in Projects.from_dir() return True
if project.has_configs()
]
for project_name in affected_projects: try:
args.projects = project_name Executable('docker').run([
result &= runner.run('down') 'network', 'create',
'--driver', 'bridge',
'--internal',
'--subnet', net_cidr,
net_name
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
logging.info(f"Network '{net_name}' created")
# cleanly sync configs except subprocess.CalledProcessError:
result &= runner.run('conf-purge') logging.error(f"Error creating network '{net_name}'")
result &= runner.run('conf-copy') return False
# bring projects back up return True
for project_name in affected_projects:
args.projects = project_name
result &= runner.run('up')
return result

View file

@ -0,0 +1,37 @@
from ..projects import Projects
from ..subcommand import SubCommand
class CleanCommand(SubCommand):
"""kiwi clean"""
def __init__(self):
super().__init__(
'clean',
action="Cleaning all configs for",
description="Cleanly sync all configs to target folder, then relaunch affected projects"
)
def _run_instance(self, runner, args):
result = True
affected_projects = [
project.get_name()
for project in Projects.from_dir()
if project.has_configs()
]
for project_name in affected_projects:
args.projects = project_name
result &= runner.run('down')
# cleanly sync configs
result &= runner.run('conf-purge')
result &= runner.run('conf-copy')
# bring projects back up
for project_name in affected_projects:
args.projects = project_name
result &= runner.run('up')
return result

View file

@ -8,14 +8,14 @@ from ..subcommand import SubCommand
from ..config import DefaultConfig, LoadedConfig from ..config import DefaultConfig, LoadedConfig
class InitCommand(SubCommand): class ConfigCommand(SubCommand):
"""kiwi init""" """kiwi config"""
def __init__(self): def __init__(self):
super().__init__( super().__init__(
'init', 'config',
action=f"Initializing '{KIWI_CONF_NAME}' in", action=f"Configuring '{KIWI_CONF_NAME}' in",
description="Create a new kiwi-config instance" description="Configure kiwi-config instance"
) )
# -f switch: Initialize with default config # -f switch: Initialize with default config
@ -25,9 +25,21 @@ class InitCommand(SubCommand):
help=f"use default values even if {KIWI_CONF_NAME} is present" help=f"use default values even if {KIWI_CONF_NAME} is present"
) )
# -s switch: Show current config instead
self._sub_parser.add_argument(
'-s', '--show',
action='store_true',
help=f"show effective {KIWI_CONF_NAME} contents instead"
)
def _run_instance(self, runner, args): def _run_instance(self, runner, args):
config = LoadedConfig.get() config = LoadedConfig.get()
# check show switch
if args.show:
print(config)
return True
# check force switch # check force switch
if args.force and os.path.isfile(KIWI_CONF_NAME): if args.force and os.path.isfile(KIWI_CONF_NAME):

View file

@ -24,14 +24,14 @@ def _print_list(strings):
_print_list(list(strings)) _print_list(list(strings))
class ListCommand(ServiceCommand): class InspectCommand(ServiceCommand):
"""kiwi list""" """kiwi inspect"""
def __init__(self): def __init__(self):
super().__init__( super().__init__(
'list', num_projects='?', num_services='*', 'inspect', num_projects='?', num_services='*',
action="Listing", action="Inspecting",
description="List projects in this instance, services inside a project or service(s) inside a project" description="Inspect projects in this instance, services inside a project or service(s) inside a project"
) )
def _run_instance(self, runner, args): def _run_instance(self, runner, args):

View file

@ -1,90 +0,0 @@
# system
import logging
import subprocess
# local
from ..subcommand import SubCommand
from ..config import LoadedConfig
from ..executable import Executable
from ..misc import are_you_sure
def _find_net(net_name):
ps = Executable('docker').run([
'network', 'ls', '--filter', f"name={net_name}", '--format', '{{.Name}}'
], stdout=subprocess.PIPE)
net_found = str(ps.stdout, 'utf-8').strip()
return net_found == net_name
class NetUpCommand(SubCommand):
"""kiwi net-up"""
def __init__(self):
super().__init__(
'net-up',
action="Creating the local network hub for",
description="Create the local network hub for this instance"
)
def _run_instance(self, runner, args):
config = LoadedConfig.get()
net_name = config['network:name']
net_cidr = config['network:cidr']
if _find_net(net_name):
logging.info(f"Network '{net_name}' already exists")
return True
try:
Executable('docker').run([
'network', 'create',
'--driver', 'bridge',
'--internal',
'--subnet', net_cidr,
net_name
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
logging.info(f"Network '{net_name}' created")
except subprocess.CalledProcessError:
logging.error(f"Error creating network '{net_name}'")
return False
return True
class NetDownCommand(SubCommand):
"""kiwi net-down"""
def __init__(self):
super().__init__(
'net-down',
action="Removing the local network hub for",
description="Remove the local network hub for this instance"
)
def _run_instance(self, runner, args):
net_name = LoadedConfig.get()['network:name']
if not _find_net(net_name):
logging.info(f"Network '{net_name}' does not exist")
return True
try:
if are_you_sure("This will bring down this instance's hub network!"):
if runner.run('down'):
Executable('docker').run([
'network', 'rm', net_name
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
logging.info(f"Network '{net_name}' removed")
else:
return False
except subprocess.CalledProcessError:
logging.error(f"Error removing network '{net_name}'")
return False
return True

View file

@ -0,0 +1,45 @@
# system
import logging
import subprocess
# local
from ._hidden import _find_net
from ..subcommand import SubCommand
from ..config import LoadedConfig
from ..executable import Executable
from ..misc import are_you_sure
class PurgeCommand(SubCommand):
"""kiwi purge"""
def __init__(self):
super().__init__(
'purge',
action="Tearing down",
description="Remove all ephemeral artifacts of this instance"
)
def _run_instance(self, runner, args):
net_name = LoadedConfig.get()['network:name']
if not _find_net(net_name):
logging.info(f"Network '{net_name}' does not exist")
return True
try:
if are_you_sure("This will bring down this instance's hub network!"):
if runner.run('down'):
Executable('docker').run([
'network', 'rm', net_name
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
logging.info(f"Network '{net_name}' removed")
else:
return False
except subprocess.CalledProcessError:
logging.error(f"Error removing network '{net_name}'")
return False
return True

View file

@ -68,12 +68,12 @@ def _find_shell(args, project, service):
return None return None
class ShCommand(ServiceCommand): class ShellCommand(ServiceCommand):
"""kiwi sh""" """kiwi shell"""
def __init__(self): def __init__(self):
super().__init__( super().__init__(
'sh', num_projects=1, num_services=1, 'shell', num_projects=1, num_services=1,
action="Spawning shell in", action="Spawning shell in",
description="Spawn shell inside a project's service" description="Spawn shell inside a project's service"
) )

View file

@ -1,18 +0,0 @@
# local
from ..subcommand import SubCommand
from ..config import LoadedConfig
class ShowCommand(SubCommand):
"""kiwi show"""
def __init__(self):
super().__init__(
'show',
action="Printing",
description="Show effective kiwi.yml"
)
def _run_instance(self, runner, args):
print(LoadedConfig.get())
return True