Skip to content

Commit

Permalink
Merge pull request #46 from swimlane/0_1_7
Browse files Browse the repository at this point in the history
0.1.7
  • Loading branch information
MSAdministrator authored Sep 14, 2022
2 parents c8cd357 + 49e3758 commit 63a985a
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 26 deletions.
2 changes: 1 addition & 1 deletion .cz.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tool.commitizen]
version = "0.1.5"
version = "0.1.6"
version_files = [
"pyproject.toml:version"
]
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "atomic-operator-runner"
version = "0.1.6"
version = "0.1.7"
description = "atomic-operator-runner"
authors = ["Josh Rickard <[email protected]>"]
license = "MIT"
Expand Down
18 changes: 18 additions & 0 deletions src/atomic_operator_runner/base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Base class for all classes in this project."""
# Copyright: (c) 2022, Swimlane <[email protected]>
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
import inspect
import platform
from typing import Dict

Expand Down Expand Up @@ -45,3 +46,20 @@ def get_local_system_platform(self) -> str:
if os_name == "darwin":
return "macos"
return os_name

def log(self, val, level="info") -> None:
"""Used to centralize logging across components.
We identify the source of the logging class by inspecting the calling stack.
Args:
val (str): The log value string to output.
level (str, optional): The log level. Defaults to "info".
"""
component = None
parent = inspect.stack()[1][0].f_locals.get("self", None)
component = parent.__class__.__name__
try:
getattr(getattr(parent, f"_{component}__logger"), level)(val)
except AttributeError as ae:
getattr(self.__logger, level)(val + ae)
15 changes: 13 additions & 2 deletions src/atomic_operator_runner/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

from .base import Base
from .processor import Processor
from .utils.exceptions import IncorrectExecutorError
from .utils.exceptions import IncorrectPlatformError


class LocalRunner(Base):
Expand All @@ -32,10 +34,19 @@ def run(
shell (bool, optional): Whether to spawn a new shell or not. Defaults to False.
env (dict, optional): Environment to use including environmental variables.. Defaults to os.environ.
cwd (str, optional): The current working directory. Defaults to None.
Raises:
IncorrectExecutorError: Raises when an incorrect executor is provided
IncorrectPlatformError: Raised when an incorrect platform is provided
"""
if not self.COMMAND_MAP.get(executor):
raise IncorrectExecutorError(provided_executor=executor)
if not self.COMMAND_MAP.get(executor).get(Base.config.platform):
raise IncorrectPlatformError(provided_platform=Base.config.platform)
_executor = self.COMMAND_MAP[executor][Base.config.platform]
self.__logger.debug("Starting a subprocess on the local system.")
process = subprocess.Popen(
executor,
_executor,
shell=shell,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
Expand All @@ -48,7 +59,7 @@ def run(
outs, errs = process.communicate(bytes(command, "utf-8") + b"\n", timeout=timeout)
# Adding details to our object response object
Processor(
command=command, executor=executor, return_code=process.returncode, output=str(outs), errors=str(errs)
command=command, executor=_executor, return_code=process.returncode, output=str(outs), errors=str(errs)
)
except subprocess.TimeoutExpired as e:
if e.output:
Expand Down
2 changes: 1 addition & 1 deletion src/atomic_operator_runner/processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def _capture_base_records(self, data: Any) -> None:
Args:
data (Any): Data to build a BaseRecord from.
"""
record: Union[BaseRecord, List[BaseRecord]]
record: Union[BaseRecord, List[BaseRecord]] = None
if isinstance(data, dict):
try:
record = BaseRecord(**data)
Expand Down
51 changes: 30 additions & 21 deletions src/atomic_operator_runner/utils/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,15 @@
class IncorrectExecutorError(Exception):
"""Raised when the incorrect executor is used."""

pass
def __init__(self, provided_executor: str) -> None:
"""Raises when the provided executor is not correct or unknown."""
from ..base import Base

Base().log(
val=f"The provided executor of '{provided_executor}' is not one of "
f"{','.join([k for k in Base.COMMAND_MAP.keys()])}",
level="critical",
)


class IncorrectPlatformError(Exception):
Expand All @@ -27,8 +35,9 @@ def __init__(self, provided_platform: str) -> None:
"""Raises when the provided platforms is not correct."""
from ..base import Base

Base.__logger.critical(
f"The provided platform of '{provided_platform}' is not one of macos, linux, windows or aws"
Base().log(
f"The provided platform of '{provided_platform}' is not one of macos, linux, windows or aws",
level="critical",
)


Expand All @@ -43,45 +52,45 @@ def __init__(self, exception: Any) -> None:
error_string = (
f"SSH Error - Unable to connect to {Base.config.hostname} - Received {type(exception).__name__}"
)
Base.__logger.debug(f"Full stack trace: {exception}")
Base.__logger.warning(error_string)
Base().log(f"Full stack trace: {exception}", level="debug")
Base().log(error_string, level="warning")
elif exception is AuthenticationException:
error_string = f"SSH Error - Unable to authenticate to host - {Base.config.hostname} "
error_string += f"- Received {type(exception).__name__}"
Base.__logger.debug(f"Full stack trace: {exception}")
Base.__logger.warning(error_string)
Base().log(f"Full stack trace: {exception}", level="debug")
Base().log(error_string, level="warning")
elif exception is BadAuthenticationType:
error_string = f"SSH Error - Unable to use provided authentication type to host - {Base.config.hostname} "
error_string += f"- Received {type(exception).__name__}"
Base.__logger.debug(f"Full stack trace: {exception}")
Base.__logger.warning(error_string)
Base().log(f"Full stack trace: {exception}", level="debug")
Base().log(error_string, level="warning")
elif exception is PasswordRequiredException:
error_string = f"SSH Error - Must provide a password to authenticate to host - {Base.config.hostname} "
error_string += f"- Received {type(exception).__name__}"
Base.__logger.debug(f"Full stack trace: {exception}")
Base.__logger.warning(error_string)
Base().log(f"Full stack trace: {exception}", level="debug")
Base().log(error_string, level="warning")
elif exception is AuthenticationError:
error_string = f"Windows Error - Unable to authenticate to host - {Base.config.hostname} "
error_string += f"- Received {type(exception).__name__}"
Base.__logger.debug(f"Full stack trace: {exception}")
Base.__logger.warning(error_string)
Base().log(f"Full stack trace: {exception}", level="debug")
Base().log(error_string, level="warning")
elif exception is WinRMTransportError:
error_string = f"Windows Error - Error occurred during transport on host - {Base.config.hostname} "
error_string += f"- Received {type(exception).__name__}"
Base.__logger.debug(f"Full stack trace: {exception}")
Base.__logger.warning(error_string)
Base().log(f"Full stack trace: {exception}", level="debug")
Base().log(error_string, level="warning")
elif exception is WSManFaultError:
error_string = f"Windows Error - Received WSManFault information from host - {Base.config.hostname} "
error_string += f"- Received {type(exception).__name__}"
Base.__logger.debug(f"Full stack trace: {exception}")
Base.__logger.warning(error_string)
Base().log(f"Full stack trace: {exception}", level="debug")
Base().log(error_string, level="warning")
elif exception is RequestException:
error_string = f"Request Exception - Connection Error to the configured host - {Base.config.hostname} "
error_string += f"- Received {type(exception).__name__}"
Base.__logger.debug(f"Full stack trace: {exception}")
Base.__logger.warning(error_string)
Base().log(f"Full stack trace: {exception}", level="debug")
Base().log(error_string, level="warning")
else:
error_string = f"Unknown Error - Received an unknown error from host - {Base.config.hostname} "
error_string += f"- Received {type(exception).__name__}"
Base.__logger.debug(f"Full stack trace: {exception}")
Base.__logger.warning(error_string)
Base().log(f"Full stack trace: {exception}", level="debug")
Base().log(error_string, level="warning")

0 comments on commit 63a985a

Please sign in to comment.