From 276f29c707ea8a37e41d6ec20d4b36591ef00eea Mon Sep 17 00:00:00 2001 From: Shailaja Date: Tue, 2 Jul 2024 13:42:22 +0530 Subject: [PATCH] refractored code --- agent.py | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/agent.py b/agent.py index e8ce391..ec49183 100644 --- a/agent.py +++ b/agent.py @@ -406,16 +406,38 @@ class ServerManager: else: return self.create_note(note_data) + def get_os_release_info(self): + try: + with open('/etc/os-release') as f: + lines = f.read().splitlines() + return {line.split('=')[0]: line.split('=')[1].strip('"') for line in lines if '=' in line} + except Exception as e: + logging.error("Failed to read /etc/os-release: {}".format(e)) + return {} def get_os_id(self): try: - response = urllib.request.urlopen(f"{self.host}/api/os") - os_list = json.loads(response.read().decode()) - current_os = os.uname().sysname.lower() + os_list = self.send_request('GET', '/api/os') + os_info = self.get_os_release_info() + + if not os_info: + logging.error("No OS release info found.") + return next(os['id'] for os in os_list if os['name'].lower() == "other" or os['name'].lower() == "custom") + + current_os = f"{os_info.get('NAME', 'Unknown')} {os_info.get('VERSION', '').strip()}".strip().lower() + for os_entry in os_list: if current_os in os_entry['name'].lower(): return os_entry['id'] - return next(os['id'] for os in os_list if os['name'].lower() == "other") + + if 'ubuntu' in current_os: + return next(os['id'] for os in os_list if 'ubuntu' in os['name'].lower()) + elif 'centos' in current_os: + return next(os['id'] for os in os_list if 'centos' in os['name'].lower()) + elif 'fedora' in current_os: + return next(os['id'] for os in os_list if 'fedora' in os['name'].lower()) + + return next(os['id'] for os in os_list if os['name'].lower() == "other" or os['name'].lower() == "custom") except Exception as e: logging.error("Failed to fetch OS IDs: {}".format(e)) return 27 # Default to 'Other' if unable to fetch