blob: 29ad241b62d63b3a2a5e52714087efae670cec12 [file] [log] [blame]
Dan Shi7836d252015-04-27 15:33:58 -07001# 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
Dan Shi7836d252015-04-27 15:33:58 -07008import common
9from autotest_lib.client.bin import utils
10from autotest_lib.client.common_lib import error
Christopher Wiley190ce462015-12-16 13:26:05 -080011from autotest_lib.client.common_lib.cros.network import interface
Dan Shi7836d252015-04-27 15:33:58 -070012
13
Dan Shi7836d252015-04-27 15:33:58 -070014def 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 """
Christopher Wiley190ce462015-12-16 13:26:05 -080040 # 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
Dan Shi7836d252015-04-27 15:33:58 -070045 lxc_network = None
Christopher Wiley190ce462015-12-16 13:26:05 -080046 for name in interface_names:
Dan Shi7836d252015-04-27 15:33:58 -070047 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' %
Christopher Wiley190ce462015-12-16 13:26:05 -080053 interface_names)
54 netif = interface.Interface(lxc_network)
55 return netif.ipv4_address