Some Bits: Nelson's log

Syncthing status from the command line

I’ve written a little tool to show me the status of Syncthing on the command line. I now rely on it to get my files off of computers that will then be turned off and inaccessible. I didn’t have any way to know if it was really working. I don’t have a reliable outage monitoring system for all my personal tech crap. (I mean, who does? Hmm..)

Anyway this turned into a bit of a yak-shaving exercise. Syncthing does not really have a command line tool. There is a syncthing cli command (and formerly the syncthing-cli third party tool) but they don’t report the status I need. What syncthing does have is a very nice REST API for querying status, so I wrote a tool to check that.

The other tricky thing is defining what it means for syncthing to be synced. I’m not sure I got this right. The algorithm I’m using is it enumerates all folders and all remote devices and checks completion on each one. In practice folders seems to catch outgoing changes, remote devices catches incoming changes. It ends up being O(n) HTTP calls, not ideal, but here we are. It might be possible to get it down to 3; I didn’t quite understand how the bundling in rest/db/completion worked.

Anyway, the Python script below mostly works. I wonder if someone else has already done this and I reinvented the wheel? One last wrinkle; when to run this. I was originally thinking in MOTD (hence my earlier post) but for now I’m running it in .bash_login.

#!/usr/bin/env python3
"""
Status report for syncthing, suitable for including in /etc/motd.d. By Nelson Minar <nelson@monkey.org>

Note that this will show "completely synchronized" if a file was very recently created or altered and
syncthing is not yet aware the change has been made. See the scanning and fsnotify docs in Syncthing for details.
"""

import json, urllib.request, platform, itertools, sys
from pprint import pprint

"Configure the URL endpoint and API key based on hostname. API key is in Settings."
HOST = None
API_KEY = None
config_table = {
	'ub': ('http://127.0.0.1:8384', 'XXXXX'),
    'Nelson-Win10': ('http://127.0.0.1:2103', 'XXXXX')
}

def st_api(command):
	"Call the SyncThing REST API and return as JSON"
	req = urllib.request.Request(f'{HOST}/{command}')
	req.add_header('X-API-Key', API_KEY)
	resp = urllib.request.urlopen(req, timeout=2).read()
	return json.loads(resp)

def main():
	global HOST, API_KEY
	try:
		HOST, API_KEY = config_table[platform.node()]
	except:
		# Exit silently if we're not configured
		sys.exit(0)

	folder_report = []
	device_report = []
	try:
		# Explicit error handling for first REST connection. Others are YOLO.
		devices = st_api('rest/config/devices')
	except Exception as e:
		print(f'Syncthing: Error connecting to {HOST}.')
		sys.exit(0)

	# Check completion for all remote devices
	for device in devices:
		completion = st_api(f'rest/db/completion?device={device["deviceID"]}')
		device_report.append((device["name"], completion["completion"]))

	# Check completion for all folders
	for folder in st_api('rest/config/folders'):
		completion = st_api(f'rest/db/completion?folder={folder["id"]}')
		folder_report.append((folder["label"], completion["completion"]))

	# Show a short status message
	if all([c == 100 for n, c in itertools.chain(folder_report, device_report)]):
		print('Syncthing:', f'Completely synchronized.')
	else:
		incompletes = ((n, c) for n, c in itertools.chain(folder_report, device_report) if c != 100)
		print('Syncthing:', 'Incomplete.\n ', '\n  '.join(f'{n}: {c:.2f}%' for n, c in incompletes))
		print(f'Details at {HOST}')

if __name__ == '__main__':
	main()
	sys.exit(0)