Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelogs/fragments/win_updates-poll-transport-loss.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
bugfixes:
- win_updates - Reset the connection and retry polling the update progress and cancelling the update task on any
connection error, like a WSMan fault raised by the ``psrp`` or ``winrm`` connection plugin, instead of failing and
leaving the update task running on the host - https://github.com/ansible-collections/ansible.windows/issues/970
46 changes: 31 additions & 15 deletions plugins/action/win_updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import random
import time
import traceback

from ansible.errors import AnsibleActionFail, AnsibleConnectionFailure
Expand All @@ -12,13 +14,6 @@
from ansible.plugins.action import ActionBase
from ansible.utils.display import Display

# This is not ideal but the psrp connection plugin doesn't catch all these exceptions as an AnsibleConnectionFailure.
# Until we can guarantee we are using a version of psrp that handles all this we try to handle those issues.
try:
from requests.exceptions import Timeout as RequestTimeoutException
except ImportError:
RequestTimeoutException = AnsibleConnectionFailure

try:
from typing import (
Dict,
Expand Down Expand Up @@ -941,11 +936,14 @@ def _run_updates(self, task_vars, module_options, for_testing=False):
# The last thing we should be doing is to cancel the task. This
# stops a process that might still be running and is also used in
# a normal operation to signal the exit status has been received.
# The update task keeps on running if the cancel does not reach
# it so it is retried like the poll.
try:
self._execute_win_updates(
task_vars,
operation="cancel",
operation_options=cancel_options,
retry_on_failure=True,
)
except Exception as e:
if has_errored:
Expand All @@ -968,24 +966,35 @@ def _execute_win_updates(
final_options["_operation_options"] = operation_options or {}

# WinRM based connections are problematic when the host is under load.
# When polling the output, ignore connection/timeout failures and try
# again in case it was a temporary error. We can only do this during
# the polling stage as that's the only time we can ignore a dropped
# progress message.
# When polling the output or cancelling the task, ignore
# connection/timeout failures and try again in case it was a temporary
# error. We can only do this during the polling stage as that's the
# only time we can ignore a dropped progress message, the cancel can
# be sent more than once. The update task outlives the WinRM shell so
# the connection is reset to run the command on a new shell. The psrp
# and winrm connection plugins don't raise all of their connection
# errors as an AnsibleConnectionFailure, e.g. a WSManFault when the
# shell was aborted, so any error is retried.
result = {}
for idx in range(2):
attempts = 6 if retry_on_failure else 1
for idx in range(attempts):
try:
result = self._execute_module(
module_name='ansible.windows.win_updates',
module_args=final_options,
task_vars=task_vars,
)
break
except (AnsibleConnectionFailure, RequestTimeoutException) as e:
if not retry_on_failure or idx == 1:
except Exception as e:
if idx == attempts - 1:
raise

display.warning("Connection failure when polling update result - attempting to retry: %s" % to_text(e))
action = "polling update result" if operation == "poll" else "cancelling update task"
display.warning("Connection failure when %s - attempting to retry: %s" % (action, to_text(e)))
self._reset_connection(task_vars.get('inventory_hostname', None))

# Use exponential backoff with a max timeout, plus a little bit of randomness
time.sleep(min(2**idx, 12) + random.randint(0, 1000) / 1000)

if 'invocation' in result and not self._invocation:
# First run through we want to update the invocation value in the final results
Expand All @@ -1012,6 +1021,13 @@ def _execute_win_updates(

return result

def _reset_connection(self, inventory_hostname): # type: (Optional[str]) -> None
"""Resets the connection, the next command reconnects if it fails."""
try:
self._connection.reset()
except Exception as e:
display.vvvv("Failed to reset connection: %s" % to_text(e), host=inventory_hostname)

def _get_update_info(self, update_id): # type: (str) -> Dict
"""Gets the update results info value to return."""
raw_info = self._updates[update_id]
Expand Down
70 changes: 63 additions & 7 deletions tests/unit/plugins/action/test_win_updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@ def _read_gen(self):
yield AnsibleConnectionFailure("connection error")
continue

if line == b'FAILURE_WSMAN':
# pypsrp exception raised as is by the psrp connection plugin
yield Exception("Received a WSManFault message. (Code: 995)")
continue

if not line:
if not output:
continue
Expand Down Expand Up @@ -165,13 +170,14 @@ def win_updates_init(task_args, async_val=0, check_mode=False, connection=None):
return plugin


def run_action(monkeypatch, test_id, task_vars, check_mode=False, poll_rc=0, poll_stderr=b'', poll_newline_separator=b'\n'):
def run_action(monkeypatch, test_id, task_vars, check_mode=False, poll_rc=0, poll_stderr=b'', poll_newline_separator=b'\n',
connection=None):
module_arg_return = task_vars.copy()

plugin = win_updates_init(
task_vars,
check_mode=check_mode,
connection=MagicMock(),
connection=connection or MagicMock(),
)
execute_module = MagicMock()
execute_module.side_effect = UpdateModuleMock(test_id, module_arg_return).__iter__()
Expand Down Expand Up @@ -578,6 +584,7 @@ def test_fail_install(monkeypatch):
def test_connection_failures_during_poll(monkeypatch):
mock_warning = MagicMock()
monkeypatch.setattr(win_updates.display, "warning", mock_warning)
monkeypatch.setattr(win_updates.time, "sleep", MagicMock())
actual = run_action(monkeypatch, 'poll_error1.txt', {
'category_names': ['*'],
})
Expand Down Expand Up @@ -623,17 +630,66 @@ def test_connection_failures_during_poll(monkeypatch):
def test_multiple_connection_failures_during_poll(monkeypatch):
mock_warning = MagicMock()
monkeypatch.setattr(win_updates.display, "warning", mock_warning)
monkeypatch.setattr(win_updates.time, "sleep", MagicMock())
connection = MagicMock()
actual = run_action(monkeypatch, 'poll_error2.txt', {
'category_names': ['*'],
})
}, connection=connection)

assert actual['unreachable']
assert actual['msg'] == 'connection error'

assert mock_warning.call_count == 3
assert mock_warning.mock_calls[0][1] == ('Connection failure when polling update result - attempting to retry: connection error',)
assert mock_warning.mock_calls[1][1] == ('Unknown failure when polling update result - attempting to cancel task: connection error',)
assert mock_warning.mock_calls[2][1] == ('Unknown failure when cancelling update task: connection error',)
assert mock_warning.call_count == 12
for idx in range(5):
assert mock_warning.mock_calls[idx][1] == ('Connection failure when polling update result - attempting to retry: connection error',)
assert mock_warning.mock_calls[5][1] == ('Unknown failure when polling update result - attempting to cancel task: connection error',)
for idx in range(6, 11):
assert mock_warning.mock_calls[idx][1] == ('Connection failure when cancelling update task - attempting to retry: connection error',)
assert mock_warning.mock_calls[11][1] == ('Unknown failure when cancelling update task: connection error',)

# Reset before each poll and cancel retry.
assert connection.reset.call_count == 10


def test_wsman_fault_during_poll(monkeypatch):
mock_warning = MagicMock()
monkeypatch.setattr(win_updates.display, "warning", mock_warning)
monkeypatch.setattr(win_updates.time, "sleep", MagicMock())
connection = MagicMock()
actual = run_action(monkeypatch, 'poll_error3.txt', {
'category_names': ['*'],
}, connection=connection)

assert 'failed' not in actual
assert actual['changed']
assert actual['found_update_count'] == 3
assert actual['installed_update_count'] == 3

assert connection.reset.call_count == 1
assert mock_warning.call_count == 1
assert mock_warning.mock_calls[0][1] == (
'Connection failure when polling update result - attempting to retry: Received a WSManFault message. (Code: 995)',
)


def test_wsman_fault_during_cancel(monkeypatch):
mock_warning = MagicMock()
monkeypatch.setattr(win_updates.display, "warning", mock_warning)
monkeypatch.setattr(win_updates.time, "sleep", MagicMock())
connection = MagicMock()
actual = run_action(monkeypatch, 'poll_error4.txt', {
'category_names': ['*'],
}, connection=connection)

assert 'failed' not in actual
assert actual['changed']
assert actual['installed_update_count'] == 3

assert connection.reset.call_count == 1
assert mock_warning.call_count == 1
assert mock_warning.mock_calls[0][1] == (
'Connection failure when cancelling update task - attempting to retry: Received a WSManFault message. (Code: 995)',
)


def test_repeated_update(monkeypatch):
Expand Down
9 changes: 9 additions & 0 deletions tests/unit/test_data/win_updates/poll_error2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,12 @@
FAILURE
FAILURE
FAILURE
FAILURE
FAILURE
FAILURE
FAILURE
FAILURE
FAILURE
FAILURE
FAILURE
FAILURE
Loading
Loading