def test_timeout(self): # we expect a logging.warn() message, don't care about the contents base_utils.logging.warn.expect_any_call() try: base_utils.run('echo -n output && sleep 10', timeout=1, verbose=False) except base_utils.error.CmdError, err: self.assertEquals(err.result_obj.stdout, 'output')
def remote_wget(source_url, dest_path, ssh_cmd): """wget source_url from localhost to dest_path on remote host using ssh. @param source_url: The complete url of the source of the package to send. @param dest_path: The path on the remote host's file system where we would like to store the package. @param ssh_cmd: The ssh command to use in performing the remote wget. """ wget_cmd = ("wget -O - %s | %s 'cat >%s'" % (source_url, ssh_cmd, dest_path)) base_utils.run(wget_cmd)
def sudo_require_password(): """Test if the process can run sudo command without using password. @return: True if the process needs password to run sudo command. """ try: base_utils.run('sudo -n true') return False except error.CmdError: logging.warn('sudo command requires password.') return True
def ping(host, deadline=None, tries=None, timeout=60): """Attempt to ping |host|. Shell out to 'ping' to try to reach |host| for |timeout| seconds. Returns exit code of ping. Per 'man ping', if you specify BOTH |deadline| and |tries|, ping only returns 0 if we get responses to |tries| pings within |deadline| seconds. Specifying |deadline| or |count| alone should return 0 as long as some packets receive responses. @param host: the host to ping. @param deadline: seconds within which |tries| pings must succeed. @param tries: number of pings to send. @param timeout: number of seconds after which to kill 'ping' command. @return exit code of ping command. """ args = [host] if deadline: args.append('-w%d' % deadline) if tries: args.append('-c%d' % tries) return base_utils.run('ping', args=args, ignore_status=True, timeout=timeout, stdout_tee=base_utils.TEE_TO_LOGS, stderr_tee=base_utils.TEE_TO_LOGS).exit_status
def test_safe_args(self): cmd = 'echo "hello \\"world" "again"' self.__check_result(base_utils.run('echo', verbose=False, args=('hello "world', 'again')), cmd, stdout='hello "world again\n')
def test_ignore_status(self): cmd = 'echo error >&2 && exit 11' self.__check_result(base_utils.run(cmd, ignore_status=True, verbose=False), cmd, exit_status=11, stderr='error\n')
def get_sleep_state(): """ Returns the current powerd configuration of the sleep state. Can be "freeze" or "mem". """ cmd = 'check_powerd_config --suspend_to_idle' result = base_utils.run(cmd, ignore_status=True) return 'freeze' if result.exit_status == 0 else 'mem'
def is_in_container(): """Check if the process is running inside a container. @return: True if the process is running inside a container, otherwise False. """ result = base_utils.run('grep -q "/lxc/" /proc/1/cgroup', verbose=False, ignore_status=True) return result.exit_status == 0
def test_safe_args(self): # NOTE: The string in expected_quoted_cmd depends on the internal # implementation of shell quoting which is used by base_utils.run(), # in this case, sh_quote_word(). expected_quoted_cmd = "echo 'hello \"world' again" self.__check_result(base_utils.run('echo', verbose=False, args=('hello "world', 'again')), expected_quoted_cmd, stdout='hello "world again\n')
def get_interface_mac_address(interface): """Return the MAC address of a given interface. @param interface: Interface to look up the MAC address of. """ interface_link = base_utils.run('ip addr show %s | grep link/ether' % interface).stdout # The output will be in the format of: # 'link/ether <mac> brd ff:ff:ff:ff:ff:ff' return interface_link.split()[1]
def __init__(self): cmd = 'check_powerd_config --keyboard_backlight' result = base_utils.run(cmd, ignore_status=True) if result.exit_status: raise KbdBacklightException('Keyboard backlight support' + 'is not enabled') cmd = 'get_powerd_initial_backlight_level --keyboard 2>/dev/null' self._default_backlight_level = int(utils.system_output(cmd).rstrip()) logging.info("Default keyboard backlight brightness level = %d", self._default_backlight_level)
def test_stdout_stderr_tee(self): cmd = 'echo output && echo error >&2' stdout_tee = StringIO.StringIO() stderr_tee = StringIO.StringIO() self.__check_result(base_utils.run( cmd, stdout_tee=stdout_tee, stderr_tee=stderr_tee, verbose=False), cmd, stdout='output\n', stderr='error\n') self.assertEqual(stdout_tee.getvalue(), 'output\n') self.assertEqual(stderr_tee.getvalue(), 'error\n')
def get_service_pid(service_name): """Return pid of service. @param service_name: string name of service. @return: pid or 0 if service is not running. """ if has_systemd(): # systemctl show prints 'MainPID=0' if the service is not running. cmd_result = base_utils.run('systemctl show -p MainPID %s' % service_name, ignore_status=True) return int(cmd_result.stdout.split('=')[1]) else: cmd_result = base_utils.run('status %s' % service_name, ignore_status=True) if 'start/running' in cmd_result.stdout: return int(cmd_result.stdout.split()[3]) return 0
def get_built_in_ethernet_nic_name(): """Gets the moblab public network interface. If the eth0 is an USB interface, try to use eth1 instead. Otherwise use eth0 by default. """ try: cmd_result = base_utils.run('readlink -f /sys/class/net/eth0') if cmd_result.exit_status == 0 and 'usb' in cmd_result.stdout: cmd_result = base_utils.run('readlink -f /sys/class/net/eth1') if cmd_result.exit_status == 0 and not ('usb' in cmd_result.stdout): logging.info('Eth0 is a USB dongle, use eth1 as moblab nic.') return _MOBLAB_ETH_1 except error.CmdError: # readlink is not supported. logging.info('No readlink available, use eth0 as moblab nic.') pass return _MOBLAB_ETH_0
def test_stdout_stderr_tee(self): cmd = 'echo output && echo error >&2' stdout_tee = StringIO.StringIO() stderr_tee = StringIO.StringIO() self.__check_result(base_utils.run(cmd, stdout_tee=stdout_tee, stderr_tee=stderr_tee, verbose=False), cmd, stdout='output\n', stderr='error\n') self.assertEqual(stdout_tee.getvalue(), 'output\n') self.assertEqual(stderr_tee.getvalue(), 'error\n')
def _has_light_sensor(self): """ Determine if there is a light sensor on the board. @returns True if this host has a light sensor or False if it does not. """ # If the command exits with a failure status, # we do not have a light sensor cmd = 'check_powerd_config --ambient_light_sensor' result = base_utils.run(cmd, ignore_status=True) if result.exit_status: logging.debug('Ambient light sensor not present') return False logging.debug('Ambient light sensor present') return True
def _has_hover_detection(self): """ Checks if hover is detected by the device. Returns: Returns True if the hover detection support is enabled. Else returns false. """ cmd = 'check_powerd_config --hover_detection' result = base_utils.run(cmd, ignore_status=True) if result.exit_status: logging.debug('Hover not present') return False logging.debug('Hover present') return True
def ping(host, deadline=None, tries=None, timeout=60): """Attempt to ping |host|. Shell out to 'ping' if host is an IPv4 addres or 'ping6' if host is an IPv6 address to try to reach |host| for |timeout| seconds. Returns exit code of ping. Per 'man ping', if you specify BOTH |deadline| and |tries|, ping only returns 0 if we get responses to |tries| pings within |deadline| seconds. Specifying |deadline| or |count| alone should return 0 as long as some packets receive responses. Note that while this works with literal IPv6 addresses it will not work with hostnames that resolve to IPv6 only. @param host: the host to ping. @param deadline: seconds within which |tries| pings must succeed. @param tries: number of pings to send. @param timeout: number of seconds after which to kill 'ping' command. @return exit code of ping command. """ args = [host] ping_cmd = 'ping6' if re.search(r':.*:', host) else 'ping' if deadline: args.append('-w%d' % deadline) if tries: args.append('-c%d' % tries) return base_utils.run(ping_cmd, args=args, verbose=True, ignore_status=True, timeout=timeout, stdout_tee=base_utils.TEE_TO_LOGS, stderr_tee=base_utils.TEE_TO_LOGS).exit_status
def test_default_failure(self): cmd = 'exit 11' try: base_utils.run(cmd, verbose=False) except base_utils.error.CmdError, err: self.__check_result(err.result_obj, cmd, exit_status=11)
def test_default_simple(self): cmd = 'echo "hello world"' # expect some king of logging.debug() call but don't care about args base_utils.logging.debug.expect_any_call() self.__check_result(base_utils.run(cmd), cmd, stdout='hello world\n')
def gs_upload(local_file, remote_file, acl, result_dir=None, transfer_timeout=300, acl_timeout=300): """Upload to GS bucket. @param local_file: Local file to upload @param remote_file: Remote location to upload the local_file to. @param acl: name or file used for controlling access to the uploaded file. @param result_dir: Result directory if you want to add tracing to the upload. @param transfer_timeout: Timeout for this upload call. @param acl_timeout: Timeout for the acl call needed to confirm that the uploader has permissions to execute the upload. @raise CmdError: the exit code of the gsutil call was not 0. @returns True/False - depending on if the upload succeeded or failed. """ # https://developers.google.com/storage/docs/accesscontrol#extension CANNED_ACLS = [ 'project-private', 'private', 'public-read', 'public-read-write', 'authenticated-read', 'bucket-owner-read', 'bucket-owner-full-control' ] _GSUTIL_BIN = 'gsutil' acl_cmd = None if acl in CANNED_ACLS: cmd = '%s cp -a %s %s %s' % (_GSUTIL_BIN, acl, local_file, remote_file) else: # For private uploads we assume that the overlay board is set up # properly and a googlestore_acl.xml is present, if not this script # errors cmd = '%s cp -a private %s %s' % (_GSUTIL_BIN, local_file, remote_file) if not os.path.exists(acl): logging.error('Unable to find ACL File %s.', acl) return False acl_cmd = '%s setacl %s %s' % (_GSUTIL_BIN, acl, remote_file) if not result_dir: base_utils.run(cmd, timeout=transfer_timeout, verbose=True) if acl_cmd: base_utils.run(acl_cmd, timeout=acl_timeout, verbose=True) return True with open(os.path.join(result_dir, 'tracing'), 'w') as ftrace: ftrace.write('Preamble\n') base_utils.run(cmd, timeout=transfer_timeout, verbose=True, stdout_tee=ftrace, stderr_tee=ftrace) if acl_cmd: ftrace.write('\nACL setting\n') # Apply the passed in ACL xml file to the uploaded object. base_utils.run(acl_cmd, timeout=acl_timeout, verbose=True, stdout_tee=ftrace, stderr_tee=ftrace) ftrace.write('Postamble\n') return True
def test_stdin_string(self): cmd = 'cat' self.__check_result(base_utils.run(cmd, verbose=False, stdin='hi!\n'), cmd, stdout='hi!\n')
def test_safe_args(self): cmd = 'echo "hello \\"world" "again"' self.__check_result(base_utils.run( 'echo', verbose=False, args=('hello "world', 'again')), cmd, stdout='hello "world again\n')