Dan Shi | 7836d25 | 2015-04-27 15:33:58 -0700 | [diff] [blame] | 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 | |
Dan Shi | 7836d25 | 2015-04-27 15:33:58 -0700 | [diff] [blame] | 8 | import common |
| 9 | from autotest_lib.client.bin import utils |
| 10 | from autotest_lib.client.common_lib import error |
Christopher Wiley | 190ce46 | 2015-12-16 13:26:05 -0800 | [diff] [blame] | 11 | from autotest_lib.client.common_lib.cros.network import interface |
Dan Shi | 7836d25 | 2015-04-27 15:33:58 -0700 | [diff] [blame] | 12 | |
| 13 | |
Dan Shi | 7836d25 | 2015-04-27 15:33:58 -0700 | [diff] [blame] | 14 | def 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 | |
| 32 | def 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 Wiley | 190ce46 | 2015-12-16 13:26:05 -0800 | [diff] [blame] | 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 | |
Dan Shi | 7836d25 | 2015-04-27 15:33:58 -0700 | [diff] [blame] | 45 | lxc_network = None |
Christopher Wiley | 190ce46 | 2015-12-16 13:26:05 -0800 | [diff] [blame] | 46 | for name in interface_names: |
Dan Shi | 7836d25 | 2015-04-27 15:33:58 -0700 | [diff] [blame] | 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' % |
Christopher Wiley | 190ce46 | 2015-12-16 13:26:05 -0800 | [diff] [blame] | 53 | interface_names) |
| 54 | netif = interface.Interface(lxc_network) |
| 55 | return netif.ipv4_address |