From 8447966eb591384bd32edf0e2a8a97a5cc34e6f8 Mon Sep 17 00:00:00 2001 From: Antonio Date: Fri, 3 May 2024 10:08:19 +0200 Subject: [PATCH] fix(#5229): macOS AWS connection fix --- .../modules/testing/tests/helpers/executor.py | 54 +++++++++---- .../modules/testing/tests/helpers/utils.py | 80 ++++++++++--------- 2 files changed, 80 insertions(+), 54 deletions(-) diff --git a/deployability/modules/testing/tests/helpers/executor.py b/deployability/modules/testing/tests/helpers/executor.py index b288cef4bd..609a431098 100644 --- a/deployability/modules/testing/tests/helpers/executor.py +++ b/deployability/modules/testing/tests/helpers/executor.py @@ -112,25 +112,49 @@ def _execute_command(data, command) -> dict: class MacosExecutor(): @staticmethod def _execute_command(data, command) -> dict: - try: - ssh_client = paramiko.SSHClient() - ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - ssh_client.connect(hostname=data.get('host'), port=data.get('port'), username=data.get('username'), password=data.get('password')) - stdin, stdout, stderr = ssh_client.exec_command(f"sudo {command}") + if data.get('private_key_path') == None: + try: + ssh_client = paramiko.SSHClient() + ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh_client.connect(hostname=data.get('host'), port=data.get('port'), username=data.get('username'), password=data.get('password')) + stdin, stdout, stderr = ssh_client.exec_command(f"sudo {command}") - stdout_str = ''.join(stdout.readlines()) - stderr_str = ''.join(stderr.readlines()) + stdout_str = ''.join(stdout.readlines()) + stderr_str = ''.join(stderr.readlines()) - ssh_client.close() + ssh_client.close() - if stdout_str: - return {'success': True, 'output': stdout_str.replace('\n', '')} - if stderr_str: - return {'success': False, 'output': stderr_str.replace('\n', '')} - return {'success': False, 'output': None} + if stdout_str: + return {'success': True, 'output': stdout_str.replace('\n', '')} + if stderr_str: + return {'success': False, 'output': stderr_str.replace('\n', '')} + return {'success': False, 'output': None} - except Exception as e: - raise Exception(f'Error executing command: {command} with error: {e}') + except Exception as e: + raise Exception(f'Error executing command: {command} with error: {e}') + else: + ssh_command = [ + "ssh", + "-i", data.get('private_key_path'), + "-o", "StrictHostKeyChecking=no", + "-o", "UserKnownHostsFile=/dev/null", + "-p", str(data.get('port')), + f"{data.get('username')}@{data.get('host')}", + "sudo", + command + ] + + try: + ret = subprocess.run(ssh_command, stdout=subprocess.PIPE, text=True) + if ret.stdout: + return {'success': True, 'output': ret.stdout.replace('\n', '')} + if ret.stderr: + return {'success': False, 'output': ret.stderr.replace('\n', '')} + return {'success': False, 'output': None} + + except Exception as e: + #return {'success': False, 'output': ret.stderr} + raise Exception(f'Error executing command: {command} with error: {e}') # ------------------------------------------------------ diff --git a/deployability/modules/testing/tests/helpers/utils.py b/deployability/modules/testing/tests/helpers/utils.py index dbf73e34af..b1bbccadb0 100644 --- a/deployability/modules/testing/tests/helpers/utils.py +++ b/deployability/modules/testing/tests/helpers/utils.py @@ -29,6 +29,8 @@ def check_inventory_connection(inventory_path, attempts=10, sleep=30) -> bool: match = re.search(r'/manager-[^-]+-([^-]+)-([^-]+)-', inventory_path) elif 'agent' in inventory_path: match = re.search(r'/agent-[^-]+-([^-]+)-([^-]+)-', inventory_path) + elif 'central_components' in inventory_path: + match = re.search(r'/central_components-[^-]+-([^-]+)-([^-]+)-', inventory_path) if match: os_name = match.group(1)+ '-' + match.group(2) logger.info(f'Checking connection to {os_name}') @@ -46,7 +48,6 @@ def check_inventory_connection(inventory_path, attempts=10, sleep=30) -> bool: username = inventory_data.get('ansible_user') password = inventory_data.get('ansible_password', None) - try: with open(inventory_path.replace('inventory', 'track'), 'r') as file: data = yaml.safe_load(file) @@ -61,7 +62,7 @@ def check_inventory_connection(inventory_path, attempts=10, sleep=30) -> bool: except Exception as e: logger.error(f"An unexpected error occurred: {e}") - if os_type == 'linux': + if private_key_path != None: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) private_key = paramiko.RSAKey.from_private_key_file(private_key_path) @@ -82,45 +83,46 @@ def check_inventory_connection(inventory_path, attempts=10, sleep=30) -> bool: logger.warning(f'Error on attempt {attempt} of {attempts}: {e}') time.sleep(sleep) - elif os_type == 'windows': - if port == 5986: - protocol = 'https' - else: - protocol = 'http' - endpoint_url = f'{protocol}://{host}:{port}' + else: + if os_type == 'windows': + if port == 5986: + protocol = 'https' + else: + protocol = 'http' + endpoint_url = f'{protocol}://{host}:{port}' + + for attempt in range(1, attempts + 1): + try: + session = winrm.Session(endpoint_url, auth=(username, password),transport='ntlm', server_cert_validation='ignore') + cmd = session.run_cmd('ipconfig') + if cmd.status_code == 0: + logger.info("WinRM connection successful.") + return True + else: + logger.error('WinRM connection failed. Check the credentials in the inventory file.') + return False + except Exception as e: + logger.warning(f'Error on attempt {attempt} of {attempts}: {e}') + time.sleep(sleep) + + elif os_type == 'macos': + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - for attempt in range(1, attempts + 1): - try: - session = winrm.Session(endpoint_url, auth=(username, password),transport='ntlm', server_cert_validation='ignore') - cmd = session.run_cmd('ipconfig') - if cmd.status_code == 0: - logger.info("WinRM connection successful.") + for attempt in range(1, attempts + 1): + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + try: + ssh.connect(hostname=host, port=port, username=username, password=password) + logger.info(f'Connection established successfully in {os_name}') + ssh.close() return True - else: - logger.error('WinRM connection failed. Check the credentials in the inventory file.') + except paramiko.AuthenticationException: + logger.error(f'Authentication error. Check SSH credentials in {os_name}') return False - except Exception as e: - logger.warning(f'Error on attempt {attempt} of {attempts}: {e}') - time.sleep(sleep) - - elif os_type == 'macos': - ssh = paramiko.SSHClient() - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - - for attempt in range(1, attempts + 1): - ssh = paramiko.SSHClient() - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - try: - ssh.connect(hostname=host, port=port, username=username, password=password) - logger.info(f'Connection established successfully in {os_name}') - ssh.close() - return True - except paramiko.AuthenticationException: - logger.error(f'Authentication error. Check SSH credentials in {os_name}') - return False - except Exception as e: - logger.warning(f'Error on attempt {attempt} of {attempts}: {e}') - time.sleep(sleep) + except Exception as e: + logger.warning(f'Error on attempt {attempt} of {attempts}: {e}') + time.sleep(sleep) logger.error(f'Connection attempts failed after {attempts} tries. Connection timeout in {os_name}') - return False + return False \ No newline at end of file