From c646cf35d6429d80bcd2e136e9dc98a199ffb837 Mon Sep 17 00:00:00 2001 From: Robert Kaussow Date: Wed, 18 Dec 2019 20:24:58 +0100 Subject: [PATCH] initial commit --- .drone.jsonnet | 150 +++++++++++++++++++++++++++++ .drone.yml | 166 ++++++++++++++++++++++++++++++++ .flake8 | 8 ++ .gitignore | 104 +++++++++++++++++++++ LICENSE | 9 ++ README.md | 1 + bin/drone-cleanup-agents | 7 ++ cleanupagents/Cli.py | 137 +++++++++++++++++++++++++++ cleanupagents/Logging.py | 192 ++++++++++++++++++++++++++++++++++++++ cleanupagents/Utils.py | 36 +++++++ cleanupagents/__init__.py | 9 ++ cleanupagents/__main__.py | 12 +++ manifest.tmpl | 24 +++++ setup.cfg | 20 ++++ setup.py | 70 ++++++++++++++ test-requirements.txt | 19 ++++ 16 files changed, 964 insertions(+) create mode 100644 .drone.jsonnet create mode 100644 .drone.yml create mode 100644 .flake8 create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100755 bin/drone-cleanup-agents create mode 100644 cleanupagents/Cli.py create mode 100644 cleanupagents/Logging.py create mode 100644 cleanupagents/Utils.py create mode 100644 cleanupagents/__init__.py create mode 100644 cleanupagents/__main__.py create mode 100644 manifest.tmpl create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 test-requirements.txt diff --git a/.drone.jsonnet b/.drone.jsonnet new file mode 100644 index 0000000..7fde47b --- /dev/null +++ b/.drone.jsonnet @@ -0,0 +1,150 @@ +local PythonVersion(pyversion="3.5") = { + name: "python" + std.strReplace(pyversion, '.', '') + "-pytest", + image: "python:" + pyversion, + pull: "always", + environment: { + PY_COLORS: 1 + }, + commands: [ + "pip install -r test-requirements.txt -qq", + "pip install -qq .", + "drone-cleanup-agents --help", + ], + depends_on: [ + "clone", + ], +}; + +local PipelineLint = { + kind: "pipeline", + name: "lint", + platform: { + os: "linux", + arch: "amd64", + }, + steps: [ + { + name: "flake8", + image: "python:3.7", + pull: "always", + environment: { + PY_COLORS: 1 + }, + commands: [ + "pip install -r test-requirements.txt -qq", + "pip install -qq .", + "flake8 ./cleanupagents", + ], + }, + ], + trigger: { + ref: ["refs/heads/master", "refs/tags/**", "refs/pull/**"], + }, +}; + +local PipelineTest = { + kind: "pipeline", + name: "test", + platform: { + os: "linux", + arch: "amd64", + }, + steps: [ + PythonVersion(pyversion="3.5"), + PythonVersion(pyversion="3.6"), + PythonVersion(pyversion="3.7"), + PythonVersion(pyversion="3.8"), + ], + trigger: { + ref: ["refs/heads/master", "refs/tags/**", "refs/pull/**"], + }, + depends_on: [ + "lint", + ], +}; + +local PipelineSecurity = { + kind: "pipeline", + name: "security", + platform: { + os: "linux", + arch: "amd64", + }, + steps: [ + { + name: "bandit", + image: "python:3.7", + pull: "always", + environment: { + PY_COLORS: 1 + }, + commands: [ + "pip install -r test-requirements.txt -qq", + "pip install -qq .", + "bandit -r ./cleanupagents -x ./cleanupagents/tests", + ], + }, + ], + depends_on: [ + "test", + ], + trigger: { + ref: ["refs/heads/master", "refs/tags/**", "refs/pull/**"], + }, +}; + +local PipelineBuild = { + kind: "pipeline", + name: "build", + platform: { + os: "linux", + arch: "amd64", + }, + steps: [ + { + name: "build", + image: "python:3.7", + pull: "always", + commands: [ + "python setup.py sdist bdist_wheel", + ] + }, + { + name: "checksum", + image: "alpine", + pull: "always", + commands: [ + "cd dist/ && sha256sum * > sha256sum.txt" + ], + }, + { + name: "publish-gitea", + image: "plugins/gitea-release", + pull: "always", + settings: { + base_url: "https://gitea.owncloud.services", + api_key: { "from_secret": "gitea_token"}, + files: ["dist/*", "sha256sum.txt"], + title: "${DRONE_TAG}", + note: "CHANGELOG.md", + }, + when: { + ref: [ "refs/tags/**" ], + }, + }, + ], + depends_on: [ + "security", + ], + trigger: { + ref: ["refs/heads/master", "refs/tags/**", "refs/pull/**"], + }, +}; + +[ + PipelineLint, + PipelineTest, + PipelineSecurity, + PipelineBuild, +] + diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..0d4ba55 --- /dev/null +++ b/.drone.yml @@ -0,0 +1,166 @@ +--- +kind: pipeline +name: lint + +platform: + os: linux + arch: amd64 + +steps: +- name: flake8 + pull: always + image: python:3.7 + commands: + - pip install -r test-requirements.txt -qq + - pip install -qq . + - flake8 ./cleanupagents + environment: + PY_COLORS: 1 + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +--- +kind: pipeline +name: test + +platform: + os: linux + arch: amd64 + +steps: +- name: python35-pytest + pull: always + image: python:3.5 + commands: + - pip install -r test-requirements.txt -qq + - pip install -qq . + - drone-cleanup-agents --help + environment: + PY_COLORS: 1 + depends_on: + - clone + +- name: python36-pytest + pull: always + image: python:3.6 + commands: + - pip install -r test-requirements.txt -qq + - pip install -qq . + - drone-cleanup-agents --help + environment: + PY_COLORS: 1 + depends_on: + - clone + +- name: python37-pytest + pull: always + image: python:3.7 + commands: + - pip install -r test-requirements.txt -qq + - pip install -qq . + - drone-cleanup-agents --help + environment: + PY_COLORS: 1 + depends_on: + - clone + +- name: python38-pytest + pull: always + image: python:3.8 + commands: + - pip install -r test-requirements.txt -qq + - pip install -qq . + - drone-cleanup-agents --help + environment: + PY_COLORS: 1 + depends_on: + - clone + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +depends_on: +- lint + +--- +kind: pipeline +name: security + +platform: + os: linux + arch: amd64 + +steps: +- name: bandit + pull: always + image: python:3.7 + commands: + - pip install -r test-requirements.txt -qq + - pip install -qq . + - bandit -r ./cleanupagents -x ./cleanupagents/tests + environment: + PY_COLORS: 1 + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +depends_on: +- test + +--- +kind: pipeline +name: build + +platform: + os: linux + arch: amd64 + +steps: +- name: build + pull: always + image: python:3.7 + commands: + - python setup.py sdist bdist_wheel + +- name: checksum + pull: always + image: alpine + commands: + - cd dist/ && sha256sum * > sha256sum.txt + +- name: publish-gitea + pull: always + image: plugins/gitea-release + settings: + api_key: + from_secret: gitea_token + base_url: https://gitea.owncloud.services + files: + - dist/* + - sha256sum.txt + note: CHANGELOG.md + title: ${DRONE_TAG} + when: + ref: + - refs/tags/** + +trigger: + ref: + - refs/heads/master + - refs/tags/** + - refs/pull/** + +depends_on: +- security + +... diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..839a6c4 --- /dev/null +++ b/.flake8 @@ -0,0 +1,8 @@ +[flake8] +# Temp disable Docstring checks D101, D102, D103, D107 +ignore = E501, W503, F401, N813, D101, D102, D103, D107 +max-line-length = 100 +inline-quotes = double +exclude = .git,.tox,__pycache__,build,dist,tests,*.pyc,*.egg-info,.cache,.eggs,env* +application-import-names = cleanupagents +format = ${cyan}%(path)s:%(row)d:%(col)d${reset}: ${red_bold}%(code)s${reset} %(text)s diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1060356 --- /dev/null +++ b/.gitignore @@ -0,0 +1,104 @@ +# ---> Python +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ +env/ +env*/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject + +# Ignore ide addons +.server-script +.on-save.json +.vscode +.pytest_cache + +pip-wheel-metadata +logs/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..1475a9a --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2019 Robert Kaussow + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..e30cd5f --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# drone-cleanup-agents diff --git a/bin/drone-cleanup-agents b/bin/drone-cleanup-agents new file mode 100755 index 0000000..03ea98a --- /dev/null +++ b/bin/drone-cleanup-agents @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 + +import sys + +import cleanupagents.__main__ + +sys.exit(cleanupagents.__main__.main()) diff --git a/cleanupagents/Cli.py b/cleanupagents/Cli.py new file mode 100644 index 0000000..c0ed534 --- /dev/null +++ b/cleanupagents/Cli.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Main program.""" + +import argparse +import json +import logging +import os +import pickle #nosec +import shutil +import sys +from collections import defaultdict +from urllib.parse import urlparse + +from cleanupagents import __version__ +from cleanupagents.Logging import SingleLog +from cleanupagents.Utils import humanize +from cleanupagents.Utils import normalize_path +from cleanupagents.Utils import run_command +from cleanupagents.Utils import to_bool + + +class AgentCleanup: + + def __init__(self): + self.args = self._cli_args() + self.config = self._config() + self.log = SingleLog(logfile=self.config["logfile"]) + self.logger = self.log.logger + self.run() + + def _cli_args(self): + parser = argparse.ArgumentParser( + description=("Cleanup outdated and faulty drone agents")) + parser.add_argument("-v", dest="log_level", action="append_const", const=-1, + help="increase log level") + parser.add_argument("-q", dest="log_level", action="append_const", + const=1, help="decrease log level") + parser.add_argument("--version", action="version", version="%(prog)s {}".format(__version__)) + + return parser.parse_args().__dict__ + + def _config(self): + config = defaultdict(dict) + logfile = os.environ.get("DRONE_LOGFILE", "/var/log/drone-agents.log") + autoscaler = os.environ.get("DRONE_SCALER") + binary = normalize_path(os.environ.get("DRONE_BIN", shutil.which("drone")) or "./") + + config["required"] = ["drone_server", "drone_token", "drone_scaler"] + config["logfile"] = normalize_path(logfile) + config["drone_server"] = os.environ.get("DRONE_SERVER") + config["drone_token"] = os.environ.get("DRONE_TOKEN") + config["log_level"] = os.environ.get("DRONE_LOGLEVEL", "WARNING") + config["statefile"] = "/tmp/droneclean.pkl" #nosec + config["pending"] = defaultdict(dict, {}) + + if os.path.isfile(binary): + config["drone_bin"] = binary + + if autoscaler: + config["drone_scaler"] = [x.strip() for x in autoscaler.split(",")] + + if not os.path.exists(os.path.dirname(config["logfile"])): + os.makedirs(os.path.dirname(config["logfile"])) + + # Override correct log level from argparse + levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + log_level = levels.index(config["log_level"]) + if self.args["log_level"]: + for adjustment in self.args["log_level"]: + log_level = min(len(levels) - 1, max(log_level + adjustment, 0)) + config["log_level"] = levels[log_level] + + if os.path.isfile(config["statefile"]): + with open(config["statefile"], "rb") as json_file: + config["pending"] = pickle.load(json_file) #nosec + + return config + + def _clean(self): + pending = self.config["pending"] + control = defaultdict(dict) + + for scaler in self.config["drone_scaler"]: + error = [] + self.logger.info("Cleanup agents for scaler '{}'".format(scaler)) + + res = run_command("drone -s {server} -t {token} --autoscaler {scaler} server ls --format '{{{{ . | jsonify }}}}'".format( + server=self.config["drone_server"], token=self.config["drone_token"], scaler=scaler)) + + if res.returncode > 0: + self.log.sysexit_with_message("Command error:\n{}".format(humanize(res.stdout))) + + for line in res.stdout.splitlines(): + obj = json.loads(line) + + if obj["state"] == "error": + error.append(obj["name"]) + + for e in error: + force = "" + force_msg = "" + + if pending[e] and pending[e] < 2: + control[e] = pending[e] + 1 + elif pending[e] and pending[e] > 1: + force = "--force" + force_msg = "\nwill '--force' now" + else: + control[e] = 1 + + self.logger.info("Stopping '{agent}' ({triage}/3) {force}".format( + agent=e, triage=control[e] or 3, force=force_msg)) + #res = run_command( + # "drone -s {server} -t {token} --autoscaler {scaler} server destroy {force} {agent}".format( + # server=self.config["drone_server"], token=self.config["drone_token"], scaler=scaler, agent=e, force=force + #)) + + #if res.returncode > 0: + # self.log.sysexit_with_message("Command error:\n{}".format(humanize(res.stdout))) + + with open(self.config["statefile"], "wb") as json_file: + pickle.dump(control, json_file) #nosec + + def run(self): + try: + self.log.set_level(self.config["log_level"]) + except ValueError as e: + self.log.sysexit_with_message("Can not update log config.\n{}".format(str(e))) + + for c in self.config["required"]: + if not self.config[c]: + self.log.sysexit_with_message("Environment variable '{}' is required but empty or unset".format(c.upper())) + + if not self.config["drone_bin"]: + self.log.sysexit_with_message("Drone binary not found in PATH or not defined by '{}'".format(c.upper())) + + self._clean() diff --git a/cleanupagents/Logging.py b/cleanupagents/Logging.py new file mode 100644 index 0000000..8ddbd55 --- /dev/null +++ b/cleanupagents/Logging.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Global utility methods and classes.""" + +import logging +import logging.handlers +import os +import sys + +import colorama +from pythonjsonlogger import jsonlogger + +import cleanupagents.Utils +from cleanupagents.Utils import Singleton +from cleanupagents.Utils import to_bool + +CONSOLE_FORMAT = "%(asctime)s {}[%(levelname)s]{} %(message)s" +FILE_FORMAT = "%(asctime)s %(levelname)s %(message)s" +JSON_FORMAT = "(asctime) (levelname) (message)" + + +def _should_do_markup(): + py_colors = os.environ.get("PY_COLORS", None) + if py_colors is not None: + return to_bool(py_colors) + + return sys.stdout.isatty() and os.environ.get("TERM") != "dumb" + + +colorama.init(autoreset=True, strip=not _should_do_markup()) + + +class LogFilter(object): + """A custom log filter which excludes log messages above the logged level.""" + + def __init__(self, level): + """ + Initialize a new custom log filter. + + :param level: Log level limit + :returns: None + + """ + self.__level = level + + def filter(self, logRecord): # noqa + # https://docs.python.org/3/library/logging.html#logrecord-attributes + return logRecord.levelno <= self.__level + + +class MultilineFormatter(logging.Formatter): + """Logging Formatter to reset color after newline characters.""" + + def format(self, record): # noqa + record.msg = record.msg.replace("\n", "\n{}... ".format(colorama.Style.RESET_ALL)) + return logging.Formatter.format(self, record) + + +class MultilineJsonFormatter(jsonlogger.JsonFormatter): + """Logging Formatter to remove newline characters.""" + + def format(self, record): # noqa + record.msg = record.msg.replace("\n", " ") + return jsonlogger.JsonFormatter.format(self, record) + + +class Log: + def __init__(self, level=logging.WARN, name="cleanupagents", logfile="/var/log/drone-agents.log", json=False): + self.logger = logging.getLogger(name) + self.logger.handlers.clear() + self.logger.setLevel(level) + self.logger.addHandler(self._get_error_handler(json=json)) + self.logger.addHandler(self._get_warn_handler(json=json)) + self.logger.addHandler(self._get_info_handler(json=json)) + self.logger.addHandler(self._get_critical_handler(json=json)) + self.logger.addHandler(self._get_debug_handler(json=json)) + self.logger.addHandler(self._get_file_handler(logfile=logfile, json=json)) + self.logger.propagate = False + + def _get_file_handler(self, logfile, json=False): + handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=512000, backupCount=5) + handler.setLevel(logging.DEBUG) + handler.setFormatter(logging.Formatter(FILE_FORMAT)) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def _get_error_handler(self, json=False): + handler = logging.StreamHandler(sys.stderr) + handler.setLevel(logging.ERROR) + handler.addFilter(LogFilter(logging.ERROR)) + handler.setFormatter(MultilineFormatter( + self.error(CONSOLE_FORMAT.format(colorama.Fore.RED, colorama.Style.RESET_ALL)))) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def _get_warn_handler(self, json=False): + handler = logging.StreamHandler(sys.stdout) + handler.setLevel(logging.WARN) + handler.addFilter(LogFilter(logging.WARN)) + handler.setFormatter(MultilineFormatter( + self.warn(CONSOLE_FORMAT.format(colorama.Fore.YELLOW, colorama.Style.RESET_ALL)))) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def _get_info_handler(self, json=False): + handler = logging.StreamHandler(sys.stdout) + handler.setLevel(logging.INFO) + handler.addFilter(LogFilter(logging.INFO)) + handler.setFormatter(MultilineFormatter( + self.info(CONSOLE_FORMAT.format(colorama.Fore.CYAN, colorama.Style.RESET_ALL)))) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def _get_critical_handler(self, json=False): + handler = logging.StreamHandler(sys.stderr) + handler.setLevel(logging.CRITICAL) + handler.addFilter(LogFilter(logging.CRITICAL)) + handler.setFormatter(MultilineFormatter( + self.critical(CONSOLE_FORMAT.format(colorama.Fore.RED, colorama.Style.RESET_ALL)))) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def _get_debug_handler(self, json=False): + handler = logging.StreamHandler(sys.stderr) + handler.setLevel(logging.DEBUG) + handler.addFilter(LogFilter(logging.DEBUG)) + handler.setFormatter(MultilineFormatter( + self.critical(CONSOLE_FORMAT.format(colorama.Fore.BLUE, colorama.Style.RESET_ALL)))) + + if json: + handler.setFormatter(MultilineJsonFormatter(JSON_FORMAT)) + + return handler + + def set_level(self, s): + self.logger.setLevel(s) + + def debug(self, msg): + """Format info messages and return string.""" + return msg + + def critical(self, msg): + """Format critical messages and return string.""" + return msg + + def error(self, msg): + """Format error messages and return string.""" + return msg + + def warn(self, msg): + """Format warn messages and return string.""" + return msg + + def info(self, msg): + """Format info messages and return string.""" + return msg + + def _color_text(self, color, msg): + """ + Colorize strings. + + :param color: colorama color settings + :param msg: string to colorize + :returns: string + + """ + return "{}{}{}".format(color, msg, colorama.Style.RESET_ALL) + + def sysexit(self, code=1): + sys.exit(code) + + def sysexit_with_message(self, msg, code=1): + self.logger.critical(str(msg)) + self.sysexit(code) + + +class SingleLog(Log, metaclass=Singleton): + pass diff --git a/cleanupagents/Utils.py b/cleanupagents/Utils.py new file mode 100644 index 0000000..5057f79 --- /dev/null +++ b/cleanupagents/Utils.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Global utility methods and classes.""" + +import os +import shlex +import subprocess #nosec +import sys +from distutils.util import strtobool + + +def normalize_path(path): + if path: + return os.path.abspath(os.path.expanduser(os.path.expandvars(path))) + + +def to_bool(string): + return bool(strtobool(str(string))) + + +def run_command(command): + cmd = [x.strip() for x in shlex.split(command)] + p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) #nosec + return p + + +def humanize(value): + return value.decode("utf-8").strip() + + +class Singleton(type): + _instances = {} + + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) + return cls._instances[cls] diff --git a/cleanupagents/__init__.py b/cleanupagents/__init__.py new file mode 100644 index 0000000..269e62a --- /dev/null +++ b/cleanupagents/__init__.py @@ -0,0 +1,9 @@ +"""Default package.""" + +__author__ = "Robert Kaussow" +__project__ = "drone-cleanup-agents" +__version__ = "0.1.0" +__license__ = "MIT" +__maintainer__ = "Robert Kaussow" +__email__ = "rkaussow@owncloud.com" +__url__ = "https://gitea.owncloud.services/internal/drone-cleanup-agents" diff --git a/cleanupagents/__main__.py b/cleanupagents/__main__.py new file mode 100644 index 0000000..336d2e9 --- /dev/null +++ b/cleanupagents/__main__.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +"""Main program.""" + +from cleanupagents.Cli import AgentCleanup + + +def main(): + AgentCleanup() + + +if __name__ == "__main__": + main() diff --git a/manifest.tmpl b/manifest.tmpl new file mode 100644 index 0000000..d11a5cf --- /dev/null +++ b/manifest.tmpl @@ -0,0 +1,24 @@ +image: internal/drone-cleanup-agents:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}latest{{/if}} +{{#if build.tags}} +tags: +{{#each build.tags}} + - {{this}} +{{/each}} +{{/if}} +manifests: + - image: internal/drone-cleanup-agents:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}amd64 + platform: + architecture: amd64 + os: linux + + - image: internal/drone-cleanup-agents:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}arm64 + platform: + architecture: arm64 + os: linux + variant: v8 + + - image: internal/drone-cleanup-agents:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}arm + platform: + architecture: arm + os: linux + variant: v7 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..46fb2da --- /dev/null +++ b/setup.cfg @@ -0,0 +1,20 @@ +[metadata] +description-file = README.md +license_file = LICENSE + +[bdist_wheel] +universal = 1 + +[isort] +default_section = THIRDPARTY +known_first_party = cleanupagents +sections = FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER +force_single_line = true +line_length = 120 +skip_glob = **/.venv/* + +[tool:pytest] +filterwarnings = + ignore::FutureWarning + ignore:.*collections.*:DeprecationWarning + ignore:.*pep8.*:FutureWarning diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..7fd59b0 --- /dev/null +++ b/setup.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Setup script for the package.""" + +import io +import os +import re + +from setuptools import find_packages +from setuptools import setup + +PACKAGE_NAME = "cleanupagents" + + +def get_property(prop, project): + current_dir = os.path.dirname(os.path.realpath(__file__)) + result = re.search( + r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(prop), + open(os.path.join(current_dir, project, "__init__.py")).read()) + return result.group(1) + + +def get_readme(filename="README.md"): + this = os.path.abspath(os.path.dirname(__file__)) + with io.open(os.path.join(this, filename), encoding="utf-8") as f: + long_description = f.read() + return long_description + + +setup( + name=get_property("__project__", PACKAGE_NAME), + version=get_property("__version__", PACKAGE_NAME), + description="Cleanup drone agents", + author=get_property("__author__", PACKAGE_NAME), + author_email=get_property("__email__", PACKAGE_NAME), + url=get_property("__url__", PACKAGE_NAME), + license=get_property("__license__", PACKAGE_NAME), + long_description=get_readme(), + long_description_content_type="text/markdown", + packages=find_packages(exclude=["*.tests", "tests", "tests.*"]), + include_package_data=True, + zip_safe=False, + python_requires=">=3.5", + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "Intended Audience :: Developers", + "Intended Audience :: Information Technology", + "Intended Audience :: System Administrators", + "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)", + "Natural Language :: English", + "Operating System :: POSIX", + "Programming Language :: Python :: 3 :: Only", + "Topic :: System :: Installation/Setup", + "Topic :: System :: Systems Administration", + "Topic :: Utilities", + "Topic :: Software Development", + "Topic :: Software Development :: Documentation", + ], + install_requires=[ + "gitpython", + "colorama", + "python-json-logger", + ], + entry_points={ + "console_scripts": [ + "drone-cleanup-agents = cleanupagents.__main__:main" + ] + }, + test_suite="tests" +) diff --git a/test-requirements.txt b/test-requirements.txt new file mode 100644 index 0000000..25c2aaf --- /dev/null +++ b/test-requirements.txt @@ -0,0 +1,19 @@ +# open issue +# https://gitlab.com/pycqa/flake8-docstrings/issues/36 +pydocstyle<4.0.0 +flake8 +flake8-colors +flake8-blind-except +flake8-builtins +flake8-colors +flake8-docstrings<=3.0.0 +flake8-isort +flake8-logging-format +flake8-polyfill +flake8-quotes +pep8-naming +wheel +pytest +pytest-mock +pytest-cov +bandit