45 lines
1.4 KiB
Python
45 lines
1.4 KiB
Python
import json
|
|
|
|
import etcd3 as etcd3
|
|
from retrying import retry
|
|
|
|
CLUSTER_INFO_KEY = '/syncthing_monitor/cluster_info'
|
|
|
|
|
|
class EtcdClient:
|
|
def __init__(self, host, port):
|
|
self.etcd = etcd3.client(host=host, port=port)
|
|
|
|
def load_cluster_info(self):
|
|
raw_value = self.etcd.get(CLUSTER_INFO_KEY)[0]
|
|
if raw_value is None:
|
|
return {'devices': []}
|
|
return json.loads(raw_value)
|
|
|
|
@retry
|
|
def add_device_to_cluster(self, device_id, public_host):
|
|
with self.etcd.lock('syncthing_monitor'):
|
|
cluster_info = self.load_cluster_info()
|
|
|
|
if any(device_id in device['id'] for device in cluster_info['devices']):
|
|
return
|
|
|
|
new_device = {
|
|
'id': device_id,
|
|
'hostname': public_host
|
|
}
|
|
|
|
cluster_info['devices'].append(new_device)
|
|
|
|
print("Updating etcd value for '{0}': {1}".format(CLUSTER_INFO_KEY, json.dumps(cluster_info)))
|
|
self.etcd.put(CLUSTER_INFO_KEY, json.dumps(cluster_info))
|
|
|
|
@retry
|
|
def get_device_list(self):
|
|
device_list = self.load_cluster_info()['devices']
|
|
print("Obtained device_list devices from etcd: {0}".format(json.dumps(device_list)))
|
|
return device_list
|
|
|
|
def register_device_update_handler(self, device_update_handler):
|
|
self.etcd.add_watch_callback(CLUSTER_INFO_KEY, device_update_handler)
|