2019-04-04 14:06:18 +00:00
|
|
|
"""Standard definition."""
|
|
|
|
|
2021-05-04 19:55:44 +00:00
|
|
|
import copy
|
2021-01-30 15:52:48 +00:00
|
|
|
import importlib
|
|
|
|
import inspect
|
|
|
|
import os
|
|
|
|
import pathlib
|
|
|
|
import re
|
2023-02-10 07:51:17 +00:00
|
|
|
from abc import ABCMeta, abstractmethod
|
2021-01-30 15:52:48 +00:00
|
|
|
from collections import defaultdict
|
2023-04-20 06:23:12 +00:00
|
|
|
from urllib.parse import urlparse
|
2019-04-04 14:06:18 +00:00
|
|
|
|
2021-01-30 15:52:48 +00:00
|
|
|
import toolz
|
|
|
|
import yaml
|
|
|
|
from yamllint import linter
|
|
|
|
from yamllint.config import YamlLintConfig
|
2019-04-02 14:34:03 +00:00
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
from ansiblelater.exceptions import LaterAnsibleError, LaterError
|
|
|
|
from ansiblelater.utils import Singleton, sysexit_with_message
|
|
|
|
from ansiblelater.utils.yamlhelper import (
|
|
|
|
UnsafeTag,
|
|
|
|
VaultTag,
|
|
|
|
action_tasks,
|
|
|
|
normalize_task,
|
|
|
|
normalized_yaml,
|
|
|
|
parse_yaml_linenumbers,
|
|
|
|
)
|
2019-04-02 14:34:03 +00:00
|
|
|
|
|
|
|
|
2021-01-30 15:52:48 +00:00
|
|
|
class StandardMeta(type):
|
2019-04-02 14:34:03 +00:00
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
def __call__(cls, *args):
|
2021-01-30 15:52:48 +00:00
|
|
|
mcls = type.__call__(cls, *args)
|
2023-02-10 07:51:17 +00:00
|
|
|
mcls.sid = cls.sid
|
|
|
|
mcls.description = getattr(cls, "description", "__unknown__")
|
|
|
|
mcls.helptext = getattr(cls, "helptext", "")
|
|
|
|
mcls.version = getattr(cls, "version", None)
|
|
|
|
mcls.types = getattr(cls, "types", [])
|
2021-01-30 15:52:48 +00:00
|
|
|
return mcls
|
|
|
|
|
|
|
|
|
|
|
|
class StandardExtendedMeta(StandardMeta, ABCMeta):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
class StandardBase(metaclass=StandardExtendedMeta):
|
2021-01-30 15:52:48 +00:00
|
|
|
|
2023-04-20 06:23:12 +00:00
|
|
|
SHELL_PIPE_CHARS = "&|<>;$\n*[]{}?"
|
|
|
|
|
2021-01-30 15:52:48 +00:00
|
|
|
@property
|
|
|
|
@abstractmethod
|
|
|
|
def sid(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def check(self, candidate, settings):
|
|
|
|
pass
|
2019-04-02 14:34:03 +00:00
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
def __repr__(self):
|
2023-01-09 10:59:25 +00:00
|
|
|
return f"Standard: {self.description} (version: {self.version}, types: {self.types})"
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2023-02-10 07:51:17 +00:00
|
|
|
def get_tasks(candidate, settings): # noqa
|
2021-01-30 15:52:48 +00:00
|
|
|
errors = []
|
|
|
|
yamllines = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
with open(candidate.path, encoding="utf-8") as f:
|
2021-01-30 15:52:48 +00:00
|
|
|
yamllines = parse_yaml_linenumbers(f, candidate.path)
|
|
|
|
except LaterError as ex:
|
|
|
|
e = ex.original
|
|
|
|
errors.append(
|
2023-01-09 10:59:25 +00:00
|
|
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
except LaterAnsibleError as e:
|
2023-01-09 10:59:25 +00:00
|
|
|
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
|
2021-01-30 15:52:48 +00:00
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return yamllines, errors
|
|
|
|
|
|
|
|
@staticmethod
|
2023-02-10 07:51:17 +00:00
|
|
|
def get_action_tasks(candidate, settings): # noqa
|
2021-01-30 15:52:48 +00:00
|
|
|
tasks = []
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
with open(candidate.path, encoding="utf-8") as f:
|
2021-01-30 15:52:48 +00:00
|
|
|
yamllines = parse_yaml_linenumbers(f, candidate.path)
|
|
|
|
|
|
|
|
if yamllines:
|
|
|
|
tasks = action_tasks(yamllines, candidate)
|
|
|
|
except LaterError as ex:
|
|
|
|
e = ex.original
|
|
|
|
errors.append(
|
2023-01-09 10:59:25 +00:00
|
|
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
except LaterAnsibleError as e:
|
2023-01-09 10:59:25 +00:00
|
|
|
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
|
2021-01-30 15:52:48 +00:00
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return tasks, errors
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_normalized_task(task, candidate, settings):
|
|
|
|
normalized = None
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
|
|
|
normalized = normalize_task(
|
2021-05-04 19:55:44 +00:00
|
|
|
copy.copy(task), candidate.path, settings["ansible"]["custom_modules"]
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
except LaterError as ex:
|
|
|
|
e = ex.original
|
|
|
|
errors.append(
|
2023-01-09 10:59:25 +00:00
|
|
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
except LaterAnsibleError as e:
|
2023-01-09 10:59:25 +00:00
|
|
|
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
|
2021-01-30 15:52:48 +00:00
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return normalized, errors
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_normalized_tasks(candidate, settings, full=False):
|
|
|
|
normalized = []
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
with open(candidate.path, encoding="utf-8") as f:
|
2021-01-30 15:52:48 +00:00
|
|
|
yamllines = parse_yaml_linenumbers(f, candidate.path)
|
|
|
|
|
|
|
|
if yamllines:
|
|
|
|
tasks = action_tasks(yamllines, candidate)
|
|
|
|
for task in tasks:
|
|
|
|
# An empty `tags` block causes `None` to be returned if
|
|
|
|
# the `or []` is not present - `task.get("tags", [])`
|
|
|
|
# does not suffice.
|
|
|
|
|
|
|
|
# Deprecated.
|
|
|
|
if "skip_ansible_lint" in (task.get("tags") or []) and not full:
|
|
|
|
# No need to normalize_task if we are skipping it.
|
|
|
|
continue
|
|
|
|
|
|
|
|
if "skip_ansible_later" in (task.get("tags") or []) and not full:
|
|
|
|
# No need to normalize_task if we are skipping it.
|
|
|
|
continue
|
|
|
|
|
|
|
|
normalized.append(
|
|
|
|
normalize_task(
|
|
|
|
task, candidate.path, settings["ansible"]["custom_modules"]
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
except LaterError as ex:
|
|
|
|
e = ex.original
|
|
|
|
errors.append(
|
2023-01-09 10:59:25 +00:00
|
|
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
except LaterAnsibleError as e:
|
2023-01-09 10:59:25 +00:00
|
|
|
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
|
2021-01-30 15:52:48 +00:00
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return normalized, errors
|
|
|
|
|
|
|
|
@staticmethod
|
2023-02-10 07:51:17 +00:00
|
|
|
def get_normalized_yaml(candidate, settings, options=None): # noqa
|
2021-01-30 15:52:48 +00:00
|
|
|
errors = []
|
|
|
|
yamllines = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
if not options:
|
|
|
|
options = defaultdict(dict)
|
|
|
|
options.update(remove_empty=True)
|
|
|
|
options.update(remove_markers=True)
|
|
|
|
|
|
|
|
try:
|
|
|
|
yamllines = normalized_yaml(candidate.path, options)
|
|
|
|
except LaterError as ex:
|
|
|
|
e = ex.original
|
|
|
|
errors.append(
|
2023-01-09 10:59:25 +00:00
|
|
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
except LaterAnsibleError as e:
|
2023-01-09 10:59:25 +00:00
|
|
|
errors.append(StandardBase.Error(e.line, f"syntax error: {e.message}"))
|
2021-01-30 15:52:48 +00:00
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return yamllines, errors
|
|
|
|
|
|
|
|
@staticmethod
|
2023-02-10 07:51:17 +00:00
|
|
|
def get_raw_yaml(candidate, settings): # noqa
|
2021-01-30 15:52:48 +00:00
|
|
|
content = None
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
with open(candidate.path, encoding="utf-8") as f:
|
2021-01-30 15:52:48 +00:00
|
|
|
yaml.add_constructor(
|
|
|
|
UnsafeTag.yaml_tag, UnsafeTag.yaml_constructor, Loader=yaml.SafeLoader
|
|
|
|
)
|
2021-04-13 20:27:26 +00:00
|
|
|
yaml.add_constructor(
|
|
|
|
VaultTag.yaml_tag, VaultTag.yaml_constructor, Loader=yaml.SafeLoader
|
|
|
|
)
|
2021-01-30 15:52:48 +00:00
|
|
|
content = yaml.safe_load(f)
|
|
|
|
except yaml.YAMLError as e:
|
|
|
|
errors.append(
|
2023-01-09 10:59:25 +00:00
|
|
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return content, errors
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def run_yamllint(candidate, options="extends: default"):
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
with open(candidate.path, encoding="utf-8") as f:
|
2021-01-30 15:52:48 +00:00
|
|
|
for problem in linter.run(f, YamlLintConfig(options)):
|
|
|
|
errors.append(StandardBase.Error(problem.line, problem.desc))
|
|
|
|
except yaml.YAMLError as e:
|
|
|
|
errors.append(
|
2023-01-09 10:59:25 +00:00
|
|
|
StandardBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
2023-01-16 20:56:06 +00:00
|
|
|
except (TypeError, ValueError) as e:
|
|
|
|
errors.append(StandardBase.Error(None, f"yamllint error: {e}"))
|
|
|
|
candidate.faulty = True
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
return errors
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_first_cmd_arg(task):
|
|
|
|
if "cmd" in task["action"]:
|
|
|
|
first_cmd_arg = task["action"]["cmd"].split()[0]
|
|
|
|
elif "argv" in task["action"]:
|
|
|
|
first_cmd_arg = task["action"]["argv"][0]
|
|
|
|
else:
|
|
|
|
first_cmd_arg = task["action"]["__ansible_arguments__"][0]
|
|
|
|
|
2023-03-27 11:18:25 +00:00
|
|
|
return first_cmd_arg
|
2021-01-30 15:52:48 +00:00
|
|
|
|
2023-04-20 06:23:12 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_safe_cmd(task):
|
|
|
|
if "cmd" in task["action"]:
|
|
|
|
cmd = task["action"].get("cmd", "")
|
|
|
|
else:
|
|
|
|
cmd = " ".join(task["action"].get("__ansible_arguments__", []))
|
|
|
|
|
|
|
|
cmd = re.sub(r"{{.+?}}", "JINJA_EXPRESSION", cmd)
|
|
|
|
cmd = re.sub(r"{%.+?%}", "JINJA_STATEMENT", cmd)
|
|
|
|
cmd = re.sub(r"{#.+?#}", "JINJA_COMMENT", cmd)
|
|
|
|
|
|
|
|
parts = cmd.split()
|
|
|
|
parts = [p if not urlparse(p.strip('"').strip("'")).scheme else "URL" for p in parts]
|
|
|
|
|
|
|
|
return " ".join(parts)
|
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
class Error:
|
2021-01-30 15:52:48 +00:00
|
|
|
"""Default error object created if a rule failed."""
|
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
def __init__(self, lineno, message, **kwargs):
|
2021-01-30 15:52:48 +00:00
|
|
|
"""
|
|
|
|
Initialize a new error object and returns None.
|
|
|
|
|
|
|
|
:param lineno: Line number where the error from de rule occures
|
|
|
|
:param message: Detailed error description provided by the rule
|
|
|
|
|
|
|
|
"""
|
|
|
|
self.lineno = lineno
|
|
|
|
self.message = message
|
|
|
|
self.kwargs = kwargs
|
|
|
|
for (key, value) in kwargs.items():
|
|
|
|
setattr(self, key, value)
|
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
def __repr__(self):
|
2021-01-30 15:52:48 +00:00
|
|
|
if self.lineno:
|
2023-01-09 10:59:25 +00:00
|
|
|
return f"{self.lineno}: {self.message}"
|
2023-02-10 07:51:17 +00:00
|
|
|
return f" {self.message}"
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
def to_dict(self):
|
2023-02-10 07:51:17 +00:00
|
|
|
result = {"lineno": self.lineno, "message": self.message}
|
2021-01-30 15:52:48 +00:00
|
|
|
for (key, value) in self.kwargs.items():
|
|
|
|
result[key] = value
|
|
|
|
return result
|
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
class Result:
|
2021-01-30 15:52:48 +00:00
|
|
|
"""Generic result object."""
|
|
|
|
|
|
|
|
def __init__(self, candidate, errors=None):
|
|
|
|
self.candidate = candidate
|
|
|
|
self.errors = errors or []
|
|
|
|
|
|
|
|
def message(self):
|
2023-01-09 10:59:25 +00:00
|
|
|
return "\n".join([f"{self.candidate}:{error}" for error in self.errors])
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
|
2023-06-28 07:14:39 +00:00
|
|
|
class StandardLoader():
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
def __init__(self, source):
|
|
|
|
self.rules = []
|
|
|
|
|
|
|
|
for s in source:
|
|
|
|
for p in pathlib.Path(s).glob("*.py"):
|
|
|
|
filename = os.path.splitext(os.path.basename(p))[0]
|
|
|
|
if not re.match(r"^[A-Za-z]+$", filename):
|
|
|
|
continue
|
|
|
|
|
|
|
|
spec = importlib.util.spec_from_file_location(filename, p)
|
|
|
|
module = importlib.util.module_from_spec(spec)
|
|
|
|
|
|
|
|
try:
|
|
|
|
spec.loader.exec_module(module)
|
|
|
|
except (ImportError, NameError) as e:
|
2023-06-15 07:30:03 +00:00
|
|
|
sysexit_with_message(f"Failed to load roles file {filename}: \n {e!s}")
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
for _name, obj in inspect.getmembers(module):
|
2021-01-30 15:52:48 +00:00
|
|
|
if self._is_plugin(obj):
|
|
|
|
self.rules.append(obj())
|
|
|
|
except TypeError as e:
|
2023-05-28 21:13:08 +00:00
|
|
|
sysexit_with_message(f"Failed to load roles file: \n {e!s}")
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
self.validate()
|
|
|
|
|
|
|
|
def _is_plugin(self, obj):
|
|
|
|
return inspect.isclass(obj) and issubclass(
|
|
|
|
obj, StandardBase
|
|
|
|
) and obj is not StandardBase and not None
|
|
|
|
|
|
|
|
def validate(self):
|
|
|
|
normalized_std = (list(toolz.remove(lambda x: x.sid == "", self.rules)))
|
|
|
|
unique_std = len(list(toolz.unique(normalized_std, key=lambda x: x.sid)))
|
|
|
|
all_std = len(normalized_std)
|
2023-02-10 07:51:17 +00:00
|
|
|
if all_std != unique_std:
|
2021-01-30 15:52:48 +00:00
|
|
|
sysexit_with_message(
|
|
|
|
"Detect duplicate ID's in standards definition. Please use unique ID's only."
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class SingleStandards(StandardLoader, metaclass=Singleton):
|
|
|
|
"""Singleton config class."""
|
|
|
|
|
|
|
|
pass
|