Commit 88d14415 authored by Michael Hanselmann's avatar Michael Hanselmann
Browse files

Add function to get all local IP addresses, will be used in cmdlib.py.

Reviewed-by: schreiberal
parent c1671c0e
......@@ -749,3 +749,38 @@ def ShellQuoteArgs(args):
"""
return ' '.join([ShellQuote(i) for i in args])
def _ParseIpOutput(output):
"""Parsing code for GetLocalIPAddresses().
This function is split out, so we can unit test it.
"""
re_ip = re.compile('^(\d+\.\d+\.\d+\.\d+)(?:/\d+)$')
ips = []
for line in output.splitlines(False):
fields = line.split()
if len(line) < 4:
continue
m = re_ip.match(fields[3])
if m:
ips.append(m.group(1))
return ips
def GetLocalIPAddresses():
"""Gets a list of all local IP addresses.
Should this break one day, a small Python module written in C could
use the API call getifaddrs().
"""
result = RunCmd(["ip", "-family", "inet", "-oneline", "addr", "show"])
if result.failed:
raise errors.OpExecError("Command '%s' failed, error: %s,"
" output: %s" % (result.cmd, result.fail_reason, result.output))
return _ParseIpOutput(result.output)
......@@ -32,7 +32,7 @@ import ganeti
from ganeti.utils import IsProcessAlive, Lock, Unlock, RunCmd, \
RemoveFile, CheckDict, MatchNameComponent, FormatUnit, \
ParseUnit, AddAuthorizedKey, RemoveAuthorizedKey, \
ShellQuote, ShellQuoteArgs
ShellQuote, ShellQuoteArgs, _ParseIpOutput
from ganeti.errors import LockError, UnitParseError
class TestIsProcessAlive(unittest.TestCase):
......@@ -424,5 +424,31 @@ class TestShellQuoting(unittest.TestCase):
self.assertEqual(ShellQuoteArgs(['a', 'b\'', 'c']), "a 'b'\\\''' c")
class TestIpAdressList(unittest.TestCase):
"""Test case for local IP addresses"""
def _test(self, output, required):
ips = _ParseIpOutput(output)
# Sort the output, so our check below works in all cases
ips.sort()
required.sort()
self.assertEqual(required, ips)
def testSingleIpAddress(self):
output = \
("3: lo inet 127.0.0.1/8 brd 127.255.255.255 scope host lo\n"
"5: eth0 inet 10.0.0.1/24 brd 172.30.15.127 scope global eth0\n")
self._test(output, ['127.0.0.1', '10.0.0.1'])
def testMultipleIpAddresses(self):
output = \
("3: lo inet 127.0.0.1/8 brd 127.255.255.255 scope host lo\n"
"5: eth0 inet 10.0.0.1/24 brd 172.30.15.127 scope global eth0\n"
"5: eth0 inet 1.2.3.4/8 brd 1.255.255.255 scope global eth0:test\n")
self._test(output, ['127.0.0.1', '10.0.0.1', '1.2.3.4'])
if __name__ == '__main__':
unittest.main()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment