Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: move cli command logic #115

Merged
merged 1 commit into from
Nov 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 51 additions & 93 deletions getdeck/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import logging
import os
import traceback
from getdeck.telemetry.telemetry import CliTelemetry


os.environ["PYOXIDIZER"] = "1"

Expand All @@ -13,26 +11,36 @@
ARGUMENT_DECKFILE_HELP = "the deck.yaml location (as file, git or https)"


def check_positive(value):
try:
ivalue = int(value)
except ValueError:
raise argparse.ArgumentTypeError("timeout must be a positive integer value")
if ivalue <= 0:
raise argparse.ArgumentTypeError("timeout must be a positive integer value")
return ivalue


parser = argparse.ArgumentParser(
prog="deck",
description="The Deck CLI. For more help please visit: https://getdeck.dev",
)
action = parser.add_subparsers(dest="action", help="the action to be performed")
parser.add_argument("-d", "--debug", action="store_true", help="add debug output")

# list all decks of the given deck.yaml
# list
list_parser = action.add_parser("list")
list_parser.add_argument(
"Deckfile", help=ARGUMENT_DECKFILE_HELP, nargs="?", default="."
)

# rollout the cluster and install the deck from the given deck.yaml
# get
get_parser = action.add_parser("get")
get_parser.add_argument("--name", help="the Deck that you want to run", required=False)
get_parser.add_argument(
"-I",
"--no-cluster",
help="do not set up the cluster, use current kubectl context",
help="Do not set up the cluster, use current kubectl context",
action="store_true",
required=False,
)
Expand All @@ -44,17 +52,6 @@
required=False,
)


def check_positive(value):
try:
ivalue = int(value)
except ValueError:
raise argparse.ArgumentTypeError("timeout must be a positive integer value")
if ivalue <= 0:
raise argparse.ArgumentTypeError("timeout must be a positive integer value")
return ivalue


get_parser.add_argument(
"-T",
"--timeout",
Expand All @@ -73,6 +70,7 @@ def check_positive(value):
)
get_parser.add_argument("Deckfile", help=ARGUMENT_DECKFILE_HELP, nargs="?", default=".")

# remove
remove_parser = action.add_parser("remove")
remove_parser.add_argument(
"--name", help="the Deck that you want to remove", required=False
Expand All @@ -86,7 +84,7 @@ def check_positive(value):
remove_parser.add_argument(
"-I",
"--no-cluster",
help="do not set up the cluster, use current kubectl context",
help="Do not set up the cluster, use current kubectl context",
action="store_true",
default=False,
required=False,
Expand All @@ -95,115 +93,75 @@ def check_positive(value):
"Deckfile", help=ARGUMENT_DECKFILE_HELP, nargs="?", default="."
)

# stop
stop_parser = action.add_parser("stop")
stop_parser.add_argument(
"-I",
"--no-cluster",
help="do not set up the cluster, use current kubectl context",
help="Do not set up the cluster, use current kubectl context",
action="store_true",
required=False,
)
stop_parser.add_argument(
"Deckfile", help=ARGUMENT_DECKFILE_HELP, nargs="?", default="."
)

# version
version_parser = action.add_parser("version")


# hosts
hosts_parser = action.add_parser("hosts")
hosts_parser.add_argument("host_action", help="list/write/remove")
hosts_parser.add_argument(
"Deckfile", help=ARGUMENT_DECKFILE_HELP, nargs="?", default="."
)
hosts_parser.add_argument(
"--name", help="the Deck whose hosts will be considered", required=False
"--name", help="The Deck whose hosts will be considered", required=False
)

# telemetry
telemetry_parser = action.add_parser("telemetry")
telemetry_parser.add_argument("--off", help="Turn off telemetry", action="store_true")
telemetry_parser.add_argument("--on", help="Turn on telemetry", action="store_true")

try:
telemetry = CliTelemetry()
except Exception:
telemetry = False


def telemetry_command(on, off):
if not telemetry:
logger.info("Telemetry in not working on your machine. No action taken.")
return
if off and not on:
telemetry.off()
elif on and not off:
telemetry.on()
else:
logger.info("Invalid flags. Please use either --off or --on.")


def main():
from getdeck import configuration
from getdeck.api import (
get_available_decks,
run_deck,
remove_cluster,
remove_deck,
stop_cluster,
)
from getdeck.api.hosts import run_hosts
from getdeck.cli.console import console_setup
from getdeck.cli.get import get_command
from getdeck.cli.hosts import hosts_command
from getdeck.cli.list import list_command
from getdeck.cli.remove import remove_command
from getdeck.cli.stop import stop_command
from getdeck.cli.telemetry import telemetry_command
from getdeck.cli.version import version_command

args = parser.parse_args()
debug = args.debug

try:
args = parser.parse_args()
if args.debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)

logger.addHandler(configuration.console)
if args.action == "list":
decks = get_available_decks(args.Deckfile)
names = [deck.name for deck in decks]
logger.info(names)
elif args.action == "get":
if args.wait:
wait = True
timeout = int(args.timeout)
else:
wait = False
timeout = None

run_deck(
args.Deckfile,
args.name,
ignore_cluster=args.no_cluster,
wait=wait,
timeout=timeout,
no_input=args.no_input,
)
elif args.action == "remove":
if args.cluster:
remove_cluster(args.Deckfile, ignore_cluster=args.no_cluster)
else:
remove_deck(args.Deckfile, args.name, ignore_cluster=args.no_cluster)
elif args.action == "stop":
stop_cluster(args.Deckfile, ignore_cluster=args.no_cluster)
elif args.action == "version":
logger.info(f"Deck version: {configuration.__VERSION__}")
elif args.action == "hosts":
run_hosts(
args.Deckfile,
args.host_action,
deck_name=args.name,
)
elif args.action == "telemetry":
telemetry_command(on=args.on, off=args.off)
else:
console_setup(debug=debug)

command = {
"list": list_command,
"get": get_command,
"remove": remove_command,
"stop": stop_command,
"version": version_command,
"hosts": hosts_command,
"telemetry": telemetry_command,
}.get(args.action, None)

# unknown / invalid command
if not command:
parser.print_help()
exit(0)

command(args=args)
exit(0)
except Exception as e:
if args.debug:
if debug:
traceback.print_exc()
logger.fatal(f"There was an error running deck: {e}")
logger.critical(f"There was an error running deck: {e}")
exit(1)


Expand Down
File renamed without changes.
17 changes: 17 additions & 0 deletions getdeck/cli/console.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import logging
import sys

logger = logging.getLogger("deck")


def console_setup(debug: bool = False):
console = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter("[%(levelname)s] %(message)s")
console.setFormatter(formatter)

if debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)

logger.addHandler(console)
24 changes: 21 additions & 3 deletions getdeck/api/get.py → getdeck/cli/get.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import logging
from typing import Callable

from getdeck.api import stopwatch, remove
from getdeck.api.hosts import verify_all_hosts
from getdeck.cli import stopwatch, remove
from getdeck.cli.hosts import verify_all_hosts
from getdeck.configuration import default_configuration
from getdeck.k8s import create_namespace
from getdeck.provider.types import ProviderType
Expand Down Expand Up @@ -56,7 +56,7 @@ def run_deck( # noqa: C901
if progress_callback:
progress_callback(20)

# change api for beiboot
# change kubeconfig for beiboot
if k8s_provider.kubernetes_cluster_type == ProviderType.BEIBOOT:
_old_kubeconfig = config.kubeconfig
config.kubeconfig = k8s_provider.get_kubeconfig()
Expand Down Expand Up @@ -169,3 +169,21 @@ def _wait_ready(config, generated_deck, timeout):
raise RuntimeError(
f"The Pods of this Deck did not become ready in time (timout was {timeout} s)."
)


def get_command(args):
if args.wait:
wait = True
timeout = int(args.timeout)
else:
wait = False
timeout = None

run_deck(
args.Deckfile,
args.name,
ignore_cluster=args.no_cluster,
wait=wait,
timeout=timeout,
no_input=args.no_input,
)
10 changes: 9 additions & 1 deletion getdeck/api/hosts.py → getdeck/cli/hosts.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from python_hosts import Hosts, HostsEntry

from getdeck.api import stopwatch
from getdeck.cli import stopwatch
from getdeck.fetch.fetch import fetch_data

logger = logging.getLogger("deck")
Expand Down Expand Up @@ -63,3 +63,11 @@ def verify_host(host) -> bool:

def verify_all_hosts(*hosts):
return all(verify_host(host) for host in hosts)


def hosts_command(args):
run_hosts(
args.Deckfile,
args.host_action,
deck_name=args.name,
)
8 changes: 7 additions & 1 deletion getdeck/api/list.py → getdeck/cli/list.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
from typing import List

from getdeck.api.utils import stopwatch
from getdeck.cli.utils import stopwatch
from getdeck.fetch.fetch import fetch_data

logger = logging.getLogger("deck")
Expand All @@ -15,3 +15,9 @@ def get_available_decks(deckfile_location: str) -> List:

logger.debug(available_decks)
return available_decks


def list_command(args):
decks = get_available_decks(args.Deckfile)
names = [deck.name for deck in decks]
logger.info(names)
9 changes: 8 additions & 1 deletion getdeck/api/remove.py → getdeck/cli/remove.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import Callable

from getdeck.configuration import default_configuration
from getdeck.api import stopwatch
from getdeck.cli import stopwatch
from getdeck.fetch.fetch import fetch_data


Expand Down Expand Up @@ -84,3 +84,10 @@ def remove_deck(

del data_aux
return True


def remove_command(args):
if args.cluster:
remove_cluster(args.Deckfile, ignore_cluster=args.no_cluster)
else:
remove_deck(args.Deckfile, args.name, ignore_cluster=args.no_cluster)
6 changes: 5 additions & 1 deletion getdeck/api/stop.py → getdeck/cli/stop.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging

from getdeck.api import stopwatch
from getdeck.cli import stopwatch
from getdeck.configuration import default_configuration
from getdeck.fetch.fetch import fetch_data

Expand All @@ -23,3 +23,7 @@ def stop_cluster(

del data_aux
k8s_provider.stop()


def stop_command(args):
stop_cluster(args.Deckfile, ignore_cluster=args.no_cluster)
22 changes: 22 additions & 0 deletions getdeck/cli/telemetry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from getdeck.telemetry.telemetry import CliTelemetry
import logging


logger = logging.getLogger("deck")

try:
telemetry = CliTelemetry()
except Exception:
telemetry = False


def telemetry_command(args):
if not telemetry:
logger.info("Telemetry is not working on your machine. No action taken.")
return
if args.off and not args.on:
telemetry.off()
elif args.on and not args.off:
telemetry.on()
else:
logger.info("Invalid flags. Please use either --off or --on.")
File renamed without changes.
Loading