From 1e586266f7996a470d1b11cc103068f950a47b8e Mon Sep 17 00:00:00 2001 From: Shailaja Date: Tue, 25 Jun 2024 16:42:20 +0530 Subject: [PATCH] Added condition to check if file exists and readable and skips it if it is not readable --- agent.py | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/agent.py b/agent.py index e30560a..90f6895 100644 --- a/agent.py +++ b/agent.py @@ -27,25 +27,27 @@ class ServerData: self.public_ip = self.get_public_ip() logging.basicConfig(level=logging.INFO) - def get_ram_and_disk(self): - # RAM information - with open('/proc/meminfo', 'r') as f: - meminfo = f.read() - ram = int([x for x in meminfo.split('\n') if 'MemTotal' in x][0].split()[1]) // 1024 - - # Disk space information - disk = 0 - for device in os.listdir('/sys/block'): +def get_ram_and_disk(self): + # RAM information + with open('/proc/meminfo', 'r') as f: + meminfo = f.read() + ram = int([x for x in meminfo.split('\n') if 'MemTotal' in x][0].split()[1]) // 1024 + + # Disk space information + disk = 0 + for device in os.listdir('/sys/block'): + size_path = f'/sys/block/{device}/size' + if os.path.exists(size_path) and os.access(size_path, os.R_OK): try: - with open(f'/sys/block/{device}/size', 'r') as f: + with open(size_path, 'r') as f: size = int(f.read().strip()) disk += size - except Exception as e: - logging.error(f"Failed to read disk size for {device}: {e}") - - disk = disk * 512 // (1024**3) # convert to GB - logging.info(f"RAM: {ram}MB, Disk: {disk}GB") - return ram, disk + except Exception: + pass # Skip the device if any exception occurs + + disk = disk * 512 // (1024**3) # convert to GB + logging.info(f"RAM: {ram}MB, Disk: {disk}GB") + return ram, disk def get_cpu_count(self): cpu_count = 0