1# Copyright 2015 The Chromium 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
5"""This module provides some utilities used by LXC and its tools.
6"""
7
8import common
9from autotest_lib.client.bin import utils
10from autotest_lib.client.common_lib import error
11from autotest_lib.client.common_lib.cros.network import interface
12
13
14def path_exists(path):
15    """Check if path exists.
16
17    If the process is not running with root user, os.path.exists may fail to
18    check if a path owned by root user exists. This function uses command
19    `test -e` to check if path exists.
20
21    @param path: Path to check if it exists.
22
23    @return: True if path exists, otherwise False.
24    """
25    try:
26        utils.run('sudo test -e "%s"' % path)
27        return True
28    except error.CmdError:
29        return False
30
31
32def get_host_ip():
33    """Get the IP address of the host running containers on lxcbr*.
34
35    This function gets the IP address on network interface lxcbr*. The
36    assumption is that lxc uses the network interface started with "lxcbr".
37
38    @return: IP address of the host running containers.
39    """
40    # The kernel publishes symlinks to various network devices in /sys.
41    result = utils.run('ls /sys/class/net', ignore_status=True)
42    # filter out empty strings
43    interface_names = [x for x in result.stdout.split() if x]
44
45    lxc_network = None
46    for name in interface_names:
47        if name.startswith('lxcbr'):
48            lxc_network = name
49            break
50    if not lxc_network:
51        raise error.ContainerError('Failed to find network interface used by '
52                                   'lxc. All existing interfaces are: %s' %
53                                   interface_names)
54    netif = interface.Interface(lxc_network)
55    return netif.ipv4_address
56