git-annex-mirror-orchestrator/gamo/update_refs.py
Michael Hanke cb1e979533
All checks were successful
Ruff / Code linting (push) Successful in 38s
Codespell / Check for spelling errors (push) Successful in 53s
Type annotations / check (push) Successful in 58s
Unit tests (Linux) / check (push) Successful in 2m46s
feat: switch order of operations keys before push
2026-11-17 09:55:38 +01:00

297 lines
9.1 KiB
Python

import json
import subprocess
import sys
import tempfile
from datetime import UTC
from pathlib import Path
from datalad_core.clone import clone_annexrepo
from datalad_core.config import (
ConfigItem,
get_defaults,
)
from datalad_core.repo import (
Repo,
Worktree,
)
from datalad_core.runners import (
CommandError,
call_annex_json_lines,
call_git,
call_git_lines,
call_git_oneline,
)
from gamo.annex_ref_mirror import mirror
from gamo.timestamps import (
now,
parse_timestamp,
timestamp_str,
)
defaults = get_defaults()
def _optional_int(val: int | str | None) -> int | None:
return None if val is None else int(val)
defaults.add(
'gamo.schedule.auto-disable-after-nerrors', ConfigItem(None, coercer=_optional_int)
)
# 15min, 25% duty cycle for an hourly pipeline run
defaults.add('gamo.transfer.maximum-duration-secs', ConfigItem(900, coercer=int))
def get_config(cfg, sec: str, item: str):
key = f'gamo.{sec}.{item}'
return cfg.get(key).value
def count_remote_commits(
repo: str | Path,
remote: str,
days: int = 30,
) -> int:
"""
Count unique commits on all branches of one remote from the last `days` days.
Git's committer date is used for the date filter.
"""
repo = Path(repo)
refs_output = call_git_lines(
['for-each-ref', '--format=%(refname)', f'refs/remotes/{remote}/'],
cwd=repo,
)
refs = [ref for ref in refs_output if not ref.endswith('/HEAD')]
if not refs:
return 0
count = call_git_oneline(
['rev-list', '--stdin', '--count', f'--since={days} days ago'],
inputs='\n'.join(refs) + '\n',
cwd=repo,
)
return int(count.strip() or 0)
def auto_disable(record, config):
state = record['state']
if 'errors' not in state:
# no errors, nothing to disable
return
threshold = get_config(config, 'schedule', 'auto-disable-after-nerrors')
if (
isinstance(threshold, int)
and threshold > 0
and len(state['errors']) >= threshold
):
record.setdefault('schedule', {})['auto_disabled'] = True
def source_last_modified(repo: str | Path, remote: str) -> str | None:
"""
Return the newest committer date across the remote's branches.
The result is normalized to UTC with a trailing ``Z``. Returns ``None``
when the remote has no branches.
"""
repo = Path(repo)
dates = call_git_lines(
[
'for-each-ref',
'--sort=-committerdate',
'--format=%(committerdate:iso8601-strict)',
f'refs/remotes/{remote}/',
],
cwd=repo,
)
for raw_date in dates:
date = raw_date.strip()
if date:
return timestamp_str(parse_timestamp(date).astimezone(UTC))
return None
def count_tags(repo: str | Path) -> int:
"""Count the tags present in the repository."""
repo = Path(repo)
refs = call_git_lines(
['for-each-ref', '--format=%(refname)', 'refs/tags/'],
cwd=repo,
)
return len([ref for ref in refs if ref.strip()])
def count_keys(
repo: str | Path,
findkeys_args: list[str],
) -> tuple[int, int, bool]:
repo = Path(repo)
# git annex findkeys --not --in origin
# git annex findkeys --anything
nkeys = 0
bytesize: int = 0
nosize_keys: bool = False
for rec in call_annex_json_lines(
['findkeys', *findkeys_args],
cwd=repo,
):
nkeys += 1
try:
bytesize += int(rec.get('bytesize'))
except ValueError:
# invalidate completeness of any bytesize report as soon as we have
# one key with unknown size
nosize_keys = True
return nkeys, bytesize, nosize_keys
def record_success_state(state, repo, remote):
state['last_success'] = timestamp_str(now())
if 'errors' in state:
del state['errors']
state['last30days_ncommits'] = count_remote_commits(repo, remote, 30)
state['source_last_modified'] = source_last_modified(repo, remote)
# the tags were force-fetched from the remote by mirror(), so the local
# count equals what is pushed to the target
state['n_tags'] = count_tags(repo)
(
state['keys_total_n'],
state['keys_total_bytesize'],
state['keys_total_unsized_present'],
) = count_keys(
repo,
['--anything'],
)
(
state['keys_missing_n'],
state['keys_missing_bytesize'],
state['keys_missing_unsized_present'],
) = count_keys(
repo,
['--not', '--in', 'origin'],
)
def transfer_keys(repo: Repo, to_remote: str):
print('Transferring keys...', file=sys.stderr) # noqa: T201
try:
for res in call_annex_json_lines(
[
'copy',
'--all',
'--from-anywhere',
'--to',
to_remote,
'--jobs',
'2',
'--time-limit',
f'{repo.config.get("gamo.transfer.maximum-duration-secs").value}s',
],
cwd=repo.path,
):
print(res, file=sys.stderr) # noqa: T201
except CommandError as e:
# git-annex's special return value to say "all good, but timeout"
if e.returncode == 101: # noqa: PLR2004
print( # noqa: T201
'Key transfer stopped at max runtime',
file=sys.stderr,
)
else:
# for now we just dump the error in the log.
# call_annex_json_lines() and with it CommandError()
# need to become more clever to not duplicate identical
# error messages in the (unstructured) error message.
# when this is done, we can RF this function to retain
# the last transfer error in the state record.
# overall, we do not want to fail because (few) keys failed
# to download. a partially complete mirror is just a
# condition to overcome (later). in particular we do not
# want to raise an exception here, because it would prevent
# later state assessment and reporting.
print(e, file=sys.stderr) # noqa: T201
def update_refs(record):
target = record['target']
target_url = target['url']
source_url = record['source']['url']
prune = target.get('prune', False)
force_tags = target.get('force_tags', True)
with tempfile.TemporaryDirectory(prefix='git-annex-ref-mirror-') as tmpdir:
repo = clone_annexrepo(
target_url,
Path(tmpdir),
bare=True,
private=True,
quiet=True,
)
# the next three are needed to deal with a git-annex repo that may
# not yet be initialized server-side (e.g. a forgejo-aneksajo repo
# fresh after a migration, at least as of 16.0.5-annex0).
# The annex-info triggers the init, and the fetch pulls it
call_git(
['annex', 'info', 'origin'],
cwd=repo.path,
capture_output=True,
)
call_git(
['fetch', 'origin', 'git-annex'],
cwd=repo.path,
capture_output=True,
)
call_git(
['annex', 'merge'],
cwd=repo.path,
capture_output=True,
)
# regular program from here
call_git(['remote', 'add', 'upstream', source_url], cwd=repo.path)
mirror(repo.path, 'upstream', prune=prune, force_tags=force_tags, quiet=True)
# the keys are transferred before the refs are pushed: the forgejo
# target only refreshes its reported repository size on a ref push,
# so the content must already be in place when the refs land.
transfer_keys(repo, 'origin')
# the transfer advanced the git-annex branch on both sides; fetch
# and merge the target's branch so the ref push below fast-forwards.
call_git(['fetch', 'origin', 'git-annex'], cwd=repo.path, capture_output=True)
call_git(['annex', 'merge'], cwd=repo.path, capture_output=True)
push_all = ['push', '--quiet', '--all', 'origin']
if prune:
push_all.append('--prune')
call_git(push_all, cwd=repo.path)
push_tags = ['push', '--quiet', '--tags', 'origin']
if force_tags:
push_tags.append('--force')
call_git(push_tags, cwd=repo.path)
record_success_state(record['state'], repo.path, 'upstream')
def main():
wt = Worktree.from_path(Path.cwd())
record_str = sys.stdin.read()
if not record_str.strip():
return
record = json.loads(record_str)
record.setdefault('state', {})
state = record['state']
state['last_attempt'] = timestamp_str(now())
try:
update_refs(record)
except (KeyError, OSError, ValueError, subprocess.CalledProcessError) as e:
# datalad's CommandError subclasses subprocess.CalledProcessError,
# so git/git-annex call failures are recorded as task errors here
# instead of escaping as crashes.
state.setdefault('errors', []).append(str(e))
finally:
auto_disable(record, wt.config)
print(json.dumps(record, separators=(',', ':'))) # noqa: T201