Syncthing Monitoring via API

This commit is contained in:
Shailaja Kumari 2024-04-26 12:36:18 +05:30
parent f43e9d967b
commit da5c266da9
Signed by untrusted user: shailaja
GPG Key ID: 2B9455CAFBC4D75A
1 changed files with 73 additions and 0 deletions

73
syncthing_sync.py Normal file
View File

@ -0,0 +1,73 @@
import os
import json
import requests
import time
def get_api_key(config_file):
""" Retrieve the API key from the local Syncthing configuration file. """
try:
with open(config_file, 'r') as file:
config_data = json.load(file)
return config_data['apikey']
except FileNotFoundError:
raise Exception("Configuration file not found.")
except KeyError:
raise Exception("API key not found in the configuration file.")
def syncthing_request(url, api_key, method='GET', payload=None):
""" Generic function for Syncthing API requests. """
headers = {'X-Api-Key': api_key}
if method == 'GET':
response = requests.get(url, headers=headers)
elif method == 'POST':
response = requests.post(url, headers=headers, json=payload)
else:
raise ValueError("Unsupported HTTP method.")
response.raise_for_status()
return response.json()
def check_folder_idle(api_url, folder_id, api_key):
""" Check if the specified folder is idle. """
status_url = f"{api_url}/rest/db/status?folder={folder_id}"
status = syncthing_request(status_url, api_key)
return status['state'] == 'idle'
def long_poll_events(api_url, last_event_id, api_key):
""" Long poll the events endpoint filtering by the last known event ID. """
events_url = f"{api_url}/rest/events?since={last_event_id}&timeout=60"
return syncthing_request(events_url, api_key)
def main():
api_url = os.getenv('SYNCTHING_API_URL', 'http://127.0.0.1:8384')
folder_id = os.getenv('SYNCTHING_FOLDER_ID')
config_file = os.getenv('SYNCTHING_CONFIG_FILE', DEFAULT_ST_CONFIG_LOCATION)
if not folder_id:
raise ValueError("Folder ID must be provided as an environment variable.")
api_key = get_api_key(config_file)
# Start by getting the latest event ID
current_events = syncthing_request(f"{api_url}/rest/events?limit=1", api_key)
last_event_id = current_events[0]['id'] if current_events else 0
while True:
if check_folder_idle(api_url, folder_id, api_key):
print("Folder is idle.")
break
# Process events related to the folder
events = long_poll_events(api_url, last_event_id, api_key)
for event in events:
print("Processing event:", event)
if event['type'] == 'StateChanged' and event['data']['folder'] == folder_id:
last_event_id = event['id']
if event['data']['to'] == 'idle':
print("Folder transitioned to idle.")
break
time.sleep(1)
if __name__ == '__main__':
main()