Initial commands

This commit is contained in:
einarf 2023-03-09 00:56:50 +01:00
parent 7294d85c09
commit dbf238c5a9
7 changed files with 58 additions and 48 deletions

View file

@ -1,9 +1,7 @@
import argparse import argparse
import os import os
import logging import logging
from importlib import import_module from typing import List
from pkgutil import iter_modules
from typing import Dict, List
from restic_compose_backup import ( from restic_compose_backup import (
alerts, alerts,
@ -13,27 +11,16 @@ from restic_compose_backup import (
) )
from restic_compose_backup.config import Config from restic_compose_backup.config import Config
from restic_compose_backup.containers import RunningContainers from restic_compose_backup.containers import RunningContainers
from restic_compose_backup import cron, utils from restic_compose_backup import utils
from restic_compose_backup import commands from restic_compose_backup import commands
from restic_compose_backup.commands.base import BaseCommand
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def get_commands() -> Dict[str, BaseCommand]:
"""Return the list of available command classes"""
_commands = {}
for module_info in iter_modules(commands.__path__):
module = import_module(f'restic_compose_backup.commands.{module_info.name}')
if hasattr(module, 'Command'):
_commands[module_info.name] = module.Command
return _commands
def main(): def main():
"""CLI entrypoint""" """Main entry point for the application"""
commands = get_commands() args = parse_args(sorted(commands.COMMANDS.keys()))
args = parse_args(sorted(commands.keys())) command = commands.COMMANDS[args.action](args)
command = commands[args.action]()
command.run() command.run()
return return
@ -63,13 +50,6 @@ def main():
elif args.action == 'alert': elif args.action == 'alert':
alert(config, containers) alert(config, containers)
elif args.action == 'version':
import restic_compose_backup
print(restic_compose_backup.__version__)
elif args.action == "crontab":
crontab(config)
# Random test stuff here # Random test stuff here
elif args.action == "test": elif args.action == "test":
nodes = utils.get_swarm_nodes() nodes = utils.get_swarm_nodes()
@ -296,20 +276,6 @@ def snapshots(config, containers):
print(line) print(line)
def alert(config, containers):
"""Test alerts"""
logger.info("Testing alerts")
alerts.send(
subject="{}: Test Alert".format(containers.project_name),
body="Test message",
)
def crontab(config):
"""Generate the crontab"""
print(cron.generate_crontab(config))
def parse_args(choices: List[str]): def parse_args(choices: List[str]):
parser = argparse.ArgumentParser(prog='restic_compose_backup') parser = argparse.ArgumentParser(prog='restic_compose_backup')
parser.add_argument( parser.add_argument(

View file

@ -1 +0,0 @@
from .base import BaseCommand

View file

@ -0,0 +1,19 @@
import sys
from importlib import import_module
from pkgutil import iter_modules
from typing import Dict
from .base import BaseCommand
def get_commands() -> Dict[str, BaseCommand]:
"""Return the list of available command classes"""
_commands = {}
current_module = sys.modules[__name__]
for module_info in iter_modules(current_module.__path__):
module = import_module(f'restic_compose_backup.commands.{module_info.name}')
if hasattr(module, 'Command'):
_commands[module_info.name] = module.Command
return _commands
COMMANDS = get_commands()

View file

@ -1,9 +1,15 @@
from .base import BaseCommand from .base import BaseCommand
from restic_compose_backup import alerts
class Command(BaseCommand): class Command(BaseCommand):
"""Send an alert""" """Send an alert"""
name = "alert" name = "alert"
def run(self): def run(self):
print("Alert!") """Test alerts"""
self.logger.info("Testing alerts")
containers = self.get_containers()
alerts.send(
subject="{}: Test Alert".format(containers.project_name),
body="Test message",
)

View file

@ -1,12 +1,30 @@
import logging
from restic_compose_backup.config import Config from restic_compose_backup.config import Config
from restic_compose_backup.containers import RunningContainers
from restic_compose_backup import log
class BaseCommand: class BaseCommand:
"""Base class for all commands""" """Base class for all commands"""
name = "base" name = "base"
def __init__(self): def __init__(self, cli_args, *args, **kwargs):
self.cli_args = cli_args
self.log_level = cli_args.log_level
self.config = Config() self.config = Config()
self.logger = logging.getLogger(__name__)
log.setup(level=self.log_level or self.config.log_level)
def get_containers(self):
"""Get running containers"""
return RunningContainers()
def run(self): def run(self):
"""Run the command"""
raise NotImplementedError raise NotImplementedError
def run_command(self, command: str):
"""Run a command by name and return the result"""
from . import COMMANDS
command = COMMANDS[command]
command(self.cli_args).run()

View file

@ -1,9 +1,10 @@
from .base import BaseCommand from .base import BaseCommand
from restic_compose_backup import cron
class Command(BaseCommand): class Command(BaseCommand):
"""Manage crontab""" """Manage crontab"""
name = "crontab" name = "crontab"
def run(self): def run(self):
print("Crontab!") """Generate the crontab"""
print(cron.generate_crontab(self.config))

View file

@ -6,4 +6,5 @@ class Command(BaseCommand):
name = "version" name = "version"
def run(self): def run(self):
print("Version!") import restic_compose_backup
print(restic_compose_backup.__version__)