Compare commits

...

5 commits

Author SHA1 Message Date
a2d4a65466 doc: add systemd timer and service example 2024-09-01 23:25:09 +02:00
421e33e874 feat: update example config file
- add self-update option

🤖
2024-09-01 19:44:35 +02:00
260ab2ba22 chore: fix pylint complains 2024-06-10 12:09:05 +02:00
3d52b21442 doc: update README with cronjob instructions
- add section about recommended crontab usage
- provide example of how to set up cron job for dc-ops
- remind users to set up logrotate for the log file

🤖
2024-01-05 22:13:36 +01:00
3bf7fc2255 feat: enhance logging
- remove `*` from stack log entry
- prefix log messages with arrow symbol for better readability
2023-12-22 22:44:17 +01:00
4 changed files with 66 additions and 11 deletions

View file

@ -18,6 +18,50 @@ See `requirements.txt`
2. Adapt `config.yml.example` to your needs and save it as `config.yml`
3. Run `dc-ops` from the shell or from a cron job
### Cron
Recommended crontab usage:
`*/15 * * * * python3 /opt/dc-ops/dc-ops 2>&1 | ts "\%FT\%H:\%M:\%S" >>/var/log/dc-ops.log`
(do not forget logrotate)
### Systemd
Recommended systemd usage:
```toml
# /etc/systemd/system/dc-ops.service
[Unit]
Description=Run dc-ops once
After=docker.target
[Service]
Type=simple
WorkingDirectory=/opt/dc-ops/
ExecStart=python3 dc-ops
```
```toml
# /etc/systemd/system/dc-ops.timer
[Unit]
Description=Start dc-ops service periodically
[Timer]
Persistent=true
OnCalendar=*:0/15
Unit=dc-ops.service
[Install]
WantedBy=timers.target
```
Enable and start the timer:
```
systemctl enable dc-ops.timer
systemctl start dc-ops.timer
```
## Parameters
See `dc-ops --help`

View file

@ -1,3 +1,4 @@
self-update: true # optional
loglevdel: "INFO" # optional
compose-opts: "--dry-run"
stacks:

11
dc-ops
View file

@ -5,6 +5,8 @@
# CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/deed.de)
# for civil use only
# pylint: disable=missing-module-docstring,invalid-name
import argparse
import logging as log
from pathlib import Path
@ -15,12 +17,12 @@ from lib.helper import run_subprocess, update_git_repo, do_selfupdate
# read config file
configfile = Path(__file__).with_name("config.yml")
with configfile.open("r") as f:
with configfile.open("r", encoding="utf-8") as f:
cfg = yaml.safe_load(f.read())
# fmt: off
parser = argparse.ArgumentParser()
parser.add_argument("--ignore-git-status", action="store_true", help="continue even if there are no new commits") # noqa
parser.add_argument("--ignore-git-status", action="store_true", help="continue even if there are no new commits")
parser.add_argument("--loglevel", help="set loglevel (overrides config file)")
args = parser.parse_args()
# fmt: on
@ -47,7 +49,7 @@ for stack in cfg["stacks"]:
# header
stackdir = stack["dir"]
log.info(f"* processing {stackdir}")
log.info("processing: %s", stackdir)
# update repo and check for new commits
if not update_git_repo(stackdir, args.ignore_git_status):
@ -55,6 +57,7 @@ for stack in cfg["stacks"]:
# run pre-command
if "pre" in stack:
log.info("-> executing pre-command")
if not run_subprocess(stack["pre"], stackdir):
continue
@ -62,6 +65,7 @@ for stack in cfg["stacks"]:
# (or just for the directory if no compose-file defined)
composefiles = stack.get("compose-files", ["docker-compose.yml"])
for composefile in composefiles:
log.info("-> bringing up %s", composefile)
if not run_subprocess(
f"docker compose --file {composefile} up --detach {composeopts}",
stackdir,
@ -70,5 +74,6 @@ for stack in cfg["stacks"]:
# run post-command
if "post" in stack:
log.info("-> executing post-command")
if not run_subprocess(stack["post"], stackdir):
continue

View file

@ -1,3 +1,5 @@
# pylint: disable=missing-module-docstring
import logging as log
import subprocess
import sys
@ -16,9 +18,9 @@ def do_selfupdate():
log.error(str(e))
return
if pull_res.old_commit:
log.info("selfupdate: successfully updated myself - exiting")
log.info("SelfUpdate: successfully updated myself - exiting")
sys.exit(0)
log.info("selfupdate: no updates found for myself")
log.info("SelfUpdate: no updates found for myself")
def run_subprocess(command: str, workdir: str) -> bool:
@ -32,7 +34,9 @@ def run_subprocess(command: str, workdir: str) -> bool:
bool: False if subprocess fails
"""
try:
log.debug(subprocess.run(command.split(" "), cwd=workdir, text=True))
log.debug(
subprocess.run(command.split(" "), cwd=workdir, text=True, check=False)
)
except subprocess.CalledProcessError:
return False
@ -49,11 +53,12 @@ def update_git_repo(repo_path: str, ignore_git_status: bool) -> bool:
Returns:
bool: False if any step fails
"""
# create repo instance if it exists
try:
repo = git.Repo(repo_path)
except git.exc.NoSuchPathError:
log.error("directory not found")
log.error("-> directory not found")
return False
if not ignore_git_status:
@ -61,19 +66,19 @@ def update_git_repo(repo_path: str, ignore_git_status: bool) -> bool:
try:
fetch_res = repo.remotes.origin.fetch()[0]
except git.exc.GitCommandError as e:
log.error(str(e))
log.error("-> %s ", str(e))
return False
# check for new commits
if not fetch_res.old_commit:
log.info("no changes - skipping")
log.info("-> no changes - skipping")
return False
# pull remote changes to local branch
try:
log.info(repo.git.pull())
log.info("-> %s", repo.git.pull())
except git.exc.GitCommandError as e:
log.error(str(e))
log.error("-> %s", str(e))
return False
return True