ucloud_common/ucloud_common/host.py

70 lines
1.9 KiB
Python
Raw Normal View History

2019-10-23 12:28:42 +00:00
import time
from typing import List
2019-07-30 13:13:05 +00:00
from datetime import datetime
from os.path import join
2019-07-30 13:13:05 +00:00
2019-09-14 15:26:44 +00:00
from .helpers import SpecificEtcdEntryBase
2019-07-30 13:13:05 +00:00
2019-09-11 13:01:15 +00:00
class HostStatus:
2019-09-14 15:26:44 +00:00
"""Possible Statuses of ucloud host."""
2019-07-30 13:13:05 +00:00
alive = "ALIVE"
dead = "DEAD"
class HostEntry(SpecificEtcdEntryBase):
2019-09-14 15:26:44 +00:00
"""Represents Host Entry Structure and its supporting methods."""
def __init__(self, e):
self.specs = None # type: dict
self.hostname = None # type: str
self.status = None # type: str
self.last_heartbeat = None # type: str
super().__init__(e)
2019-09-11 13:01:15 +00:00
2019-07-30 13:13:05 +00:00
def update_heartbeat(self):
self.status = HostStatus.alive
2019-10-23 12:28:42 +00:00
self.last_heartbeat = time.strftime("%Y-%m-%d %H:%M:%S")
2019-07-30 13:13:05 +00:00
def is_alive(self):
2019-10-23 12:28:42 +00:00
last_heartbeat = datetime.strptime(self.last_heartbeat, "%Y-%m-%d %H:%M:%S")
delta = datetime.now() - last_heartbeat
2019-07-30 13:13:05 +00:00
if delta.total_seconds() > 60:
return False
return True
def declare_dead(self):
self.status = HostStatus.dead
2019-10-23 12:28:42 +00:00
self.last_heartbeat = time.strftime("%Y-%m-%d %H:%M:%S")
2019-07-30 13:13:05 +00:00
2019-09-11 13:01:15 +00:00
class HostPool:
2019-07-30 13:13:05 +00:00
def __init__(self, etcd_client, host_prefix):
self.client = etcd_client
self.prefix = host_prefix
@property
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):
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)
if v:
return HostEntry(v)
2019-09-11 13:01:15 +00:00
return None
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
2019-09-14 15:26:44 +00:00
return list(filter(lambda x: x.status == status, _hosts))