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'
|
|
|
|
|
|
|
|
|
2021-01-29 10:19:53 +00:00
|
|
|
class EtcdClient:
|
2021-01-29 13:55:51 +00:00
|
|
|
def __init__(self, host, port):
|
2021-01-29 10:56:51 +00:00
|
|
|
self.etcd = etcd3.client(host=host, port=port)
|
2021-01-29 08:28:35 +00:00
|
|
|
|
2021-01-29 10:56:51 +00:00
|
|
|
def load_cluster_info(self):
|
2021-01-29 12:56:07 +00:00
|
|
|
raw_value = self.etcd.get(CLUSTER_INFO_KEY)[0]
|
2021-01-29 10:56:51 +00:00
|
|
|
if raw_value is None:
|
|
|
|
return {'devices': []}
|
|
|
|
return json.loads(raw_value)
|
2021-01-29 08:28:35 +00:00
|
|
|
|
2021-01-29 10:56:51 +00:00
|
|
|
@retry
|
2021-01-31 09:45:07 +00:00
|
|
|
def add_device_to_cluster(self, device_id, hostname, address):
|
2021-01-29 10:56:51 +00:00
|
|
|
with self.etcd.lock('syncthing_monitor'):
|
|
|
|
cluster_info = self.load_cluster_info()
|
2021-01-29 08:28:35 +00:00
|
|
|
|
2021-01-29 12:56:07 +00:00
|
|
|
if any(device_id in device['id'] for device in cluster_info['devices']):
|
|
|
|
return
|
|
|
|
|
|
|
|
new_device = {
|
|
|
|
'id': device_id,
|
2021-01-31 09:45:07 +00:00
|
|
|
'hostname': hostname,
|
|
|
|
'address': address
|
2021-01-29 12:56:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
cluster_info['devices'].append(new_device)
|
2021-01-29 09:59:59 +00:00
|
|
|
|
2021-01-29 10:56:51 +00:00
|
|
|
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))
|
2021-01-29 09:59:59 +00:00
|
|
|
|
2021-01-29 10:19:53 +00:00
|
|
|
@retry
|
2021-01-29 10:56:51 +00:00
|
|
|
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
|
2021-01-29 12:56:07 +00:00
|
|
|
|
|
|
|
def register_device_update_handler(self, device_update_handler):
|
|
|
|
self.etcd.add_watch_callback(CLUSTER_INFO_KEY, device_update_handler)
|