2019-08-12 13:35:35 +00:00
|
|
|
from typing import List
|
|
|
|
|
2019-07-30 13:13:05 +00:00
|
|
|
from .helpers import SpecificEtcdEntryBase
|
|
|
|
from .etcd3_wrapper import EtcdEntry
|
|
|
|
from datetime import datetime
|
2019-08-12 13:35:35 +00:00
|
|
|
from os.path import join
|
2019-07-30 13:13:05 +00:00
|
|
|
|
|
|
|
|
|
|
|
class HostStatus(object):
|
|
|
|
alive = "ALIVE"
|
|
|
|
dead = "DEAD"
|
|
|
|
|
|
|
|
|
|
|
|
class HostEntry(SpecificEtcdEntryBase):
|
|
|
|
def __init__(self, e: EtcdEntry):
|
|
|
|
self.specs = dict()
|
|
|
|
self.hostname = ""
|
|
|
|
self.status = ""
|
|
|
|
self.last_heartbeat = ""
|
|
|
|
|
|
|
|
super().__init__(e)
|
|
|
|
|
|
|
|
def update_heartbeat(self):
|
|
|
|
self.status = HostStatus.alive
|
|
|
|
self.last_heartbeat = datetime.utcnow().isoformat()
|
|
|
|
|
|
|
|
def is_alive(self):
|
|
|
|
last_heartbeat = datetime.fromisoformat(self.last_heartbeat)
|
|
|
|
delta = datetime.utcnow() - last_heartbeat
|
|
|
|
if delta.total_seconds() > 60:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
def declare_dead(self):
|
|
|
|
self.status = HostStatus.dead
|
|
|
|
self.last_heartbeat = datetime.utcnow().isoformat()
|
|
|
|
|
|
|
|
|
|
|
|
class HostPool(object):
|
|
|
|
def __init__(self, etcd_client, host_prefix):
|
|
|
|
self.client = etcd_client
|
|
|
|
self.prefix = host_prefix
|
|
|
|
|
|
|
|
@property
|
2019-08-12 13:35:35 +00:00
|
|
|
def hosts(self) -> List[HostEntry]:
|
2019-07-30 13:13:05 +00:00
|
|
|
_hosts = self.client.get_prefix(self.prefix, value_in_json=True)
|
|
|
|
return [HostEntry(host) for host in _hosts]
|
|
|
|
|
|
|
|
def get(self, key):
|
2019-08-12 13:35:35 +00:00
|
|
|
if not key.startswith(self.prefix):
|
|
|
|
key = join(self.prefix, key)
|
2019-07-30 13:13:05 +00:00
|
|
|
v = self.client.get(key, value_in_json=True)
|
2019-08-12 13:35:35 +00:00
|
|
|
if v:
|
|
|
|
return HostEntry(v)
|
2019-07-30 13:13:05 +00:00
|
|
|
|
|
|
|
def put(self, obj: HostEntry):
|
|
|
|
self.client.put(obj.key, obj.value, value_in_json=True)
|
|
|
|
|
|
|
|
def by_status(self, status, _hosts=None):
|
|
|
|
if _hosts is None:
|
|
|
|
_hosts = self.hosts
|
|
|
|
return list(filter(lambda x: x.status == status, _hosts))
|