__init__.py000064400000003131147205356560006670 0ustar00from base64 import b64encode import functools import random import string def b64str(s: str) -> str: """Return `s` base64-encoded. :param s: string to encode """ return b64encode(s.encode()).decode() def fmap(func, obj): "Homomorphic mapping of a function" # strings are specifically not fmap-able because that invites # consideration as byte characters, not unicode if isinstance(obj, tuple): return tuple(map(functools.partial(fmap, func), obj)) iterableitems = isinstance(obj, (list, dict)) if not iterableitems: try: iterableitems = isinstance(obj, (filter, map, zip, range)) except TypeError: # pragma: nocover # Python2 doesn't have objects like the above # The corresponding operations just result in lists # which is already covered pass if iterableitems: if hasattr(obj, 'items'): return dict(map(functools.partial(fmap, func), obj.items())) return list(map(functools.partial(fmap, func), obj)) if hasattr(obj, 'fmap'): return obj.fmap(func) return func(obj) def random_password(length: int = None) -> str: """Create a random password. :param length: An int specifying password length :returns: the password, in cleartext """ if not length: length = random.randint(10, 23) edited_punctuation = string.punctuation.replace('"', '').replace("'", "").replace("\\", "") return ''.join([random.choice(string.digits + string.ascii_letters + edited_punctuation) for X in range(length)]) execute.py000064400000047007147205356560006605 0ustar00# -*- coding: utf-8 -*- import logging import os import sys import subprocess import tempfile from pathlib import Path from typing import Any, Tuple, Union, List from subprocess import list2cmdline from primordial.sizes import ByteSize from customer_local_ops.util import fmap DEFAULT_MAX_SEGMENT_SIZE = ByteSize(KiBytes=32) LOG = logging.getLogger(__name__) MAX_COMMAND_RESPONSE_BUFFER_SIZE = 2 * DEFAULT_MAX_SEGMENT_SIZE # Type aliases RunCommandResult = Tuple[int, str, str] # pylint: disable=import-error if sys.platform == 'win32': import win32con from win32com.shell import shellcon from win32com.shell import shell HANDLE = int HWND = int HKEY = int DWORD = int def shell_start(file_name: str, params: str = None, verb: str = "open", show: int = win32con.SW_SHOWNORMAL, mask: int = shellcon.SEE_MASK_FLAG_DDEWAIT, dir_name: str = None, id_list: Any = None, class_id: str = None, class_key: HKEY = None, hot_key: DWORD = None, monitor: HANDLE = None, window: HWND = None) -> bool: """ Wrapper for the Win32 API call ShellExecuteEx. This function can be used on Windows platforms any time Nydus needs to restart itself for any reason because ShellExecuteEx allows the child process to survive after its parent process stops. Initially added to resolve a DLL conflict issue, this could also be useful for upgrading Nydus, for example. Further information for ShellExecuteEx can be found at https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecuteexa :param file_name: The name of the executable to be started. ShellExecuteEx also handles file associations, so this could also be the name of a document, for example, to be opened with the associated application, or a URL to be opened by the user's default browser. :param params: Parameters to be passed to the application. Should not be specified if file_name is NOT an executable file. :param verb: Action to take. May be one of 'edit', 'explore', 'find', 'open', 'print', 'properties' or 'runas'. Defaults to 'open' :param show: Specify how an application is to be shown :param mask: Flags that indicate content and validity of other parameters :param dir_name: Name of the working directory. If None, the current directory is used :param id_list: See Microsoft documentation at the URL above :param class_id: See Microsoft documentation at the URL above :param class_key: See Microsoft documentation at the URL above :param hot_key: See Microsoft documentation at the URL above :param monitor: See Microsoft documentation at the URL above :param window: See Microsoft documentation at the URL above :return: True if the file/application is successfully launched; otherwise, False """ def add_field(key: str, val: Any) -> None: """ It is an error to include a field with a value of None in the structure passed to ShellExecuteEx, so this function only adds a key to the dictionary if the value is not None. :param key: The name of the SHELLEXECUTEINFO field :param val: The value of the field """ if val is not None: shell_execute_info[key] = val shell_execute_info = {} add_field('fMask', mask) add_field('hwnd', window) add_field('lpVerb', verb) add_field('lpFile', file_name) add_field('lpParameters', params) add_field('lpDirectory', dir_name) add_field('nShow', show) add_field('lpIDList', id_list) add_field('lpClass', class_id) add_field('hkeyClass', class_key) add_field('dwHotKey', hot_key) add_field('hMonitor', monitor) return shell.ShellExecuteEx(**shell_execute_info) else: def shell_start(**kwargs) -> bool: return True def pfx(line): return '| ' + line def pfxs(lines): return list(map(pfx, lines)) def trim_visible_output_to_lines(inp, out): """Converts input blob to lines... but not too many""" if inp is not None: out = out.replace(inp, '<>', 1) outl = out.strip().split('\n') if not outl: return outl if len(outl) == 1 and not outl[0].strip(): return [] # no single blank lines please if len(outl) < 11: return pfxs(outl) return pfxs(outl[:5] + ['...elided %d lines...' % (len(outl) - 10)] + outl[-5:]) def mark_error_output(errOut): "Converts error blob into lines with prefix marks" se = errOut.strip() if se: for L in se.split('\n'): yield 'ERR: ' + L class EndsBuffer: """String buffer that maintains two segments: a first segment and a last segment (i.e. the two ends), where each has a maximum size limit. Any extra output in between these is discarded. The assumption is that if there is a huge amount of output that some must be discarded to avoid memory overflows and that generally the first and last stuff is the most relevant. """ def __init__(self, max_segment_size=None): self._mss = ByteSize(max(0, max_segment_size or 0)) or DEFAULT_MAX_SEGMENT_SIZE self._data = '' self._elided = False def add_str(self, data): self._data += data if len(self._data) > self._mss * 2: self._data = self._data[:self._mss] + self._data[-int(self._mss):] self._elided = True def get_bufstr(self): if self._elided: return '\n'.join([ self._data[:self._mss], '...[elided]...', self._data[-int(self._mss):], ]) return self._data def str_form(bytestr): try: return bytestr.decode('utf-8', errors='backslashreplace') except UnicodeDecodeError: try: import chardet # pylint: disable=import-outside-toplevel try: return bytestr.decode(chardet.detect(bytestr)['encoding']) except UnicodeDecodeError: pass except ImportError: pass except AttributeError: return bytestr # already a string class RunningCommand: def __init__(self, popen_obj, tag, stdInput, errorOK, logger, max_buffer_size=MAX_COMMAND_RESPONSE_BUFFER_SIZE): self.p = popen_obj self.tag = tag self.stdInput = stdInput self.logger = (lambda r, _l=logger or LOG, e=errorOK: getattr(_l, "error" if r and not e else "info")) self._bufsize = max_buffer_size self._output = EndsBuffer(self._bufsize / 2) self._errors = EndsBuffer(self._bufsize / 2) self._partial = False self._completed = False def checkIfCompleted(self): self._output.add_str(str_form(self.p.stdout.read())) self._errors.add_str(str_form(self.p.stderr.read())) return self.p.poll() is not None def outputToDate(self): o = self._output.get_bufstr() e = self._errors.get_bufstr() self._output = EndsBuffer(self._bufsize / 2) self._errors = EndsBuffer(self._bufsize / 2) self._partial = True return o, e def waitForCompletion(self): # n.b. communicate returns byte strings, in an unknown encoding, although # with older python, they could also be strings o, e = fmap(str_form, self.p.communicate()) self._output.add_str(o) self._errors.add_str(e) self._completed = True return self def getResult(self, omitOutput=False): if not self._completed: self.waitForCompletion() outs, errs = self._output.get_bufstr(), self._errors.get_bufstr() output_lines = trim_visible_output_to_lines(self.stdInput, outs) if omitOutput: output_lines = [line if line.startswith("<>") else "<>" for line in output_lines] for line in (output_lines + list(mark_error_output(errs)) + ["ExitCode: %d" % self.p.returncode]): lstr = self.tag + ' ' + line self.logger(self.p.returncode)(lstr) # NOTE This is not a Nydus Result; it must be converted return self.p.returncode, outs.strip(), errs.strip() def startCommand(cmd, tag, useShell=False, stdInput=None, errorOK=False, logger=None, omitString=None, env=None): """Starts the specified command; no Shell. The cmd is expected to be an array of strings, although it is also possible to specify simply a string if there are no arguments to the command. The tag value is only used to annotate log lines for distinctive tagging in the logging output. If errorOK is True then a non-zero return code is still only logged as "info" instead of "error". The ProcOpResult will accurately reflect the result of the operation regardless of the errorOK argument. If omitString is specified, it is removed from any logging output. The command is run asynchronously in a separate process. The return value is a RunningCommand object that supports a .checkIfCompleted() method to test for subprocess completion (non-blocking) and a .getResult() to get the ProcOpResult of a completed process (will block until completion if not already completed). """ # if cmd is a string, leave as is to correctly obfuscate omitString # If cmd is a bytestring, make sure omitString and the replacement text are also bytestrings log_cmd = ' '.join(cmd) if isinstance(cmd, list) else cmd replace_text = "<>" if isinstance(log_cmd, bytes): if omitString is not None and isinstance(omitString, str): omitString = omitString.encode('utf-8') replace_text = b'<>' if omitString: log_cmd = log_cmd.replace(omitString, replace_text) if logger is None: logger = LOG logger.info(tag + " RUN: " + str(log_cmd)) # pylint: disable=logging-not-lazy # pylint: disable=consider-using-with p = subprocess.Popen(cmd, shell=useShell, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if stdInput: p.stdin.write(stdInput.encode()) return RunningCommand(p, tag, stdInput, errorOK, logger) def runCommand(cmd, tag, useShell=False, stdInput=None, errorOK=False, logger=None, omitString=None, omitOutput=False, env=None): """Runs the specified command and waits for completion; no Shell. The cmd is expected to be an array of strings, although it is also possible to specify simply a string if there are no arguments to the command. The tag value is only used to annotate log lines for distinctive tagging in the logging output. If errorOK is True then a non-zero return code is still only logged as "info" instead of "error". The ProcOpResult will accurately reflect the result of the operation regardless of the errorOK argument. If omitString is specified, it is removed from any logging output. """ return startCommand(cmd, tag, useShell=useShell, stdInput=stdInput, errorOK=errorOK, logger=logger, omitString=omitString, env=env) \ .waitForCompletion() \ .getResult(omitOutput=omitOutput) def run_command_pipe(cmd, useShell=False): """Used to run commands that make use of | """ p = subprocess.Popen(cmd, shell=useShell, stdout=subprocess.PIPE) with p: o, e = p.communicate() return p.returncode, o, e def run_powershell(command: str, tag: str, quiet: bool = False) -> Tuple[int, str, str]: """Execute the code in ``command`` using PowerShell. :param command: Code to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :return: Tuple containing (exit_code, stdout, stderr) """ # 1. Python 3.5 Windows: cannot use context manager - it does not unlink the file on exit. # 2. Encode in UTF-8 with byte order mark (BOM) so PowerShell 5.1 (Windows 2016) sees the file is UTF-8. Without # this, the file will be encoded with the default system encoding which can be changed by administrators and # which, by default, cannot encode all Unicode characters properly. Encoding as UTF-8 without BOM does not work # because standard output cannot be decoded as UTF-8. # - Encoding PowerShell scripts: # https://docs.microsoft.com/en-us/powershell/scripting/dev-cross-plat/ # vscode/understanding-file-encoding?view=powershell-7.1 # - utf-8-sig encoding: https://docs.python.org/3.5/library/codecs.html#encodings-and-unicode # - Default encoding (locale.getpreferredencoding()): https://docs.python.org/3.5/library/functions.html#open # pylint: disable=consider-using-with temp = tempfile.NamedTemporaryFile(mode='w+t', encoding='utf-8-sig', suffix='.ps1', delete=False) try: temp.write(command) temp.close() if not quiet: LOG.debug("Running PowerShell command: %s", command) return run_powershell_file(temp.name, tag, quiet) finally: os.unlink(temp.name) def run_shell_script_file(script_file: Union[str, Path], tag: str, quiet: bool = False, script_file_args: List[str] = None, stdin: str = None) -> Tuple[int, str, str]: """Invoke Shell script, passing just ``filename`` or ``filepath`` and a list of arguments for execution of the file :param script_file: The path of the script file to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :param script_file_args: List of string arguments if required while execution of the file :param stdin: string to pass through standard input :return: Tuple containing (exit_code, stdout, stderr) """ command = ['bash', str(script_file)] if script_file_args: for arg in script_file_args: command.append(str(arg)) return runCommand(command, tag, stdInput=stdin, omitOutput=quiet) def run_powershell_file(script_file: Union[str, Path], tag: str, quiet: bool = False, script_file_args: List[str] = None, stdin: str = None) -> Tuple[int, str, str]: """Invoke PowerShell, passing just ``filename`` or ``filename`` and a list of arguments for execution of the file :param script_file: The path of the script file to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :param script_file_args: List of string arguments if required while execution of the file :param stdin: string to pass through standard input :return: Tuple containing (exit_code, stdout, stderr) """ command = ['powershell.exe', '-ExecutionPolicy', 'Unrestricted', '-File', str(script_file)] if script_file_args: for arg in script_file_args: command.append(str(arg)) return runCommand(command, tag, stdInput=stdin, omitOutput=quiet) def run_uapi_command(cmd_list: Union[str, List[str]], description: str, op_name: str, use_shell: bool = False, omit_string: str = None) -> Tuple[bool, str, str]: """Run a command on the target machine :param cmd_list: string or list of strings that represents a command to be executed :param description: short description of what the command is doing :param op_name: name of the operation that is running the command :param use_shell: indicator that the command should be executed in a shell :param omit_string: a string to be removed from any logging output. :return: Tuple containing (exit_code, stdout, stderr) """ cmd_list_str = str(cmd_list) if omit_string: cmd_list_str = cmd_list_str.replace(omit_string, "<>") LOG.debug("run_uapi_command %s cmd_list: %s", op_name, cmd_list_str) exit_code, outs, errs = runCommand(cmd_list, description, useShell=use_shell, omitString=omit_string) LOG.debug("%s_result- %s - %s - %s", description, exit_code, outs, errs) return exit_code, outs, errs def run_multiple_uapi_commands(cmds_list: List[Tuple[str, Union[str, List[str]]]], op_name: str, use_shell: bool = False, omit_string: str = None) -> Tuple[bool, str, str]: """Run a command on the target machine :param cmds_list: List of tuples with description-command pairs :param op_name: name of the operation that is running the command :param use_shell: indicator that the command should be executed in a shell :param omit_string: a string to be removed from any logging output. :return: Tuple containing (exit_code, stdout, stderr) """ exit_code, outs, errs = 0, '', '' for description, cmd in cmds_list: exit_code, outs, errs = run_uapi_command(cmd, description, op_name, use_shell=use_shell, omit_string=omit_string) if exit_code != 0: return exit_code, outs, errs return exit_code, outs, errs def start_powershell_file(script_file: Union[str, Path]) -> Tuple[int, str, str]: """ Invoke PowerShell, passing just ``filename`` or ``filename`` and a list of arguments for execution of the file. Do not wait for the sub-process to complete. The exit code returned in the tuple only indicates whether or not the process was successfully started. :param script_file: The path of the script file to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :param script_file_args: List of string arguments if required while execution of the file :return: Tuple containing (exit_code, stdout, stderr) """ params = list2cmdline(['-ExecutionPolicy', 'Unrestricted', '-File', str(script_file)]) LOG.info("Staring PowerShell: powershell.exe %s", params) code = 0 if shell_start('powershell.exe', params=params) else 1 return code, '', '' def start_powershell(command: str) -> Tuple[int, str, str]: """Execute the code in ``command`` using PowerShell. :param command: Code to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :return: Tuple containing (exit_code, stdout, stderr) """ # Because the process started by this command could (and probably will) survive after this process has exited, # we can't delete the temporary file, here. # pylint: disable=consider-using-with temp = tempfile.NamedTemporaryFile(mode='w+t', suffix='.ps1', delete=False) temp.write(command) temp.close() LOG.debug("Running Powershell command: %s", command) return start_powershell_file(temp.name) helpers.py000064400000004554147205356560006605 0ustar00# -*- coding: utf-8 -*- """\ © Copyright. All rights reserved. """ from __future__ import unicode_literals from fileinput import FileInput from functools import reduce import sys class HandledFailureException(Exception): pass def edit_file_lines(filename, editfunc): """Iterates through the lines of the named file, calling the editfunc for each line, replacing the original file with the new output. """ with FileInput(files=(filename,), inplace=True) as f: for line in f: sys.stdout.write(editfunc(line)) def replace_file_lines_multiple(filename, replace_dict, firstword=True): """Iterates through the lines of the named file, and through a dictionary of match -> replace pairs, replacing all that apply for each line, and replacing the original file with the new output. """ with FileInput(files=(filename,), inplace=True) as f: for line in f: updated_line = line for match, replace in replace_dict.items(): updated_line = replace_line(updated_line, match, replace, firstword) sys.stdout.write(updated_line) def replace_line(line, match, replace, firstword=True): """Checks `line` to see if it starts with `match`; if yes, return `replace`, otherwise return the original `line`. If `firstword` is True, then the match must be followed by at least one space or tab (unless it matches the entire line), otherwise it is matched directly. Suitable for use as an editfunc with `edit_file_lines`. """ # pylint: disable=too-many-boolean-expressions if ( line.strip() == match or (firstword and (line.startswith(match+' ') or line.startswith(match+'\t'))) or (not firstword and line.startswith(match)) ): return replace return line def append_line(filename, line): """Appends a line to to the specified file. """ with open(filename, 'a', encoding='UTF-8') as file: file.write('\n') file.write(line) def create_file(filename, contents): """Creates the specified file, with the specified contents. Overwrites any file already existing at that location. """ with open(filename, 'w', encoding='UTF-8') as wf: wf.write(contents) def compose(*funcs): return reduce(lambda f, g: lambda x: f(g(x)), funcs, lambda x: x) retry.py000064400000004140147205356560006277 0ustar00# -*- coding: utf-8 -*- """\ © Copyright. All rights reserved. """ from __future__ import unicode_literals from datetime import datetime, timedelta from functools import wraps import logging LOG = logging.getLogger(__name__) class Retry: """Ops decorated with @retry can return a Retry instance to request retry with the interval and timeout as specified in the decorator. See also the RETRY sentinel if there is no intermediate_result. """ def __init__(self, intermediate_result=None): if not (intermediate_result is None or isinstance(intermediate_result, dict)): raise TypeError('Retry intermediate_result must be dictionary ' 'but got %s' % type(intermediate_result)) self.intermediate_result = intermediate_result def __str__(self): return 'Retry ' + str(self.__dict__) RETRY = Retry() # A Retry that can be returned from ops decorated with @retry # when there is no intermediate_result. def retry(interval=2, timeout=60): """Op decorator that returns a retry request to Nydus when the op returns a Retry instance. Op will be retried by Nydus after `interval` seconds. Returns failure at the specified timeout (seconds). """ def deco(original): @wraps(original) def wrapper(*args, **kw): intermediate_result = kw.get('intermediate_result', None) now = datetime.utcnow() timeout_abs = (intermediate_result and intermediate_result.get('timeout') or now + timedelta(seconds=timeout)) if now >= timeout_abs: msg = 'Timeout waiting for {} ({}s)'.format(getattr(original, '__name__', '?'), timeout) LOG.error(msg) return False, msg result = original(*args, **kw) if isinstance(result, Retry): ir = result.intermediate_result or {} ir.setdefault('timeout', timeout_abs) return False, ir, interval return result return wrapper return deco __pycache__/__init__.cpython-38.pyc000064400000003101147205356560013153 0ustar00U afY@sRddlmZddlZddlZddlZeedddZddZd eedd d Z dS) ) b64encodeN)sreturncCst|S)z?Return `s` base64-encoded. :param s: string to encode )rencodedecode)rrQ/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/customer_local_ops/util/__init__.pyb64strsr cCst|tr tttt||St|ttf}|s^zt|ttt t f}Wnt k r\YnX|rt |drtttt|| Stttt||St |dr||S||S)z!Homomorphic mapping of a functionitemsfmap) isinstancetuplemap functoolspartialr listdictfilterziprange TypeErrorhasattrr )funcobjZ iterableitemsrrrr s    r )lengthrcsJ|stdd}tjdddddddfddt|DS) z}Create a random password. :param length: An int specifying password length :returns: the password, in cleartext "'\cs"g|]}ttjtjqSr)randomchoicestringdigits ascii_letters).0XZedited_punctuationrr 0sz#random_password..)r!randintr# punctuationreplacejoinr)rrr(rrandom_password's  r.)N) base64rrr!r#strr r intr.rrrrs __pycache__/execute.cpython-38.pyc000064400000041503147205356560013066 0ustar00U afN@sddlZddlZddlZddlZddlZddlmZddlmZm Z m Z m Z ddlm Z ddl mZddlmZeddZeeZd eZe eeefZejd krddlZdd lmZdd lmZeZeZeZ eZ!dd ej"ej#dddddddf eeeeeeeee e!eee$d ddZ%ne$dddZ%ddZ&ddZ'ddZ(ddZ)GdddZ*ddZ+Gdd d Z,dd&d'Z/d?eee$e eeefd(d)d*Z0d@e eefee$e eee eeefd+d,d-Z1dAe eefee$e eee eeefd+d.d/Z2dBe ee efeee$ee e$eefd0d1d2Z3dCe e ee ee effee$ee e$eefd3d4d5Z4e eefe eeefd6d7d8Z5ee eeefd9d:d;Z6dS)DN)Path)AnyTupleUnionList) list2cmdline)ByteSize)fmap )ZKiByteswin32)shellcon)shellopen) file_nameparamsverbshowmaskdir_nameid_listclass_id class_keyhot_keymonitorwindowreturnc sttddfdd } i| d|| d| | d|| d|| d || d || d || d || d || d|| d| | d| tjfS)a Wrapper for the Win32 API call ShellExecuteEx. This function can be used on Windows platforms any time Nydus needs to restart itself for any reason because ShellExecuteEx allows the child process to survive after its parent process stops. Initially added to resolve a DLL conflict issue, this could also be useful for upgrading Nydus, for example. Further information for ShellExecuteEx can be found at https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecuteexa :param file_name: The name of the executable to be started. ShellExecuteEx also handles file associations, so this could also be the name of a document, for example, to be opened with the associated application, or a URL to be opened by the user's default browser. :param params: Parameters to be passed to the application. Should not be specified if file_name is NOT an executable file. :param verb: Action to take. May be one of 'edit', 'explore', 'find', 'open', 'print', 'properties' or 'runas'. Defaults to 'open' :param show: Specify how an application is to be shown :param mask: Flags that indicate content and validity of other parameters :param dir_name: Name of the working directory. If None, the current directory is used :param id_list: See Microsoft documentation at the URL above :param class_id: See Microsoft documentation at the URL above :param class_key: See Microsoft documentation at the URL above :param hot_key: See Microsoft documentation at the URL above :param monitor: See Microsoft documentation at the URL above :param window: See Microsoft documentation at the URL above :return: True if the file/application is successfully launched; otherwise, False N)keyvalrcs|dk r||<dS)aC It is an error to include a field with a value of None in the structure passed to ShellExecuteEx, so this function only adds a key to the dictionary if the value is not None. :param key: The name of the SHELLEXECUTEINFO field :param val: The value of the field N)rrZshell_execute_inforP/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/customer_local_ops/util/execute.py add_fieldKszshell_start..add_fieldZfMaskZhwndZlpVerbZlpFileZ lpParametersZ lpDirectoryZnShowZlpIDListZlpClassZ hkeyClassZdwHotKeyZhMonitor)strrrZShellExecuteEx) rrrrrrrrrrrrr"rr r! shell_start$s'             r$)rcKsdSNTr)kwargsrrr!r$fscCsd|S)Nz| r)linerrr!pfxjsr(cCsttt|SN)listmapr()linesrrr!pfxsnsr-cCs|dk r||dd}|d}|s,|St|dkrH|dsHgSt|dkr\t|St|dddt|d g|d dS) z0Converts input blob to lines... but not too manyN <> r z...elided %d lines... )replacestripsplitlenr-)inpoutZoutlrrr!trim_visible_output_to_linesrs r;ccs*|}|r&|dD]}d|VqdS)z0Converts error blob into lines with prefix marksr0zERR: N)r6r7)ZerrOutseLrrr!mark_error_outputsr>c@s*eZdZdZd ddZddZddZdS) EndsBufferaString buffer that maintains two segments: a first segment and a last segment (i.e. the two ends), where each has a maximum size limit. Any extra output in between these is discarded. The assumption is that if there is a huge amount of output that some must be discarded to avoid memory overflows and that generally the first and last stuff is the most relevant. NcCs(ttd|p dpt|_d|_d|_dS)NrF)rmaxDEFAULT_MAX_SEGMENT_SIZE_mss_data_elided)selfZmax_segment_sizerrr!__init__szEndsBuffer.__init__cCsT|j|7_t|j|jdkrP|jd|j|jt|j d|_d|_dSNr T)rDr8rCintrE)rFdatarrr!add_strs(zEndsBuffer.add_strcCs:|jr4d|jd|jd|jt|j dgS|jS)Nr0z...[elided]...)rEjoinrDrCrIrFrrr! get_bufstrszEndsBuffer.get_bufstr)N)__name__ __module__ __qualname____doc__rGrKrNrrrr!r?s r?c Csz|jdddWStk rxz>ddl}z|||dWWYStk rZYnXWntk rrYnXYntk r|YSXdS)Nutf-8backslashreplace)errorsrencoding)decodeUnicodeDecodeErrorchardetdetect ImportErrorAttributeError)ZbytestrrYrrr!str_forms  r]c@s:eZdZefddZddZddZddZd d d Zd S)RunningCommandcCs\||_||_||_|pt|fdd|_||_t|jd|_t|jd|_d|_ d|_ dS)NcSst||r|sdndS)Nerrorinfo)getattr)rZ_lerrr!sz)RunningCommand.__init__..r F) ptagstdInputLOGlogger_bufsizer?_output_errors_partial _completed)rF popen_objrfrgerrorOKrimax_buffer_sizerrr!rGszRunningCommand.__init__cCs>|jt|jj|jt|jj|jdk Sr)) rkrKr]restdoutreadrlstderrpollrMrrr!checkIfCompletedszRunningCommand.checkIfCompletedcCsB|j}|j}t|jd|_t|jd|_d|_||fSrH)rkrNrlr?rjrmrForcrrr! outputToDates   zRunningCommand.outputToDatecCs6tt|j\}}|j||j|d|_|Sr%)r r]re communicaterkrKrlrnrwrrr!waitForCompletions   z RunningCommand.waitForCompletionFcCs|js||j|j}}t|j|}|rBdd|D}|tt|d|j j gD]$}|j d|}| |j j |q`|j j | | fS)NcSsg|]}|dr|ndqS)r. <>) startswith).0r'rrr! sz,RunningCommand.getResult..z ExitCode: %d )rnr{rkrNrlr;rgr*r>re returncoderfrir6)rF omitOutputoutserrsZ output_linesr'Zlstrrrr! getResults   zRunningCommand.getResultN)F) rOrPrQ MAX_COMMAND_RESPONSE_BUFFER_SIZErGrvryr{rrrrr!r^s   r^Fc Cst|trd|n|}d} t|trF|dk rBt|trB|d}d} |rV||| }|dkrbt}||dt|t j ||t j t j t j |d} |r| j |t| ||||S)aStarts the specified command; no Shell. The cmd is expected to be an array of strings, although it is also possible to specify simply a string if there are no arguments to the command. The tag value is only used to annotate log lines for distinctive tagging in the logging output. If errorOK is True then a non-zero return code is still only logged as "info" instead of "error". The ProcOpResult will accurately reflect the result of the operation regardless of the errorOK argument. If omitString is specified, it is removed from any logging output. The command is run asynchronously in a separate process. The return value is a RunningCommand object that supports a .checkIfCompleted() method to test for subprocess completion (non-blocking) and a .getResult() to get the ProcOpResult of a completed process (will block until completion if not already completed). rr|NrSs <>z RUN: )rrrstdinrtenv) isinstancer*rLbytesr#encoder5rhr` subprocessPopenPIPErwriter^) cmdrfuseShellrgrpri omitStringrZlog_cmdZ replace_textrerrr! startCommands*   rc Cs$t||||||||dj|dS)aRuns the specified command and waits for completion; no Shell. The cmd is expected to be an array of strings, although it is also possible to specify simply a string if there are no arguments to the command. The tag value is only used to annotate log lines for distinctive tagging in the logging output. If errorOK is True then a non-zero return code is still only logged as "info" instead of "error". The ProcOpResult will accurately reflect the result of the operation regardless of the errorOK argument. If omitString is specified, it is removed from any logging output. )rrgrprirr)r)rr{r) rrfrrgrprirrrrrr! runCommands rc CsFtj||tjd}|&|\}}|j||fW5QRSQRXdS)z(Used to run commands that make use of | )rrrN)rrrrzr)rrrerxrcrrr!run_command_pipe;s r)commandrfquietrc CsZtjddddd}z4||||s6td|t |j||WSt|jXdS))Execute the code in ``command`` using PowerShell. :param command: Code to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :return: Tuple containing (exit_code, stdout, stderr) w+tz utf-8-sig.ps1F)moderVsuffixdeletezRunning PowerShell command: %sN) tempfileNamedTemporaryFileosunlinknamercloserhdebugrun_powershell_file)rrfrtemprrr!run_powershellCs  r) script_filerfrscript_file_argsrrcCs8dt|g}|r(|D]}|t|qt||||dS)aInvoke Shell script, passing just ``filename`` or ``filepath`` and a list of arguments for execution of the file :param script_file: The path of the script file to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :param script_file_args: List of string arguments if required while execution of the file :param stdin: string to pass through standard input :return: Tuple containing (exit_code, stdout, stderr) Zbashrgrr#appendrrrfrrrrargrrr!run_shell_script_fileas rcCs>ddddt|g}|r.|D]}|t|qt||||dS)aInvoke PowerShell, passing just ``filename`` or ``filename`` and a list of arguments for execution of the file :param script_file: The path of the script file to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :param script_file_args: List of string arguments if required while execution of the file :param stdin: string to pass through standard input :return: Tuple containing (exit_code, stdout, stderr) powershell.exe-ExecutionPolicy Unrestricted-Filerrrrrr!rts r)cmd_list descriptionop_name use_shell omit_stringrc CsXt|}|r||d}td||t||||d\}}}td|||||||fS)aRun a command on the target machine :param cmd_list: string or list of strings that represents a command to be executed :param description: short description of what the command is doing :param op_name: name of the operation that is running the command :param use_shell: indicator that the command should be executed in a shell :param omit_string: a string to be removed from any logging output. :return: Tuple containing (exit_code, stdout, stderr) r|z run_uapi_command %s cmd_list: %s)rrz%s_result- %s - %s - %s)r#r5rhrr) rrrrrZ cmd_list_str exit_coderrrrr!run_uapi_commands  r) cmds_listrrrrc CsPd\}}}|D]6\}}t|||||d\}}}|dkr|||fSq|||fS)aRun a command on the target machine :param cmds_list: List of tuples with description-command pairs :param op_name: name of the operation that is running the command :param use_shell: indicator that the command should be executed in a shell :param omit_string: a string to be removed from any logging output. :return: Tuple containing (exit_code, stdout, stderr) )rr@r@)rrr)r) rrrrrrrrrrrr!run_multiple_uapi_commandss    r)rrcCs>tdddt|g}td|td|dr0dnd}|d d fS) a Invoke PowerShell, passing just ``filename`` or ``filename`` and a list of arguments for execution of the file. Do not wait for the sub-process to complete. The exit code returned in the tuple only indicates whether or not the process was successfully started. :param script_file: The path of the script file to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :param script_file_args: List of string arguments if required while execution of the file :return: Tuple containing (exit_code, stdout, stderr) rrrz%Staring PowerShell: powershell.exe %sr)rrr/r@)rr#rhr`r$)rrcoderrr!start_powershell_files  r)rrcCs8tjdddd}|||td|t|jS)rrrF)rrrzRunning Powershell command: %s)rrrrrhrrr)rrrrr!start_powershells   r)FNFNNN)FNFNNFN)F)F)FNN)FNN)FN)FN)7loggingrsysrrpathlibrtypingrrrrrZprimordial.sizesrZcustomer_local_ops.utilr rB getLoggerrOrhrrIr#ZRunCommandResultplatformZwin32conwin32com.shellr rZHANDLEZHWNDZHKEYZDWORDZ SW_SHOWNORMALZSEE_MASK_FLAG_DDEWAITboolr$r(r-r;r>r?r]r^rrrrrrrrrrrrrr!s         B6 3       "__pycache__/helpers.cpython-38.pyc000064400000006015147205356560013065 0ustar00U afl @sxdZddlmZddlmZddlmZddlZGdddeZ dd Z dd d Z dd dZ ddZ ddZddZdS)u$© Copyright. All rights reserved. )unicode_literals) FileInputreduceNc@s eZdZdS)HandledFailureExceptionN)__name__ __module__ __qualname__r r P/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/customer_local_ops/util/helpers.pyrsrc Cs8t|fdd }|D]}tj||qW5QRXdS)zIterates through the lines of the named file, calling the editfunc for each line, replacing the original file with the new output. TfilesZinplaceN)rsysstdoutwrite)filenameZeditfuncfliner r r edit_file_linessrTc CsXt|fdd@}|D]4}|}|D]\}}t||||}q$tj|qW5QRXdS)zIterates through the lines of the named file, and through a dictionary of match -> replace pairs, replacing all that apply for each line, and replacing the original file with the new output. Tr N)ritems replace_linerrr)rZ replace_dict firstwordrrZ updated_linematchreplacer r r replace_file_lines_multiples rcCsB||ks:|r,||ds:||ds:|s>||r>|S|S)amChecks `line` to see if it starts with `match`; if yes, return `replace`, otherwise return the original `line`. If `firstword` is True, then the match must be followed by at least one space or tab (unless it matches the entire line), otherwise it is matched directly. Suitable for use as an editfunc with `edit_file_lines`.   )strip startswith)rrrrr r r r)s   rc Cs2t|ddd}|d||W5QRXdS)z-Appends a line to to the specified file. aUTF-8encoding Nopenr)rrfiler r r append_line<s r'c Cs(t|ddd}||W5QRXdS)z{Creates the specified file, with the specified contents. Overwrites any file already existing at that location. wr r!Nr$)rcontentsZwfr r r create_fileDsr*cGstdd|ddS)NcsfddS)Ncs |SNr xrgr r Mz+compose....r r.r r.r r0Mr1zcompose..cSs|Sr+r r,r r r r0Mr1r)funcsr r r composeLsr3)T)T)__doc__ __future__rZ fileinputr functoolsrr Exceptionrrrrr'r*r3r r r r s    __pycache__/retry.cpython-38.pyc000064400000004312147205356560012566 0ustar00U af`@s`dZddlmZddlmZmZddlmZddlZee Z GdddZ e Z d d d Z dS) u$© Copyright. All rights reserved. )unicode_literals)datetime timedeltawrapsNc@s"eZdZdZdddZddZdS)RetryzOps decorated with @retry can return a Retry instance to request retry with the interval and timeout as specified in the decorator. See also the RETRY sentinel if there is no intermediate_result. NcCs,|dks"t|ts"tdt|||_dS)Nz7Retry intermediate_result must be dictionary but got %s) isinstancedict TypeErrortypeintermediate_result)selfr rN/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/customer_local_ops/util/retry.py__init__szRetry.__init__cCsdt|jS)NzRetry )str__dict__)r rrr__str__sz Retry.__str__)N)__name__ __module__ __qualname____doc__rrrrrrrs r<csfdd}|S)zOp decorator that returns a retry request to Nydus when the op returns a Retry instance. Op will be retried by Nydus after `interval` seconds. Returns failure at the specified timeout (seconds). cstfdd}|S)Ncs|dd}t}|r"|dp.|td}||kr^dtdd}t|d|fS||}t|t r|j pzi}| d|d|fS|S)Nr timeout)secondszTimeout waiting for {} ({}s)r?F) getrutcnowrformatgetattrLOGerrorrrr setdefault)argskwr nowZ timeout_absmsgresultZir)intervaloriginalrrrwrapper,s"        z$retry..deco..wrapperr)r*r+r)r)r*rdeco+szretry..decor)r)rr-rr,rretry%sr.)rr)r __future__rrr functoolsrlogging getLoggerrr!rRETRYr.rrrrs