• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2014 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import os
6
7from autotest_lib.client.bin import utils
8from autotest_lib.client.common_lib import error
9
10
11def get_install_path(filename, host=None):
12    """
13    Checks if a file exists on a remote machine in one of several paths.
14
15    @param filename String name of the file to check for existence.
16    @param host Host object representing the remote machine.
17    @return String full path of installed file, or None if not found.
18
19    """
20    run = utils.run
21    if host is not None:
22        run = host.run
23    PATHS = ['/bin',
24             '/sbin',
25             '/system/bin',
26             '/system/xbin',
27             '/usr/bin',
28             '/usr/sbin',
29             '/usr/local/bin',
30             '/usr/local/sbin']
31    glob_list = [os.path.join(path, filename) for path in PATHS]
32    # Some hosts have poor support for which.  Sometimes none.
33    # Others have shells that can't perform advanced globbing.
34    result = host.run('ls %s 2> /dev/null' % ' '.join(glob_list),
35                      ignore_status=True)
36    found_path = result.stdout.split('\n')[0].strip()
37    return found_path or None
38
39
40def must_be_installed(cmd, host=None):
41    """
42    Asserts that cmd is installed on a remote machine at some path and raises
43    an exception if this is not the case.
44
45    @param cmd String name of the command to check for existence.
46    @param host Host object representing the remote machine.
47    @return String full path of cmd on success.  Error raised on failure.
48
49    """
50    run = utils.run
51    if host is not None:
52        run = host.run
53    if run('ls %s >/dev/null 2>&1' % cmd,
54           ignore_status=True).exit_status == 0:
55        return cmd
56
57    # Hunt for the equivalent file in a bunch of places.
58    cmd_base = os.path.basename(cmd)
59    alternate_path = get_install_path(cmd_base, host=host)
60    if alternate_path:
61        return alternate_path
62
63    error_msg = 'Unable to find %s' % cmd
64    if host is not None:
65        error_msg += ' on %s' % host.hostname
66    raise error.TestError(error_msg)
67