|
| 1 | +# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). |
| 4 | +# You may not use this file except in compliance with the License. |
| 5 | +# A copy of the License is located at |
| 6 | +# |
| 7 | +# http://aws.amazon.com/apache2.0/ |
| 8 | +# |
| 9 | +# or in the "LICENSE.txt" file accompanying this file. |
| 10 | +# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. |
| 11 | +# See the License for the specific language governing permissions and limitations under the License. |
| 12 | +import collections |
| 13 | +import logging |
| 14 | +import os |
| 15 | +import time |
| 16 | +from math import ceil |
| 17 | +from multiprocessing import Pool |
| 18 | + |
| 19 | +from retrying import retry |
| 20 | + |
| 21 | +from common.time_utils import seconds |
| 22 | +from paramiko import AutoAddPolicy, SSHClient |
| 23 | + |
| 24 | +RemoteCommandResult = collections.namedtuple("RemoteCommandResult", ["return_code", "stdout", "stderr"]) |
| 25 | + |
| 26 | + |
| 27 | +class RemoteCommandExecutionError(Exception): |
| 28 | + """Signal a failure in remote command execution.""" |
| 29 | + |
| 30 | + pass |
| 31 | + |
| 32 | + |
| 33 | +class RemoteCommandExecutor: |
| 34 | + """Execute remote commands.""" |
| 35 | + |
| 36 | + def __init__(self, hostname, user, ssh_key_file=None): |
| 37 | + try: |
| 38 | + if not ssh_key_file: |
| 39 | + ssh_key_file = os.path.expanduser("~" + user) + "/.ssh/id_rsa" |
| 40 | + self.__ssh_client = SSHClient() |
| 41 | + self.__ssh_client.load_system_host_keys() |
| 42 | + self.__ssh_client.set_missing_host_key_policy(AutoAddPolicy()) |
| 43 | + self.__ssh_client.connect(hostname=hostname, username=user, key_filename=ssh_key_file) |
| 44 | + self.__user_at_hostname = "{0}@{1}".format(user, hostname) |
| 45 | + except Exception as e: |
| 46 | + logging.error("Failed when connecting to host %s with error: %s", hostname, e) |
| 47 | + raise |
| 48 | + |
| 49 | + def __del__(self): |
| 50 | + try: |
| 51 | + self.__ssh_client.close() |
| 52 | + except Exception as e: |
| 53 | + # Catch all exceptions if we fail to close the clients |
| 54 | + logging.warning("Exception raised when closing remote clients: {0}".format(e)) |
| 55 | + |
| 56 | + def run_remote_command(self, command, timeout=seconds(5), log_error=True, fail_on_error=True): |
| 57 | + """ |
| 58 | + Execute remote command on the configured host. |
| 59 | +
|
| 60 | + :param command: command to execute. |
| 61 | + :param log_error: log errors. |
| 62 | + :return: result of the execution. |
| 63 | + """ |
| 64 | + if isinstance(command, list): |
| 65 | + command = " ".join(command) |
| 66 | + logging.info("Executing remote command command on {0}: {1}".format(self.__user_at_hostname, command)) |
| 67 | + result = None |
| 68 | + try: |
| 69 | + stdin, stdout, stderr = self.__ssh_client.exec_command(command, get_pty=True) |
| 70 | + self._wait_for_command_execution(timeout, stdout) |
| 71 | + result = RemoteCommandResult( |
| 72 | + return_code=stdout.channel.recv_exit_status(), |
| 73 | + stdout="\n".join(stdout.read().decode().splitlines()), |
| 74 | + stderr="\n".join(stderr.read().decode().splitlines()), |
| 75 | + ) |
| 76 | + if result.return_code != 0 and fail_on_error: |
| 77 | + raise RemoteCommandExecutionError(result) |
| 78 | + return result |
| 79 | + except Exception: |
| 80 | + if log_error and result: |
| 81 | + logging.error( |
| 82 | + "Command {0} failed with error:\n{1}\nand output:\n{2}".format( |
| 83 | + command, result.stderr, result.stdout |
| 84 | + ) |
| 85 | + ) |
| 86 | + raise |
| 87 | + |
| 88 | + @staticmethod |
| 89 | + def _wait_for_command_execution(timeout, stdout): |
| 90 | + # Using the non-blocking exit_status_ready to avoid being stuck forever on recv_exit_status |
| 91 | + # especially when a compute node is terminated during this operation |
| 92 | + while timeout > 0 and not stdout.channel.exit_status_ready(): |
| 93 | + timeout = timeout - 1 |
| 94 | + time.sleep(1) |
| 95 | + if not stdout.channel.exit_status_ready(): |
| 96 | + raise RemoteCommandExecutionError("Timeout occurred when executing remote command") |
| 97 | + |
| 98 | + @staticmethod |
| 99 | + def run_remote_command_on_multiple_hosts( |
| 100 | + command, hostnames, user, ssh_key_file=None, parallelism=10, timeout=10, fail_on_error=True |
| 101 | + ): |
| 102 | + if not hostnames: |
| 103 | + return {} |
| 104 | + |
| 105 | + pool = Pool(parallelism) |
| 106 | + try: |
| 107 | + r = pool.map_async( |
| 108 | + _pickable_run_remote_command, |
| 109 | + [(hostname, command, user, ssh_key_file, timeout, fail_on_error) for hostname in hostnames], |
| 110 | + ) |
| 111 | + # The pool timeout is computed by adding 2 times the command timeout for each batch of hosts that is |
| 112 | + # processed in sequence. Where the size of a batch is given by the degree of parallelism. |
| 113 | + results = r.get(timeout=int(ceil(len(hostnames) / float(parallelism)) * (2 * timeout))) |
| 114 | + finally: |
| 115 | + pool.terminate() |
| 116 | + |
| 117 | + return dict(results) |
| 118 | + |
| 119 | + |
| 120 | +@retry(stop_max_attempt_number=2) |
| 121 | +def _pickable_run_remote_command(args): |
| 122 | + """Pickable version of the run_command method that can be used by a pool.""" |
| 123 | + (hostname, command, user, ssh_key_file, timeout, fail_on_error) = args |
| 124 | + try: |
| 125 | + remote_command_executor = RemoteCommandExecutor(hostname, user, ssh_key_file) |
| 126 | + remote_command_executor.run_remote_command(command, timeout, fail_on_error=fail_on_error) |
| 127 | + return hostname, True |
| 128 | + except Exception as e: |
| 129 | + logging.error("Failed when executing remote command on node %s with error %s", hostname, e) |
| 130 | + return hostname, False |
0 commit comments