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

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

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:
m = re_ip.match(fields[3])
if m:
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
self.assertEqual(required, ips)
def testSingleIpAddress(self):
output = \
("3: lo inet brd scope host lo\n"
"5: eth0 inet brd scope global eth0\n")
self._test(output, ['', ''])
def testMultipleIpAddresses(self):
output = \
("3: lo inet brd scope host lo\n"
"5: eth0 inet brd scope global eth0\n"
"5: eth0 inet brd scope global eth0:test\n")
self._test(output, ['', '', ''])
if __name__ == '__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