refactor code

This commit is contained in:
Swapnil 2024-06-03 14:12:48 +05:30
parent d30d6418e1
commit 305f001d42
Signed by: swapnil
GPG Key ID: 58029C48BB100574
3 changed files with 155 additions and 166 deletions

185
main.py
View File

@ -1,185 +1,38 @@
import os import os
import time import logging
import json
import requests
import psutil from server_manager import ServerManager
import tldextract from server_data import ServerData
import dns.resolver
# get ram and disk in MB and GB respectively def validate_env_vars():
def get_ram_and_disk():
ram = psutil.virtual_memory().total >> 20
disk = psutil.disk_usage('/').total >> 30
return ram, disk
def get_cpu_count():
return psutil.cpu_count()
def get_bandwidth():
return 2000
def get_hostname():
return os.uname().nodename
def get_public_ip():
try:
response = requests.get('https://api.ipify.org')
response.raise_for_status()
return response.text
except:
return '127.0.0.1'
def get_domain():
extracted = tldextract.extract(get_hostname())
return "{}.{}".format(extracted.domain, extracted.suffix)
def get_nameservers():
try:
answers = dns.resolver.resolve(get_domain(), 'NS')
return [str(rdata) for rdata in answers]
except Exception as e:
return []
def get_os():
return 27
# Create POST data
def create_post_data():
ram, disk = get_ram_and_disk()
nameservers = get_nameservers()
post_data = {
"server_type": 1,
"os_id": get_os(),
"provider_id": 10,
"location_id": 15,
"ssh_port": 22,
"ram": ram >> 10, # convert to GB
"ram_as_mb": ram, # in MB
"disk": disk, # in GB
"disk_as_gb": disk, # in GB
"cpu": get_cpu_count(),
"bandwidth": get_bandwidth(),
"was_promo": 1,
"active": 1,
"show_public": 0,
"owned_since": "2022-01-01",
"ram_type": "GB",
"disk_type": "GB",
"currency": "USD",
"price": 4,
"payment_term": 1,
"hostname": get_hostname(),
"next_due_date": "2022-02-01",
# Above ones are required fields, below are optional
"ns1": nameservers[0] if nameservers else "",
"ns2": nameservers[1] if len(nameservers) > 1 else "",
# "has_yabs": 0,
"ip1": get_public_ip(), # empty string or None gives 400 Bad Request
# "as_usd": 4,
# "usd_per_month": 4,
}
return post_data
def get_existing_servers(host, api_key):
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + api_key,
}
try:
response = requests.get(host, headers=headers)
response.raise_for_status()
return response.json()
except:
return []
def existing_server_id(existing_servers, post_data):
for server in existing_servers:
if server['hostname'] == post_data['hostname']:
return server['id']
return None
def create_server(host, api_key, post_data):
# Create the headers for the request
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + api_key,
}
payload = json.dumps(post_data)
# Send the POST request
try:
response = requests.post(host, headers=headers, data=payload)
response.raise_for_status()
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
print ("Something went wrong:",err)
else:
print(response.text)
def update_server(host, api_key, post_data, server_id):
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + api_key,
}
# remove following keys from post_data
# ssh_port, ip1, currency, price, payment_term, next_due_date
post_data.pop('ssh_port', None)
post_data.pop('ip1', None)
post_data.pop('currency', None)
post_data.pop('price', None)
post_data.pop('payment_term', None)
post_data.pop('next_due_date', None)
payload = json.dumps(post_data)
try:
response = requests.put(host + '/' + str(server_id), headers=headers, data=payload)
response.raise_for_status()
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
print ("Something went wrong:",err)
else:
print(response.text)
def send_post_request():
# Get the API key and HOST from environment variables
api_key = os.getenv('API_KEY') api_key = os.getenv('API_KEY')
host = os.getenv('HOST') host = os.getenv('HOST')
if not api_key: if not api_key:
raise Exception('API_KEY not found in environment variables') raise Exception('API_KEY not found in environment variables')
if not host: if not host:
raise Exception('HOST not found in environment variables') raise Exception('HOST not found in environment variables')
return host, api_key
# Create the data for the post request def main():
post_data = create_post_data() logging.basicConfig(level=logging.INFO)
# Get the existing servers host, api_key = validate_env_vars()
existing_servers = get_existing_servers(host, api_key)
server_data = ServerData()
post_data = server_data.create_post_data()
server_manager = ServerManager(host, api_key)
# Check if the server already exists # Check if the server already exists
server_id = existing_server_id(existing_servers, post_data) server_id = server_manager.existing_server_id(post_data)
# If the server exists, update it # If the server exists, update it
if server_id: if server_id:
print('Server already exists with id: {}, Updating...'.format(server_id)) logging.info('Server already exists with id: {}, Updating...'.format(server_id))
update_server(host, api_key, post_data, server_id) logging.info(server_manager.update_server(post_data, server_id))
else: else:
print('Server does not exist, Creating...') logging.info('Server does not exist, Creating...')
create_server(host, api_key, post_data) logging.info(server_manager.create_server(post_data))
if __name__ == '__main__': if __name__ == '__main__':
send_post_request() main()

90
server_data.py Normal file
View File

@ -0,0 +1,90 @@
import os
import requests
import psutil
import tldextract
import dns.resolver
import logging
class ServerData:
def __init__(self):
self.hostname = os.uname().nodename
self.public_ip = self.get_public_ip()
self.domain = self.get_domain()
self.nameservers = self.get_nameservers()
logging.basicConfig(level=logging.INFO)
def get_ram_and_disk(self):
ram = psutil.virtual_memory().total >> 20
disk = psutil.disk_usage('/').total >> 30
logging.info(f"RAM: {ram}MB, Disk: {disk}GB")
return ram, disk
def get_cpu_count(self):
cpu_count = psutil.cpu_count()
logging.info(f"CPU Count: {cpu_count}")
return cpu_count
def get_bandwidth(self):
bandwidth = 2000
logging.info(f"Bandwidth: {bandwidth}")
return bandwidth
def get_public_ip(self):
try:
response = requests.get('https://api.ipify.org')
response.raise_for_status()
return response.text
except requests.exceptions.RequestException as e:
logging.error(f"Failed to get public IP: {e}")
return '127.0.0.1'
def get_domain(self):
extracted = tldextract.extract(self.hostname)
domain = "{}.{}".format(extracted.domain, extracted.suffix)
logging.info(f"Domain: {domain}")
return domain
def get_nameservers(self):
try:
answers = dns.resolver.resolve(self.domain, 'NS')
return [str(rdata) for rdata in answers]
except Exception as e:
logging.error(f"Failed to get nameservers: {e}")
return []
def get_os(self):
os_id = 27
logging.info(f"OS ID: {os_id}")
return os_id
def create_post_data(self):
ram, disk = self.get_ram_and_disk()
post_data = {
"server_type": 1,
"os_id": self.get_os(),
"provider_id": 10,
"location_id": 15,
"ssh_port": 22,
"ram": ram >> 10, # convert to GB
"ram_as_mb": ram, # in MB
"disk": disk, # in GB
"disk_as_gb": disk, # in GB
"cpu": self.get_cpu_count(),
"bandwidth": self.get_bandwidth(),
"was_promo": 1,
"active": 1,
"show_public": 0,
"owned_since": "2022-01-01",
"ram_type": "GB",
"disk_type": "GB",
"currency": "USD",
"price": 4,
"payment_term": 1,
"hostname": self.hostname,
"next_due_date": "2022-02-01",
"ns1": self.nameservers[0] if self.nameservers else "",
"ns2": self.nameservers[1] if len(self.nameservers) > 1 else "",
"ip1": self.public_ip,
}
logging.info("Post data created")
return post_data

46
server_manager.py Normal file
View File

@ -0,0 +1,46 @@
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