syncthing-monitor/syncthing_monitor/etcd_client.py

44 lines
1.3 KiB
Python
Raw Normal View History

2021-01-29 08:28:35 +00:00
import json
import etcd3 as etcd3
from retrying import retry
CLUSTER_INFO_KEY = '/syncthing_monitor/cluster_info'
class EtcdClient:
def __init__(self, host):
self.host = host
2021-01-29 08:28:35 +00:00
@retry
def append_device_id(self, device_id, port=2379):
cluster_info = {'devices': []}
2021-01-29 08:28:35 +00:00
etcd = etcd3.client(host=self.host, port=port)
2021-01-29 08:28:35 +00:00
with etcd.lock('syncthing_monitor'):
raw_value = etcd.get(CLUSTER_INFO_KEY)[0]
2021-01-29 08:28:35 +00:00
if raw_value is not None:
cluster_info = json.loads(raw_value)
2021-01-29 08:28:35 +00:00
if not any(device_id in element for element in cluster_info['devices']):
cluster_info['devices'].append(device_id)
2021-01-29 09:59:59 +00:00
print("Updating etcd value for '{0}': {1}".format(CLUSTER_INFO_KEY, json.dumps(cluster_info)), flush=True)
etcd.put(CLUSTER_INFO_KEY, json.dumps(cluster_info))
2021-01-29 09:59:59 +00:00
@retry
def get_device_list(self, port=2379):
cluster_info = {'devices': []}
2021-01-29 09:59:59 +00:00
etcd = etcd3.client(host=self.host, port=port)
2021-01-29 09:59:59 +00:00
raw_value = etcd.get(CLUSTER_INFO_KEY)[0]
2021-01-29 09:59:59 +00:00
if raw_value is not None:
cluster_info = json.loads(raw_value)
2021-01-29 09:59:59 +00:00
print("Obtained cluster_info devices from etcd: {0}".format(json.dumps(cluster_info['devices'])))
return cluster_info['devices']