Skip to content

Commit

Permalink
fix(#5229): macOS AWS connection fix
Browse files Browse the repository at this point in the history
  • Loading branch information
pro-akim committed May 3, 2024
1 parent d3a2c09 commit 8447966
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 54 deletions.
54 changes: 39 additions & 15 deletions deployability/modules/testing/tests/helpers/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}')

# ------------------------------------------------------

Expand Down
80 changes: 41 additions & 39 deletions deployability/modules/testing/tests/helpers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}')
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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

0 comments on commit 8447966

Please sign in to comment.