Skip to content

Commit

Permalink
Fix issue #53
Browse files Browse the repository at this point in the history
remove exit messages and raise loglevel to critical
  • Loading branch information
LegenJCdary committed Mar 23, 2022
1 parent 9d3cdd1 commit 12cb04b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 50 deletions.
65 changes: 23 additions & 42 deletions ansible_deployer/command_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@
def verify_subcommand(command: str):
"""Function to check the first arguments for a valid subcommand"""
if command not in ("run", "list", "lock", "unlock"):
print("[ERROR]: Unknown subcommand :%s", (command), file=sys.stderr)
print("[ERROR]: Program will exit now.")
print("[CRITICAL]: Unknown subcommand :%s", (command), file=sys.stderr)
sys.exit("55")

def set_logging(options: dict):
Expand Down Expand Up @@ -121,8 +120,7 @@ def create_workdir(timestamp: str):
os.makedirs(seq_path)
os.chdir(seq_path)
except Exception as e:
logger.error("Failed to create work dir:%s error was:%s", seq_path, e, file=sys.stderr)
logger.error("Program will exit now.")
logger.critical("Failed to create work dir:%s error was:%s", seq_path, e, file=sys.stderr)
sys.exit(90)
logger.debug("Successfully created workdir: %s", seq_path)
return seq_path
Expand Down Expand Up @@ -153,8 +151,7 @@ def validate_options(options: dict):
failed = True

if failed:
logger.error("Failed to validate options")
logger.error("Program will exit now.")
logger.critical("Failed to validate options")
sys.exit(55)

def load_configuration_file(config_file: str):
Expand All @@ -168,23 +165,20 @@ def load_configuration_file(config_file: str):
try:
config = yaml.safe_load(config_stream)
except yaml.YAMLError as e:
logger.error(e)
logger.error("Program will exit now.")
logger.critical(e)
sys.exit(51)

with open(os.path.join(conf["global_paths"]["config_dir"], "schema", config_file), "r",
encoding="utf8") as schema_stream:
try:
schema = yaml.safe_load(schema_stream)
except yaml.YAMLError as e:
logger.error(e)
logger.error("Program will exit now.")
logger.critical(e)
sys.exit(52)

validator = Validator(schema)
if not validator.validate(config, schema):
logger.error(validator.errors)
logger.error("Program will exit now.")
logger.critical(validator.errors)
sys.exit(53)

logger.debug("Loaded:\n%s", str(config))
Expand Down Expand Up @@ -232,8 +226,7 @@ def validate_option_by_dict_with_name(optval: str, conf: dict):
if elem["name"] == optval:
break
else:
logger.error("%s not found in configuration file.", optval)
logger.error("Program will exit now.")
logger.critical("%s not found in configuration file.", optval)
sys.exit(54)

return elem
Expand Down Expand Up @@ -303,9 +296,8 @@ def validate_option_values_against_config(config: dict, options: dict):
selected_items["limit"] = options["limit"]
break
else:
logger.error("Limit %s is not available for task %s.", options["limit"],
logger.critical("Limit %s is not available for task %s.", options["limit"],
options["task"])
logger.error("Program will exit now.")
sys.exit(54)

selected_items["commit"] = validate_commit(options, config)
Expand Down Expand Up @@ -340,13 +332,11 @@ def lock_inventory(lockdir: str, lockpath: str):
except FileExistsError:
with open(lockpath, "r", encoding="utf8") as fh:
proc_pid, proc_user = fh.readlines()
logger.error("Another process (PID: %s) started by user %s is using this infrastructure, "
"please try again later.", proc_pid.strip(), proc_user.strip())
logger.error("Program will exit now.")
logger.critical("Another process (PID: %s) started by user %s is using this infrastructure"
", please try again later.", proc_pid.strip(), proc_user.strip())
sys.exit(61)
except Exception as exc:
logger.error(exc)
logger.error("Program will exit now.")
logger.critical(exc)
sys.exit(62)

def unlock_inventory(lockpath: str):
Expand All @@ -360,12 +350,10 @@ def unlock_inventory(lockpath: str):
os.remove(lockpath)
logger.info("Lock %s has been removed.", lockpath)
except FileNotFoundError:
logger.error("Requested lock %s was not found. Nothing to do.", lockpath)
logger.error("Program will exit now.")
logger.critical("Requested lock %s was not found. Nothing to do.", lockpath)
sys.exit(63)
except Exception as exc:
logger.error(exc)
logger.error("Program will exit now.")
logger.critical(exc)
sys.exit(64)

def setup_ansible(setup_hooks: list, commit: str, workdir: str):
Expand All @@ -392,25 +380,23 @@ def setup_ansible(setup_hooks: list, commit: str, workdir: str):
if proc.returncode != 0:
failed = True
except Exception as e:
logger.error("Failed executing %s: %s", hook["opts"]["file"], e)
logger.error("Program will exit now.")
logger.critical("Failed executing %s: %s", hook["opts"]["file"], e)
sys.exit(41)
else:
if hook_out != ("", ""):
logger.info("setup_hook(%s),\nstdout:\n%s\nstdrr:\n%s", hook["name"],
hook_out[0].decode(), hook_out[1].decode())
logger.info(hook_out)
if proc.returncode:
logger.error("Setup hook %s failed, cannot continue", hook["name"])
logger.error("Program will exit now.")
logger.critical("Setup hook %s failed, cannot continue", hook["name"])
sys.exit(40)
else:
logger.info("Setup completed in %s", os.getcwd())

else:
logger.error("Not supported")
if failed:
logger.error("Program will exit now.")
logger.critical("Program will exit now.")
sys.exit(69)

def get_playbooks(config: dict, options: dict):
Expand Down Expand Up @@ -451,9 +437,8 @@ def run_task(config: dict, options: dict, inventory: str, lockpath: str):
playbooks = get_playbooks(config, options)
tags = get_tags_for_task(config, options)
if len(playbooks) < 1:
logger.error("No playbooks found for requested task %s. Nothing to do.", options['task'])
logger.critical("No playbooks found for requested task %s. Nothing to do.", options['task'])
unlock_inventory(lockpath)
logger.error("Program will exit now.")
sys.exit(70)
else:
for playbook in playbooks:
Expand All @@ -479,12 +464,11 @@ def run_task(config: dict, options: dict, inventory: str, lockpath: str):
for line in std_e.split(b"\n\n"):
logger.error(line.decode("utf-8"))
unlock_inventory(lockpath)
logger.error("Program will exit now.")
logger.critical("Program will exit now.")
sys.exit(71)
except Exception as exc:
logger.error("'%s' failed due to:")
logger.error(exc)
logger.error("Program will exit now.")
logger.critical("'%s' failed due to:")
logger.critical(exc)
sys.exit(72)

def verify_task_permissions(selected_items, user_groups):
Expand Down Expand Up @@ -561,8 +545,7 @@ def load_global_configuration():
config = yaml.safe_load(config_stream)
return config
except yaml.YAMLError as e:
logger.error(e, file=sys.stderr)
logger.error("Program will exit now.")
logger.critical(e, file=sys.stderr)
sys.exit(51)

def get_tags_for_task(config: dict, options: dict):
Expand All @@ -581,8 +564,7 @@ def main():
start_ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

if len(sys.argv) < 2:
print("[ERROR]: Too few arguments", file=sys.stderr)
print("[ERROR]: Program will exit now.")
print("[CRITICAL]: Too few arguments", file=sys.stderr)
sys.exit(2)
options = parse_options(sys.argv[1:])
logger = set_logging(options)
Expand Down Expand Up @@ -610,8 +592,7 @@ def main():
lockpath = os.path.join(lockdir, inv_file.replace(os.sep, "_"))
if options["subcommand"] == "run":
if not verify_task_permissions(selected_items, user_groups):
logger.error("Task forbidden")
logger.error("Program will exit now.")
logger.critical("Task forbidden")
sys.exit(errno.EPERM)
setup_ansible(config["tasks"]["setup_hooks"], options["commit"], workdir)
lock_inventory(lockdir, lockpath)
Expand Down
4 changes: 2 additions & 2 deletions tests/01-test_argument_parsing.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ source ./tests/testing_lib.sh

echo -e " ___ _ _ _\n / _ \/ | __ _ _ __ __ _ _ _ _ __ ___ ___ _ __ | |_ _ __ __ _ _ __ ___(_)_ __ __ _\n | | | | | _____ / _\` | '__/ _\` | | | | '_ \` _ \ / _ \ '_ \| __| | '_ \ / _\` | '__/ __| | '_ \ / _\` |\n | |_| | | |_____| | (_| | | | (_| | |_| | | | | | | __/ | | | |_ | |_) | (_| | | \__ \ | | | | (_| |\n \___/|_| \__,_|_| \__, |\__,_|_| |_| |_|\___|_| |_|\__| | .__/ \__,_|_| |___/_|_| |_|\__, |\n |___/ |_| |___/\n _ _ _ _\n __ ___ __ ___ _ __ __ _ ___ ___ _ __ ___ | |__ (_)_ __ __ _| |_(_) ___ _ __ ___\n \ \ /\ / / '__/ _ \| '_ \ / _\` | / __/ _ \| '_ \` _ \| '_ \| | '_ \ / _\` | __| |/ _ \| '_ \/ __|\n \ V V /| | | (_) | | | | (_| | | (_| (_) | | | | | | |_) | | | | | (_| | |_| | (_) | | | \__ \\n \_/\_/ |_| \___/|_| |_|\__, | \___\___/|_| |_| |_|_.__/|_|_| |_|\__,_|\__|_|\___/|_| |_|___/\n |___/\n \n"
#Check wrong combinations
check_message_in_output 'ansible-deployer' '\[ERROR\]: Too few arguments'
check_message_in_output 'ansible-deployer' '\[CRITICAL\]: Too few arguments'
check_message_in_output 'ansible-deployer run' '\[ERROR\]: task is required for run'
check_message_in_output 'ansible-deployer run' '\[ERROR\]: infra is required for run'
check_message_in_output 'ansible-deployer run' '\[ERROR\]: stage is required for run'
Expand Down Expand Up @@ -40,4 +40,4 @@ check_run_ok "ansible-deployer list --task=task_exec_bin_true"

echo -e " ___ _ _ _\n / _ \/ | __ _ _ __ __ _ _ _ _ __ ___ ___ _ __ | |_ _ __ __ _ _ __ ___(_)_ __ __ _\n | | | | | _____ / _\` | '__/ _\` | | | | '_ \` _ \ / _ \ '_ \| __| | '_ \ / _\` | '__/ __| | '_ \ / _\` |\n | |_| | | |_____| | (_| | | | (_| | |_| | | | | | | __/ | | | |_ | |_) | (_| | | \__ \ | | | | (_| |\n \___/|_| \__,_|_| \__, |\__,_|_| |_| |_|\___|_| |_|\__| | .__/ \__,_|_| |___/_|_| |_|\__, |\n |___/ |_| |___/\n __ _\n __ ___ __ ___ _ __ __ _ ___ ___ _ __ / _(_) __ _\n \ \ /\ / / '__/ _ \| '_ \ / _\` | / __/ _ \| '_ \| |_| |/ _\` |\n \ V V /| | | (_) | | | | (_| | | (_| (_) | | | | _| | (_| |\n \_/\_/ |_| \___/|_| |_|\__, | \___\___/|_| |_|_| |_|\__, |\n |___/ |___/\n \n"
#Check if wrong config is rejected
check_message_in_output 'ansible-deployer run --dry -t task_exec_bin_true -i nonExistingInfra -s prod' '\[ERROR\]: nonExistingInfra not found in configuration file'
check_message_in_output 'ansible-deployer run --dry -t task_exec_bin_true -i nonExistingInfra -s prod' '\[CRITICAL\]: nonExistingInfra not found in configuration file'
10 changes: 4 additions & 6 deletions tests/02-checkrun.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ check_run_ok "ansible-deployer run -t task_with_limit -s testing -i testInfra2 -

echo -e " ___ ____ _ _\n / _ \___ \ _____ _____ ___ _ _| |_(_) ___ _ __\n | | | |__) | _____ / _ \ \/ / _ \/ __| | | | __| |/ _ \| '_ \ \n | |_| / __/ |_____| | __/> < __/ (__| |_| | |_| | (_) | | | |\n \___/_____| \___/_/\_\___|\___|\__,_|\__|_|\___/|_| |_|\n \n _ _ _ _ _ _\n (_)_ ____ ____ _| (_) __| | ___ _ __ | |_(_) ___ _ __ ___\n | | '_ \ \ / / _\` | | |/ _\` | / _ \| '_ \| __| |/ _ \| '_ \/ __|\n | | | | \ V / (_| | | | (_| | | (_) | |_) | |_| | (_) | | | \__ \\n |_|_| |_|\_/ \__,_|_|_|\__,_| \___/| .__/ \__|_|\___/|_| |_|___/\n |_|\n \n"
# Non-existent option values
check_message_in_output 'ansible-deployer run -t task_exec_bin_ERR -s prod -i testInfra' '\[ERROR\]: task_exec_bin_ERR not found in configuration file.'
check_message_in_output 'ansible-deployer run -t task_exec_bin_true -s prod -i testInfra_ERR' '\[ERROR\]: testInfra_ERR not found in configuration file.'
check_message_in_output 'ansible-deployer run -t task_exec_bin_true -s prod_ERR -i testInfra' '\[ERROR\]: prod_ERR not found in configuration file.'
check_message_in_output 'ansible-deployer run -t task_exec_bin_ERR -s prod -i testInfra' '\[CRITICAL\]: task_exec_bin_ERR not found in configuration file.'
check_message_in_output 'ansible-deployer run -t task_exec_bin_true -s prod -i testInfra_ERR' '\[CRITICAL\]: testInfra_ERR not found in configuration file.'
check_message_in_output 'ansible-deployer run -t task_exec_bin_true -s prod_ERR -i testInfra' '\[CRITICAL\]: prod_ERR not found in configuration file.'

echo -e " ___ ____ _ _\n / _ \___ \ _____ _____ ___ _ _| |_(_) ___ _ __\n | | | |__) | _____ / _ \ \/ / _ \/ __| | | | __| |/ _ \| '_ \ \n | |_| / __/ |_____| | __/> < __/ (__| |_| | |_| | (_) | | | |\n \___/_____| \___/_/\_\___|\___|\__,_|\__|_|\___/|_| |_|\n \n _ _ _\n ___| | _(_)_ __ _ __ (_)_ __ __ _\n / __| |/ / | '_ \| '_ \| | '_ \ / _\` |\n \__ \ <| | |_) | |_) | | | | | (_| |\n |___/_|\_\_| .__/| .__/|_|_| |_|\__, |\n |_| |_| |___/\n \n"
# Check infra/stage skipping
Expand All @@ -38,9 +38,7 @@ check_message_in_output "ansible-deployer run -t task_with_commit -s testing -i

echo -e " ___ ____ _ _\n / _ \___ \ _____ _____ ___ _ _| |_(_) ___ _ __\n | | | |__) | _____ / _ \ \/ / _ \/ __| | | | __| |/ _ \| '_ \ \n | |_| / __/ |_____| | __/> < __/ (__| |_| | |_| | (_) | | | |\n \___/_____| \___/_/\_\___|\___|\__,_|\__|_|\___/|_| |_|\n \n _ _\n ___ | |_| |__ ___ _ __ ___\n / _ \| __| '_ \ / _ \ '__/ __|\n | (_) | |_| | | | __/ | \__ \\n \___/ \__|_| |_|\___|_| |___/\n \n"
# misc
check_message_in_output 'ansible-deployer run -t task_empty -s testing -i testInfra' '\[ERROR\]: No playbooks found for requested task'
# # unlock infra for further tests
check_run_ok "ansible-deployer unlock -s testing -i testInfra"
check_message_in_output 'ansible-deployer run -t task_empty -s testing -i testInfra' '\[CRITICAL\]: No playbooks found for requested task'

#Artificially generate lock
check_run_ok "ansible-deployer lock -s locked -i testInfra"
Expand Down

0 comments on commit 12cb04b

Please # to comment.