This repository was archived by the owner on Apr 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 163
[1LP][RFR] Prepare connect_ssh #10056
Merged
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7948c57
Prepare connect_ssh
94b3c96
Make trying_ips not default to ininite loop, make it use math.inf.
d53a1f4
Redesign reconnection stuff. Make it use unquirking client-factory me…
de4b80a
Remove retry_connect_rounds
fddf905
React on review of unquirked_ssh_client.
8b54c62
Make _try_batch_of_ips underscored.
c225cd8
Remove f string.
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,6 +18,7 @@ | |
| from cfme.utils import ports | ||
| from cfme.utils.log import logger | ||
| from cfme.utils.net import net_check | ||
| from cfme.utils.net import retry_connect_vm | ||
| from cfme.utils.path import project_path | ||
| from cfme.utils.quote import quote | ||
| from cfme.utils.timeutil import parsetime | ||
|
|
@@ -28,6 +29,9 @@ | |
| # Default blocking time before giving up on an ssh command execution, | ||
| # in seconds (float) | ||
| RUNCMD_TIMEOUT = 1200.0 | ||
| CONNECT_RETRIES_TIMEOUT = 2 * 60 | ||
| CONNECT_TIMEOUT = 10 | ||
| CONNECT_SSH_DELAY = 1 | ||
|
|
||
|
|
||
| @attr.s(frozen=True, eq=False) | ||
|
|
@@ -121,7 +125,7 @@ class SSHClient(paramiko.SSHClient): | |
| stdout: If specified, overrides the system stdout file for streaming output. | ||
| stderr: If specified, overrides the system stderr file for streaming output. | ||
| """ | ||
| def __init__(self, stream_output=False, **connect_kwargs): | ||
| def __init__(self, *, stream_output=False, **connect_kwargs): | ||
| super().__init__() | ||
| self._streaming = stream_output | ||
| # deprecated/useless karg, included for backward-compat | ||
|
|
@@ -135,11 +139,12 @@ def __init__(self, stream_output=False, **connect_kwargs): | |
| self.oc_password = connect_kwargs.pop('oc_password', False) | ||
| self.f_stdout = connect_kwargs.pop('stdout', sys.stdout) | ||
| self.f_stderr = connect_kwargs.pop('stderr', sys.stderr) | ||
| self._use_check_port = connect_kwargs.pop('use_check_port', True) | ||
| self.strict_host_key_checking = connect_kwargs.pop('strict_host_key_checking', True) | ||
|
|
||
| # load the defaults for ssh, including current_appliance and default credentials keys | ||
| compiled_kwargs = dict( | ||
| timeout=10, | ||
| timeout=CONNECT_TIMEOUT, | ||
| allow_agent=False, | ||
| look_for_keys=False, | ||
| gss_auth=False, | ||
|
|
@@ -231,7 +236,9 @@ def connect(self, hostname=None, **kwargs): | |
|
|
||
| if not self.connected: | ||
| self._connect_kwargs.update(kwargs) | ||
| wait_for(self._check_port, handle_exception=True, timeout='2m', delay=5) | ||
| if self._use_check_port: | ||
| wait_for(self._check_port, handle_exception=True, | ||
| timeout=CONNECT_TIMEOUT, delay=5) | ||
| try: | ||
| conn = super().connect(**self._connect_kwargs) | ||
| except paramiko.ssh_exception.BadHostKeyException: | ||
|
|
@@ -842,3 +849,42 @@ def keygen(): | |
| with _ssh_pubkey_file.open('w') as f: | ||
| f.write("{} {} {}\n".format(pub.get_name(), pub.get_base64(), | ||
| 'autogenerated cfme_tests key')) | ||
|
|
||
|
|
||
| def unquirked_ssh_client(**kwargs): | ||
| """ A factory for the SSHClient dealing with some of its quirks: | ||
|
|
||
| * When hostname is None, the SSHClient will connect to the default | ||
| appliance. | ||
| * Set use_check_port to False to disable waiting for port being | ||
| available in the SSHClient. | ||
| * The SSHClient does not connect in the object creation time. | ||
| """ | ||
| if kwargs['hostname'] is None: | ||
| raise ValueError(f'The hostname argument cannot be None!') | ||
|
||
| client = SSHClient(use_check_port=False, **kwargs) | ||
| client.connect() | ||
| return client | ||
|
|
||
|
|
||
| def connect_ssh(vm, creds, | ||
| num_sec=CONNECT_RETRIES_TIMEOUT, | ||
| connect_timeout=CONNECT_TIMEOUT, | ||
| delay=CONNECT_SSH_DELAY): | ||
| """ | ||
| This function attempts to connect all the IPs of the vm in several | ||
| round. After each round it will delay an ammount of seconds specified as | ||
| `delay`. Once connective IP is found, it will return connected SSHClient. | ||
| The `connect_timeout` specifies a timeout for each connection attempt. | ||
| """ | ||
|
|
||
| def _connection_factory(ip): | ||
| return unquirked_ssh_client( | ||
| hostname=ip, | ||
| username=creds.principal, password=creds.secret, | ||
| timeout=connect_timeout) | ||
|
|
||
| msg = "The num_sec is smaller then connect_timeout. This looks like a bug." | ||
| assert num_sec > connect_timeout, msg | ||
|
|
||
| return retry_connect_vm(vm, _connection_factory, num_sec=num_sec, delay=delay) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| from types import SimpleNamespace | ||
| from unittest.mock import Mock | ||
| from unittest.mock import PropertyMock | ||
|
|
||
| import pytest | ||
|
|
||
| from cfme.utils.ssh import connect_ssh | ||
|
|
||
|
|
||
| creds = SimpleNamespace(principal='mockuser', secret='mockpass') | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def nosleep(mocker): | ||
| mocker.patch('time.sleep') | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def vm_mock(): | ||
| vm = Mock() | ||
| all_ips_mock = PropertyMock() | ||
| type(vm).all_ips = all_ips_mock | ||
| all_ips_mock.side_effect = [ | ||
| [None], | ||
| ['NOT_WORKING_IP_MOCK'], | ||
| ['NOT_WORKING_IP_MOCK', 'OTHER_NOT_WORKING_IP_MOCK', | ||
| 'WORKING_IP_MOCK', 'SHOULD_NOT_REACH_THIS_MOCK'], | ||
| ['SHOULD_NOT_REACH_THIS_MOCK', 'SHOULD_NOT_REACH_THIS_MOCK'] | ||
| ] | ||
| return vm | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def vm_mock2(): | ||
| vm = Mock() | ||
| all_ips_mock = PropertyMock() | ||
| type(vm).all_ips = all_ips_mock | ||
| all_ips_mock.side_effect = [ | ||
| ['WORKING_IP_MOCK', 'SHOULD_NOT_REACH_THIS_MOCK'] | ||
| ] | ||
| return vm | ||
|
|
||
|
|
||
| class SSHClientMock: | ||
| def __init__(self, **kwargs): | ||
| self.kwargs = kwargs | ||
| self.close = Mock() | ||
| self.run_command = Mock() | ||
| self.run_command.success.return_value = True | ||
|
|
||
| # disabling check_port is required for not making repeated connection | ||
| # attempts in the SSHClient | ||
| assert kwargs['use_check_port'] is False | ||
|
|
||
| def connect(self): | ||
| hostname = self.kwargs['hostname'] | ||
| if hostname == 'WORKING_IP_MOCK': | ||
| return self | ||
| elif hostname == 'SHOULD_NOT_REACH_THIS_MOCK': | ||
| pytest.fail('We should not have reached checking this IP!') | ||
| else: | ||
| raise Exception(f'This was raised for IP {hostname}.') | ||
|
|
||
|
|
||
| def test_connect_ssh(mocker, vm_mock, vm_mock2): | ||
| mocker.patch('cfme.utils.ssh.SSHClient', SSHClientMock) | ||
| assert connect_ssh(vm_mock, creds, num_sec=3, connect_timeout=1, delay=1).run_command() | ||
| assert connect_ssh(vm_mock2, creds, num_sec=3, connect_timeout=1, delay=1).run_command() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.