idlers-agent/server_manager.py
2024-06-03 14:12:48 +05:30

46 lines
1.7 KiB
Python

import json
import requests
import logging
class ServerManager:
def __init__(self, host, api_key):
self.host = host
self.api_key = api_key
self.headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + self.api_key,
}
logging.basicConfig(level=logging.INFO)
def send_request(self, method, endpoint, data=None):
url = self.host + endpoint
payload = json.dumps(data) if data else None
try:
response = requests.request(method, url, headers=self.headers, data=payload)
response.raise_for_status()
return response.json() if method == 'GET' else response.text
except requests.exceptions.RequestException as e:
logging.error(f"Request failed with {e}")
raise
def get_existing_servers(self):
return self.send_request('GET', '/api/servers')
def create_server(self, post_data):
logging.info("Creating server...")
return self.send_request('POST', '/api/servers', post_data)
def update_server(self, post_data, server_id):
# remove following keys from post_data
for key in ['ssh_port', 'ip1', 'currency', 'price', 'payment_term', 'next_due_date']:
post_data.pop(key, None)
logging.info(f"Updating server with id {server_id}...")
return self.send_request('PUT', '/api/servers/' + str(server_id), post_data)
def existing_server_id(self, post_data):
existing_servers = self.get_existing_servers()
for server in existing_servers:
if server['hostname'] == post_data['hostname']:
return server['id']
return None