forked from Sysdeploy/idlers-agent
Compare commits
5 Commits
Author | SHA1 | Date | |
---|---|---|---|
75744e0010 | |||
2c19f2eefc | |||
ea4675a56c | |||
bd6ecc3519 | |||
54d0b0decd |
143
agent.py
143
agent.py
@ -5,6 +5,7 @@ import json
|
|||||||
import http.client
|
import http.client
|
||||||
import subprocess
|
import subprocess
|
||||||
import re
|
import re
|
||||||
|
import shutil
|
||||||
|
|
||||||
NON_UPDATABLE_KEYS = [
|
NON_UPDATABLE_KEYS = [
|
||||||
'server_type',
|
'server_type',
|
||||||
@ -28,6 +29,8 @@ class ServerData:
|
|||||||
self.hostname = os.uname().nodename
|
self.hostname = os.uname().nodename
|
||||||
self.public_ip = self.get_public_ip()
|
self.public_ip = self.get_public_ip()
|
||||||
self.dmidecode_data = self.parse_dmidecode_output()
|
self.dmidecode_data = self.parse_dmidecode_output()
|
||||||
|
self.hdparm_data = self.parse_hdparm_output()
|
||||||
|
self.nvme_data = self.parse_nvme_devices()
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
|
||||||
def parse_dmidecode_output(self):
|
def parse_dmidecode_output(self):
|
||||||
@ -91,14 +94,116 @@ class ServerData:
|
|||||||
pass
|
pass
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
def parse_hdparm_output(self):
|
||||||
|
devices = {}
|
||||||
|
|
||||||
|
# Check if hdparm exists
|
||||||
|
if shutil.which('hdparm') is None:
|
||||||
|
logging.error("hdparm not found")
|
||||||
|
return devices
|
||||||
|
|
||||||
|
# Get the list of devices
|
||||||
|
try:
|
||||||
|
device_list = [device for device in os.listdir('/sys/block') if device.startswith('sd')]
|
||||||
|
except OSError as e:
|
||||||
|
logging.error("Failed to get device list: {}".format(e))
|
||||||
|
return devices
|
||||||
|
|
||||||
|
for device in device_list:
|
||||||
|
# Only get details of devices that start with 'sd': sda, sdb, etc.
|
||||||
|
if not device.startswith('sd'):
|
||||||
|
continue
|
||||||
|
|
||||||
|
device = '/dev/' + device
|
||||||
|
try:
|
||||||
|
# Get the output
|
||||||
|
output = subprocess.check_output(['hdparm', '-I', device], stderr=subprocess.STDOUT, universal_newlines=True)
|
||||||
|
except subprocess.CalledProcessError as e:
|
||||||
|
logging.error("Failed to get hdparm output for {}: {}".format(device, e))
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Parse the output
|
||||||
|
details = {}
|
||||||
|
details['model_number'] = re.search(r'Model Number:\s*(.*)', output).group(1)
|
||||||
|
details['serial_number'] = re.search(r'Serial Number:\s*(.*)', output).group(1)
|
||||||
|
details['firmware_revision'] = re.search(r'Firmware Revision:\s*(.*)', output).group(1)
|
||||||
|
details['transport'] = re.search(r'Transport:\s*(.*)', output).group(1)
|
||||||
|
details['checksum'] = re.search(r'Checksum:\s*(.*)', output).group(1)
|
||||||
|
details['buffer_size'] = re.search(r'cache/buffer size\s*=\s*(.*)', output).group(1)
|
||||||
|
details['form_factor'] = re.search(r'Form Factor:\s*(.*)', output).group(1)
|
||||||
|
|
||||||
|
devices[device] = details
|
||||||
|
|
||||||
|
return devices
|
||||||
|
|
||||||
|
def parse_nvme_devices(self):
|
||||||
|
'''
|
||||||
|
Example nvme id-ctrl output:
|
||||||
|
|
||||||
|
NVME Identify Controller:
|
||||||
|
vid : 0x144d
|
||||||
|
ssvid : 0x144d
|
||||||
|
sn : S3RVNA0K502408F
|
||||||
|
mn : Samsung SSD 970 EVO Plus 1TB
|
||||||
|
fr : 2B2QEXM7
|
||||||
|
rab : 2
|
||||||
|
....
|
||||||
|
'''
|
||||||
|
devices = {}
|
||||||
|
|
||||||
|
# Check if nvme exists
|
||||||
|
if shutil.which('nvme') is None:
|
||||||
|
print("nvme not found")
|
||||||
|
return devices
|
||||||
|
|
||||||
|
# Get the list of nvme devices starting with 'nvme'
|
||||||
|
nvme_devices = [device for device in os.listdir('/sys/block') if device.startswith('nvme')]
|
||||||
|
|
||||||
|
for device in nvme_devices:
|
||||||
|
device_path = '/dev/' + device
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Get the output of nvme id-ctrl command
|
||||||
|
output = subprocess.check_output(['nvme', 'id-ctrl', device_path], stderr=subprocess.STDOUT, universal_newlines=True)
|
||||||
|
except subprocess.CalledProcessError as e:
|
||||||
|
print(f"Failed to get nvme id-ctrl output for {device_path}: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Split the output into lines
|
||||||
|
lines = output.split('\n')
|
||||||
|
|
||||||
|
# Parse each line
|
||||||
|
device_info = {}
|
||||||
|
for line in lines:
|
||||||
|
if ':' in line:
|
||||||
|
key, value = line.split(':', 1)
|
||||||
|
device_info[key.strip()] = value.strip()
|
||||||
|
|
||||||
|
devices[device_path] = device_info
|
||||||
|
|
||||||
|
return devices
|
||||||
|
|
||||||
def get_ram_and_disk(self):
|
def get_ram_and_disk(self):
|
||||||
|
# RAM information
|
||||||
with open('/proc/meminfo', 'r') as f:
|
with open('/proc/meminfo', 'r') as f:
|
||||||
meminfo = f.read()
|
meminfo = f.read()
|
||||||
ram = int([x for x in meminfo.split('\n') if 'MemTotal' in x][0].split()[1]) // 1024
|
ram = int([x for x in meminfo.split('\n') if 'MemTotal' in x][0].split()[1]) // 1024
|
||||||
with open('/proc/diskstats', 'r') as f:
|
# Disk space information
|
||||||
diskstats = f.read()
|
disk = 0
|
||||||
disk = sum(int(x.split()[9]) for x in diskstats.split('\n') if x) * 512 // 10**9
|
for device in os.listdir('/sys/block'):
|
||||||
logging.info(f"RAM: {ram}MB, Disk: {disk}GB")
|
device_path = '/sys/block/{}/device'.format(device)
|
||||||
|
size_path = '/sys/block/{}/size'.format(device)
|
||||||
|
if not os.path.islink(device_path):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
with open(size_path, 'r') as f:
|
||||||
|
size = int(f.read().strip())
|
||||||
|
disk += size
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
disk = disk * 512 // (1024**3) # convert to GB
|
||||||
|
logging.info("RAM: {}MB, Disk: {}GB".format(ram, disk))
|
||||||
return ram, disk
|
return ram, disk
|
||||||
|
|
||||||
def get_cpu_count(self):
|
def get_cpu_count(self):
|
||||||
@ -112,12 +217,12 @@ class ServerData:
|
|||||||
with open('/proc/cpuinfo', 'r') as f:
|
with open('/proc/cpuinfo', 'r') as f:
|
||||||
cpuinfo = f.read()
|
cpuinfo = f.read()
|
||||||
cpu_count = cpuinfo.count('processor')
|
cpu_count = cpuinfo.count('processor')
|
||||||
logging.info(f"CPU Count: {cpu_count}")
|
logging.info("CPU Count: {}".format(cpu_count))
|
||||||
return cpu_count
|
return cpu_count
|
||||||
|
|
||||||
def get_bandwidth(self):
|
def get_bandwidth(self):
|
||||||
bandwidth = 2000
|
bandwidth = 2000
|
||||||
logging.info(f"Bandwidth: {bandwidth}")
|
logging.info("Bandwidth: {}".format(bandwidth))
|
||||||
return bandwidth
|
return bandwidth
|
||||||
|
|
||||||
def get_public_ip(self):
|
def get_public_ip(self):
|
||||||
@ -125,12 +230,12 @@ class ServerData:
|
|||||||
response = urllib.request.urlopen('https://api.ipify.org')
|
response = urllib.request.urlopen('https://api.ipify.org')
|
||||||
return response.read().decode()
|
return response.read().decode()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"Failed to get public IP: {e}")
|
logging.error("Failed to get public IP: {}".format(e))
|
||||||
return '127.0.0.1'
|
return '127.0.0.1'
|
||||||
|
|
||||||
def get_os(self):
|
def get_os(self):
|
||||||
os_id = 27
|
os_id = 27
|
||||||
logging.info(f"OS ID: {os_id}")
|
logging.info("OS ID: {}".format(os_id))
|
||||||
return os_id
|
return os_id
|
||||||
|
|
||||||
def create_post_data(self):
|
def create_post_data(self):
|
||||||
@ -191,9 +296,21 @@ class ServerData:
|
|||||||
serial_number = ram.get('Serial Number', 'Unknown')
|
serial_number = ram.get('Serial Number', 'Unknown')
|
||||||
ram_type = ram.get('Type', 'Unknown')
|
ram_type = ram.get('Type', 'Unknown')
|
||||||
ram_details.append("Size: {}, Speed: {} @ {}, ECC: {}, Serial Number: {}, Type: {}".format(size, speed, configured_speed, ecc, serial_number, ram_type))
|
ram_details.append("Size: {}, Speed: {} @ {}, ECC: {}, Serial Number: {}, Type: {}".format(size, speed, configured_speed, ecc, serial_number, ram_type))
|
||||||
|
|
||||||
|
# SATA Storage media
|
||||||
|
sata_details = []
|
||||||
|
for device, details in self.hdparm_data.items():
|
||||||
|
sata_details.append("Device: {}, Model: {}, Serial: {}, Checksum: {}, Buffer Size: {}, Form Factor: {}".format(
|
||||||
|
device, details['model_number'], details['serial_number'], details['checksum'], details['buffer_size'], details['form_factor']))
|
||||||
|
|
||||||
|
# NVMe Storage media
|
||||||
|
nvme_details = []
|
||||||
|
for device, details in self.nvme_data.items():
|
||||||
|
nvme_details.append("Device: {}, Model: {}, Serial: {}, Firmware: {}".format(
|
||||||
|
device, details.get('mn', 'Unknown'), details.get('sn', 'Unknown'), details.get('fr', 'Unknown')))
|
||||||
|
|
||||||
note = "Chassis Model: {} | Serial Number: {} ||| Processor Model: {} | Count: {} ||| RAM Details: {}".format(
|
note = "Chassis Model: {} | Serial Number: {} ||| Processor Model: {} | Count: {} ||| RAM Details: {} ||| SATA Details {} ||| NVME Details {}".format(
|
||||||
chassis_model, chassis_serial, processor_model, processor_count, ' | '.join(ram_details))
|
chassis_model, chassis_serial, processor_model, processor_count, ' | '.join(ram_details), ' | '.join(sata_details), ' | '.join(nvme_details))
|
||||||
|
|
||||||
note_data = {
|
note_data = {
|
||||||
'note': note,
|
'note': note,
|
||||||
@ -223,7 +340,7 @@ class ServerManager:
|
|||||||
else:
|
else:
|
||||||
return response.read().decode()
|
return response.read().decode()
|
||||||
except urllib.error.HTTPError as e:
|
except urllib.error.HTTPError as e:
|
||||||
logging.error(f"Request failed with {e}")
|
logging.error("Request failed with {}".format(e))
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def get_existing_servers(self):
|
def get_existing_servers(self):
|
||||||
@ -237,7 +354,7 @@ class ServerManager:
|
|||||||
return self.send_request('POST', '/api/notes', post_data)
|
return self.send_request('POST', '/api/notes', post_data)
|
||||||
|
|
||||||
def update_note(self, post_data, service_id):
|
def update_note(self, post_data, service_id):
|
||||||
logging.info(f"Updating note with id {service_id}...")
|
logging.info("Updating note with id {}...".format(service_id))
|
||||||
return self.send_request('PUT', '/api/notes/' + str(service_id), post_data)
|
return self.send_request('PUT', '/api/notes/' + str(service_id), post_data)
|
||||||
|
|
||||||
def create_server(self, post_data):
|
def create_server(self, post_data):
|
||||||
@ -248,7 +365,7 @@ class ServerManager:
|
|||||||
# remove following keys from post_data
|
# remove following keys from post_data
|
||||||
for key in NON_UPDATABLE_KEYS:
|
for key in NON_UPDATABLE_KEYS:
|
||||||
post_data.pop(key, None)
|
post_data.pop(key, None)
|
||||||
logging.info(f"Updating server with id {server_id}...")
|
logging.info("Updating server with id {}...".format(server_id))
|
||||||
return self.send_request('PUT', '/api/servers/' + str(server_id), post_data)
|
return self.send_request('PUT', '/api/servers/' + str(server_id), post_data)
|
||||||
|
|
||||||
def existing_server_id(self, post_data):
|
def existing_server_id(self, post_data):
|
||||||
|
Loading…
Reference in New Issue
Block a user