view sync.py @ 289:65e28d2e0cd8

move static templates to files/ ; use inventory tags for selecting hosts+features ; other refactors
author drewp@bigasterisk.com
date Sun, 21 Apr 2024 17:07:23 -0700
parents 3af02e24eaf9
children 5f3e053ba888
line wrap: on
line source

from pathlib import Path

from pyinfra import host
from pyinfra.facts.server import Command
from pyinfra.operations import apt, files, server, systemd


def host_running_version(user: str, v: str):
    # if this command fails, we go in to error state and run nothing else #bugreport
    out = host.get_fact(Command, f"runuser -u {user} syncthing serve --version || exit 0")
    if out is None:
        return False
    _, sv, *_ = out.split()
    return sv == v


def install_syncthing(user, version, os='linux', arch='amd64'):
    tmpdir = Path('/tmp/syncthing_install')
    dl_name = f'syncthing-{os}-{arch}-{version}'
    url = f'https://github.com/syncthing/syncthing/releases/download/{version}/{dl_name}.tar.gz'
    files.directory(path=tmpdir)
    files.download(src=url, dest=str(tmpdir / f'{dl_name}.tgz'))  # bugreport
    server.shell(commands=[f'cd {tmpdir}; aunpack {dl_name}.tgz'])

    systemd.service(service=f'syncthing@{user}', running=False)

    user_svc_template = '/lib/systemd/system/syncthing@.service'
    server.shell(commands=[
        f'cp -a {tmpdir}/{dl_name}/{s} {d}' for s, d in [
            ('syncthing', '/usr/bin'),
            ('etc/linux-systemd/system/syncthing@.service', user_svc_template),
            ('etc/linux-systemd/system/syncthing-resume.service', '/etc/systemd/system/syncthing-resume.service'),
        ]
    ])
    files.link(path=f'/etc/systemd/system/multi-user.target.wants/syncthing@{user}.service', target=user_svc_template)
    systemd.service(service=f'syncthing@{user}', enabled=True, restarted=True, daemon_reload=True)


# also see /my/serv/filesync/syncthing/deploy.yaml for the container one
version = 'v1.26.1'

# primary instance is in k8s (/my/serv/filesync/syncthing); the rest are run with systemd.
# Configs are in ~/.config/syncthing/ on each box
if host.data.get('syncthing'):
    apt.packages(packages=['syncthing'], present=False)
    user = 'ari' if host.name == 'dot' else 'drewp'

    if not host_running_version(user, version):
        install_syncthing(user, version)

# something above has broken devnull #bugreport
server.shell(commands=['chmod a+w /dev/null'])

# also consider https://github.com/Martchus/syncthingtray tray status viewer on dtops