Last active
January 6, 2022 05:13
-
-
Save paderinandrey/02f2ce694e98cf96df2dc41eb3570171 to your computer and use it in GitHub Desktop.
Rebrain:Python. Task-15
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import os | |
import json | |
from logger import logging | |
class APIClient: | |
def __init__(self, server_addr): | |
self.server_addr = server_addr | |
self.hostname = "hostname" | |
self.ip = self.safe_request("get", 'https://api.my-ip.io/ip').text | |
self.desc = os.environ.get("DESC", "") | |
def register(self): | |
if self.is_registered == True: | |
return | |
logging.info("Register client to API Server") | |
payload = { | |
'ip_address': self.ip, | |
'name': self.hostname, | |
'description': self.desc, | |
'server_is_active': True, | |
} | |
r = self.safe_request( | |
"post", | |
f'http://{self.server_addr}/api/servers/add', | |
payload | |
) | |
self.server_id = json.loads(r.text)["id"] | |
def safe_request(self, method, url, payload={}): | |
tries = 3 | |
for i in range(tries): | |
try: | |
r = requests.request(method, url, data=payload, timeout=3) | |
r.raise_for_status() | |
return r | |
except requests.exceptions.RequestException as err: | |
logging.error(err) | |
if i < tries - 1: | |
print(f'Trying send data...#{i+1}') | |
continue | |
else: | |
raise RuntimeError('Failed connect to server') from err | |
def send_data(self, data={}): | |
logging.info("Send metrics to API Server") | |
payload = {'server': self.server_id, | |
'data': json.dumps(data, indent=4)} | |
self.safe_request( | |
"post", | |
f'http://{self.server_addr}/api/servers/{self.server_id}/metrics', | |
payload | |
) | |
def is_registered(self): | |
data = self.safe_request( | |
"get", f'http://{self.server_addr}/api/servers/').text | |
for host in json.loads(data): | |
if host['name'] == self.hostname and host['ip_address'] == self.ip: | |
self.server_id = host['id'] | |
return True | |
return False |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import psutil | |
def network_info(): | |
return [{ | |
'name': name, | |
'interface': network_status(interface.isup), | |
'mtu': interface.mtu | |
} for name, interface in psutil.net_if_stats().items()] | |
def disk_info(): | |
return [{ | |
'disk': disk.device, | |
'mountpoint': disk.mountpoint, | |
'file_system_type': disk.fstype, | |
**disk_usage(disk) | |
} for disk in psutil.disk_partitions()] | |
def disk_usage(disk): | |
data = psutil.disk_usage(disk.mountpoint) | |
return { | |
'total': data.total, | |
'used': data.used | |
} | |
def memory_info(): | |
memory = psutil.virtual_memory() | |
return { | |
'memory_total': memory.total, | |
'memory_used': memory.used, | |
'memory_percent': memory.percent | |
} | |
def cpu_info(): | |
freq = psutil.cpu_freq() | |
return { | |
'cpu_cores': psutil.cpu_count(), | |
'cpu_physical_cores': psutil.cpu_count(logical=False), | |
'cpu_freqency': { | |
'min': freq.min, | |
'max': freq.max, | |
'current': freq.current | |
} | |
} | |
def load_average_info(): | |
keys = ['1 min', '5 min', '15 min'] | |
values = list(psutil.getloadavg()) | |
return dict(zip(keys, values)) | |
def info(): | |
host = os.uname() | |
return { | |
'host_information': {'sysname': host.sysname, 'hostname': host.nodename}, | |
'network': network_info(), | |
'disk': disk_info(), | |
'memory': memory_info(), | |
'cpu': cpu_info(), | |
'load_average': load_average_info() | |
} | |
def network_status(status): | |
return {True: "up", False: "down"}[status] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
logging.basicConfig( | |
filename='log_file.log', | |
format='%(asctime)s %(levelname)s %(message)s', | |
datefmt='%b %d %H:%M:%S', | |
level=logging.INFO | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from host_info import info | |
from api_client import APIClient | |
from logger import logging | |
import time | |
try: | |
logging.info("🚀 Start client") | |
client = APIClient('127.0.0.1:8000') | |
client.register() | |
while True: | |
client.send_data(info()) | |
time.sleep(60) | |
except Exception: | |
print("Oops! Program ended with error. See details in the log file.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment