diff options
Diffstat (limited to 'google_compute_engine/distro_lib')
17 files changed, 881 insertions, 1 deletions
diff --git a/google_compute_engine/distro_lib/debian_8/tests/utils_test.py b/google_compute_engine/distro_lib/debian_8/tests/utils_test.py index e529a26..6ff9f9c 100644 --- a/google_compute_engine/distro_lib/debian_8/tests/utils_test.py +++ b/google_compute_engine/distro_lib/debian_8/tests/utils_test.py @@ -44,3 +44,12 @@ class UtilsTest(unittest.TestCase): utils.Utils.HandleClockSync(self.mock_setup, self.mock_logger) expected_calls = [mock.call.call(mock.ANY)] self.assertEqual(mocks.mock_calls, expected_calls) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.IpForwardingUtilsIproute') + def testIpForwardingUtils(self, mock_call): + mocks = mock.Mock() + mocks.attach_mock(mock_call, 'call') + + utils.Utils.IpForwardingUtils(self.mock_setup, self.mock_logger, '66') + expected_calls = [mock.call.call(mock.ANY, '66')] + self.assertEqual(mocks.mock_calls, expected_calls) diff --git a/google_compute_engine/distro_lib/debian_8/utils.py b/google_compute_engine/distro_lib/debian_8/utils.py index 6666269..9bdccb8 100644 --- a/google_compute_engine/distro_lib/debian_8/utils.py +++ b/google_compute_engine/distro_lib/debian_8/utils.py @@ -16,6 +16,7 @@ """Utilities that are distro specific for use on Debian 8.""" from google_compute_engine.distro_lib import helpers +from google_compute_engine.distro_lib import ip_forwarding_utils from google_compute_engine.distro_lib import utils @@ -40,3 +41,12 @@ class Utils(utils.Utils): logger: logger object, used to write to SysLog and serial port. """ helpers.CallHwclock(logger) + + def IpForwardingUtils(self, logger, proto_id=None): + """Get system IP address configuration utilities. + + Args: + logger: logger object, used to write to SysLog and serial port. + proto_id: string, the routing protocol identifier for Google IP changes. + """ + return ip_forwarding_utils.IpForwardingUtilsIproute(logger, proto_id) diff --git a/google_compute_engine/distro_lib/debian_9/tests/utils_test.py b/google_compute_engine/distro_lib/debian_9/tests/utils_test.py index ebfde1a..2717f00 100644 --- a/google_compute_engine/distro_lib/debian_9/tests/utils_test.py +++ b/google_compute_engine/distro_lib/debian_9/tests/utils_test.py @@ -44,3 +44,12 @@ class UtilsTest(unittest.TestCase): utils.Utils.HandleClockSync(self.mock_setup, self.mock_logger) expected_calls = [mock.call.call(mock.ANY)] self.assertEqual(mocks.mock_calls, expected_calls) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.IpForwardingUtilsIproute') + def testIpForwardingUtils(self, mock_call): + mocks = mock.Mock() + mocks.attach_mock(mock_call, 'call') + + utils.Utils.IpForwardingUtils(self.mock_setup, self.mock_logger, '66') + expected_calls = [mock.call.call(mock.ANY, '66')] + self.assertEqual(mocks.mock_calls, expected_calls) diff --git a/google_compute_engine/distro_lib/debian_9/utils.py b/google_compute_engine/distro_lib/debian_9/utils.py index ad56ea1..452e02f 100644 --- a/google_compute_engine/distro_lib/debian_9/utils.py +++ b/google_compute_engine/distro_lib/debian_9/utils.py @@ -16,6 +16,7 @@ """Utilities that are distro specific for use on Debian 9.""" from google_compute_engine.distro_lib import helpers +from google_compute_engine.distro_lib import ip_forwarding_utils from google_compute_engine.distro_lib import utils @@ -40,3 +41,12 @@ class Utils(utils.Utils): logger: logger object, used to write to SysLog and serial port. """ helpers.CallHwclock(logger) + + def IpForwardingUtils(self, logger, proto_id=None): + """Get system IP address configuration utilities. + + Args: + logger: logger object, used to write to SysLog and serial port. + proto_id: string, the routing protocol identifier for Google IP changes. + """ + return ip_forwarding_utils.IpForwardingUtilsIproute(logger, proto_id) diff --git a/google_compute_engine/distro_lib/el_6/tests/utils_test.py b/google_compute_engine/distro_lib/el_6/tests/utils_test.py index dcfde8d..539b059 100644 --- a/google_compute_engine/distro_lib/el_6/tests/utils_test.py +++ b/google_compute_engine/distro_lib/el_6/tests/utils_test.py @@ -50,3 +50,12 @@ class UtilsTest(unittest.TestCase): utils.Utils.HandleClockSync(self.mock_setup, self.mock_logger) expected_calls = [mock.call.call(mock.ANY)] self.assertEqual(mocks.mock_calls, expected_calls) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.IpForwardingUtilsIproute') + def testIpForwardingUtils(self, mock_call): + mocks = mock.Mock() + mocks.attach_mock(mock_call, 'call') + + utils.Utils.IpForwardingUtils(self.mock_setup, self.mock_logger, '66') + expected_calls = [mock.call.call(mock.ANY, '66')] + self.assertEqual(mocks.mock_calls, expected_calls) diff --git a/google_compute_engine/distro_lib/el_6/utils.py b/google_compute_engine/distro_lib/el_6/utils.py index f3ea305..20b8e2f 100644 --- a/google_compute_engine/distro_lib/el_6/utils.py +++ b/google_compute_engine/distro_lib/el_6/utils.py @@ -16,6 +16,7 @@ """Utilities that are distro specific for use on EL 6.""" from google_compute_engine.distro_lib import helpers +from google_compute_engine.distro_lib import ip_forwarding_utils from google_compute_engine.distro_lib import utils @@ -40,3 +41,12 @@ class Utils(utils.Utils): logger: logger object, used to write to SysLog and serial port. """ helpers.CallHwclock(logger) + + def IpForwardingUtils(self, logger, proto_id=None): + """Get system IP address configuration utilities. + + Args: + logger: logger object, used to write to SysLog and serial port. + proto_id: string, the routing protocol identifier for Google IP changes. + """ + return ip_forwarding_utils.IpForwardingUtilsIproute(logger, proto_id) diff --git a/google_compute_engine/distro_lib/el_7/tests/utils_test.py b/google_compute_engine/distro_lib/el_7/tests/utils_test.py index e9803b7..17f81d0 100644 --- a/google_compute_engine/distro_lib/el_7/tests/utils_test.py +++ b/google_compute_engine/distro_lib/el_7/tests/utils_test.py @@ -129,3 +129,12 @@ class UtilsTest(unittest.TestCase): utils.Utils.HandleClockSync(self.mock_setup, self.mock_logger) expected_calls = [mock.call.call(mock.ANY)] self.assertEqual(mocks.mock_calls, expected_calls) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.IpForwardingUtilsIproute') + def testIpForwardingUtils(self, mock_call): + mocks = mock.Mock() + mocks.attach_mock(mock_call, 'call') + + utils.Utils.IpForwardingUtils(self.mock_setup, self.mock_logger, '66') + expected_calls = [mock.call.call(mock.ANY, '66')] + self.assertEqual(mocks.mock_calls, expected_calls) diff --git a/google_compute_engine/distro_lib/el_7/utils.py b/google_compute_engine/distro_lib/el_7/utils.py index 11f8462..b11a98f 100644 --- a/google_compute_engine/distro_lib/el_7/utils.py +++ b/google_compute_engine/distro_lib/el_7/utils.py @@ -21,6 +21,7 @@ import re from google_compute_engine import constants from google_compute_engine.distro_lib import helpers +from google_compute_engine.distro_lib import ip_forwarding_utils from google_compute_engine.distro_lib import utils @@ -51,7 +52,8 @@ class Utils(utils.Utils): logger: logger object, used to write to SysLog and serial port. """ for interface in interfaces: - interface_config = os.path.join(self.network_path, 'ifcfg-%s' % interface) + interface_config = os.path.join( + self.network_path, 'ifcfg-%s' % interface) if os.path.exists(interface_config): self._ModifyInterface( interface_config, 'DEVICE', interface, replace=False) @@ -97,3 +99,12 @@ class Utils(utils.Utils): logger: logger object, used to write to SysLog and serial port. """ helpers.CallHwclock(logger) + + def IpForwardingUtils(self, logger, proto_id=None): + """Get system IP address configuration utilities. + + Args: + logger: logger object, used to write to SysLog and serial port. + proto_id: string, the routing protocol identifier for Google IP changes. + """ + return ip_forwarding_utils.IpForwardingUtilsIproute(logger, proto_id) diff --git a/google_compute_engine/distro_lib/freebsd_11/tests/utils_test.py b/google_compute_engine/distro_lib/freebsd_11/tests/utils_test.py index e35a576..ead9fa4 100644 --- a/google_compute_engine/distro_lib/freebsd_11/tests/utils_test.py +++ b/google_compute_engine/distro_lib/freebsd_11/tests/utils_test.py @@ -44,3 +44,12 @@ class UtilsTest(unittest.TestCase): utils.Utils.HandleClockSync(self.mock_setup, self.mock_logger) expected_calls = [mock.call.call(mock.ANY)] self.assertEqual(mocks.mock_calls, expected_calls) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.IpForwardingUtilsIfconfig') + def testIpForwardingUtils(self, mock_call): + mocks = mock.Mock() + mocks.attach_mock(mock_call, 'call') + + utils.Utils.IpForwardingUtils(self.mock_setup, self.mock_logger, 66) + expected_calls = [mock.call.call(mock.ANY)] + self.assertEqual(mocks.mock_calls, expected_calls) diff --git a/google_compute_engine/distro_lib/freebsd_11/utils.py b/google_compute_engine/distro_lib/freebsd_11/utils.py index d9a39ec..4a9e706 100644 --- a/google_compute_engine/distro_lib/freebsd_11/utils.py +++ b/google_compute_engine/distro_lib/freebsd_11/utils.py @@ -16,6 +16,7 @@ """Utilities that are distro specific for use on FreeBSD 11.""" from google_compute_engine.distro_lib import helpers +from google_compute_engine.distro_lib import ip_forwarding_utils from google_compute_engine.distro_lib import utils @@ -40,3 +41,12 @@ class Utils(utils.Utils): logger: logger object, used to write to SysLog and serial port. """ helpers.CallNtpdate(logger) + + def IpForwardingUtils(self, logger, proto_id=None): + """Get system IP address configuration utilities. + + Args: + logger: logger object, used to write to SysLog and serial port. + proto_id: string, the routing protocol identifier for Google IP changes. + """ + return ip_forwarding_utils.IpForwardingUtilsIfconfig(logger) diff --git a/google_compute_engine/distro_lib/ip_forwarding_utils.py b/google_compute_engine/distro_lib/ip_forwarding_utils.py new file mode 100644 index 0000000..63532e2 --- /dev/null +++ b/google_compute_engine/distro_lib/ip_forwarding_utils.py @@ -0,0 +1,302 @@ +#!/usr/bin/python +# Copyright 2018 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for configuring IP address forwarding.""" + +import re +import subprocess +try: + # The following modules are required by IpForwardingUtilsIfconfig. + import netifaces + import netaddr +except ImportError: + netifaces = None + netaddr = None + + +IP_REGEX = re.compile(r'\A(\d{1,3}\.){3}\d{1,3}\Z') +IP_ALIAS_REGEX = re.compile(r'\A(\d{1,3}\.){3}\d{1,3}/\d{1,2}\Z') + + +class IpForwardingUtilsBase(object): + """System IP address configuration utilities.""" + + def ParseForwardedIps(self, forwarded_ips): + """Parse and validate forwarded IP addresses. + + Args: + forwarded_ips: list, the IP address strings to parse. + + Returns: + list, the valid IP address strings. + """ + pass + + def GetForwardedIps(self, interface, interface_ip=None): + """Retrieve the list of configured forwarded IP addresses. + + Args: + interface: string, the output device to query. + interface_ip: string, current interface ip address. + + Returns: + list, the IP address strings. + """ + pass + + def AddForwardedIp(self, address, interface): + """Configure a new IP address on the network interface. + + Args: + address: string, the IP address to configure. + interface: string, the output device to use. + """ + pass + + def RemoveForwardedIp(self, address, interface): + """Delete an IP address on the network interface. + + Args: + address: string, the IP address to configure. + interface: string, the output device to use. + """ + pass + + +class IpForwardingUtilsIproute(IpForwardingUtilsBase): + """System IP address configuration utilities. + + Command used to add IPs: + ip route add to local $IP/32 dev eth0 proto 66 + Command used to fetch list of configured IPs: + ip route ls table local type local dev eth0 scope host proto 66 + """ + + def __init__(self, logger, proto_id=None): + """Constructor. + + Args: + logger: logger object, used to write to SysLog and serial port. + proto_id: string, the routing protocol identifier for Google IP changes. + """ + self.logger = logger + self.proto_id = proto_id or '66' + + def _CreateRouteOptions(self, **kwargs): + """Create a dictionary of parameters to append to the ip route command. + + Args: + **kwargs: dict, the string parameters to update in the ip route command. + + Returns: + dict, the string parameters to append to the ip route command. + """ + options = { + 'proto': self.proto_id, + 'scope': 'host', + } + options.update(kwargs) + return options + + def _RunIpRoute(self, args=None, options=None): + """Run a command with ip route and return the response. + + Args: + args: list, the string ip route command args to execute. + options: dict, the string parameters to append to the ip route command. + + Returns: + string, the standard output from the ip route command execution. + """ + args = args or [] + options = options or {} + command = ['ip', 'route'] + command.extend(args) + for item in options.items(): + command.extend(item) + try: + process = subprocess.Popen( + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + except OSError as e: + self.logger.warning('Exception running %s. %s.', command, str(e)) + else: + if process.returncode: + message = 'Non-zero exit status running %s. %s.' + self.logger.warning(message, command, stderr.strip()) + else: + return stdout.decode('utf-8', 'replace') + return '' + + def ParseForwardedIps(self, forwarded_ips): + """Parse and validate forwarded IP addresses. + + Args: + forwarded_ips: list, the IP address strings to parse. + + Returns: + list, the valid IP address strings. + """ + addresses = [] + forwarded_ips = forwarded_ips or [] + for ip in forwarded_ips: + if ip and (IP_REGEX.match(ip) or IP_ALIAS_REGEX.match(ip)): + addresses.append(ip[:-3] if ip.endswith('/32') else ip) + else: + self.logger.warning('Could not parse IP address: "%s".', ip) + return addresses + + def GetForwardedIps(self, interface, interface_ip=None): + """Retrieve the list of configured forwarded IP addresses. + + Args: + interface: string, the output device to query. + interface_ip: string, current interface ip address. + + Returns: + list, the IP address strings. + """ + args = ['ls', 'table', 'local', 'type', 'local'] + options = self._CreateRouteOptions(dev=interface) + result = self._RunIpRoute(args=args, options=options) + result = re.sub(r'local\s', r'', result) + return self.ParseForwardedIps(result.split()) + + def AddForwardedIp(self, address, interface): + """Configure a new IP address on the network interface. + + Args: + address: string, the IP address to configure. + interface: string, the output device to use. + """ + address = address if IP_ALIAS_REGEX.match(address) else '%s/32' % address + args = ['add', 'to', 'local', address] + options = self._CreateRouteOptions(dev=interface) + self._RunIpRoute(args=args, options=options) + + def RemoveForwardedIp(self, address, interface): + """Delete an IP address on the network interface. + + Args: + address: string, the IP address to configure. + interface: string, the output device to use. + """ + address = address if IP_ALIAS_REGEX.match(address) else '%s/32' % address + args = ['delete', 'to', 'local', address] + options = self._CreateRouteOptions(dev=interface) + self._RunIpRoute(args=args, options=options) + + +class IpForwardingUtilsIfconfig(IpForwardingUtilsBase): + """System IP address configuration utilities.""" + + def __init__(self, logger): + """Constructor. + + Args: + logger: logger object, used to write to SysLog and serial port. + """ + + self.logger = logger + + def _RunIfconfig(self, args=None, options=None): + """Run a command with ifconfig and return the response. + + Args: + args: list, the string ip route command args to execute. + options: dict, the string parameters to append to the ip route command. + + Returns: + string, the standard output from the ip route command execution. + """ + args = args or [] + options = options or {} + command = ['ifconfig'] + command.extend(args) + for item in options.items(): + command.extend(item) + try: + process = subprocess.Popen( + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + except OSError as e: + self.logger.warning('Exception running %s. %s.', command, str(e)) + else: + if process.returncode: + message = 'Non-zero exit status running %s. %s.' + self.logger.warning(message, command, stderr.strip()) + else: + return stdout.decode('utf-8', 'replace') + return '' + + def ParseForwardedIps(self, forwarded_ips): + """Parse and validate forwarded IP addresses. + + Args: + forwarded_ips: list, the IP address strings to parse. + + Returns: + list, the valid IP address strings. + """ + addresses = [] + forwarded_ips = forwarded_ips or [] + for ip in forwarded_ips: + if ip and (IP_REGEX.match(ip) or IP_ALIAS_REGEX.match(ip)): + addresses.extend([str(addr) for addr in list(netaddr.IPNetwork(ip))]) + else: + self.logger.warning('Could not parse IP address: "%s".', ip) + return addresses + + def GetForwardedIps(self, interface, interface_ip=None): + """Retrieve the list of configured forwarded IP addresses. + + Args: + interface: string, the output device to query. + interface_ip: string, current interface ip address. + + Returns: + list, the IP address strings. + """ + try: + ips = netifaces.ifaddresses(interface) + ips = ips[netifaces.AF_INET] + except (ValueError, IndexError): + return [] + forwarded_ips = [] + for ip in ips: + if ip['addr'] != interface_ip: + full_addr = '%s/%d' % (ip['addr'], netaddr.IPAddress(ip['netmask']).netmask_bits()) + forwarded_ips.append(full_addr) + return self.ParseForwardedIps(forwarded_ips) + + def AddForwardedIp(self, address, interface): + """Configure a new IP address on the network interface. + + Args: + address: string, the IP address to configure. + interface: string, the output device to use. + """ + for ip in list(netaddr.IPNetwork(address)): + self._RunIfconfig(args=[interface, 'alias', '%s/32' % str(ip)]) + + def RemoveForwardedIp(self, address, interface): + """Delete an IP address on the network interface. + + Args: + address: string, the IP address to configure. + interface: string, the output device to use. + """ + ip = netaddr.IPNetwork(address) + self._RunIfconfig(args=[interface, '-alias', str(ip.ip)]) diff --git a/google_compute_engine/distro_lib/sles_11/tests/utils_test.py b/google_compute_engine/distro_lib/sles_11/tests/utils_test.py index 78110b6..22d54de 100644 --- a/google_compute_engine/distro_lib/sles_11/tests/utils_test.py +++ b/google_compute_engine/distro_lib/sles_11/tests/utils_test.py @@ -80,3 +80,12 @@ class UtilsTest(unittest.TestCase): utils.Utils.HandleClockSync(self.mock_setup, self.mock_logger) expected_calls = [mock.call.call(mock.ANY)] self.assertEqual(mocks.mock_calls, expected_calls) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.IpForwardingUtilsIproute') + def testIpForwardingUtils(self, mock_call): + mocks = mock.Mock() + mocks.attach_mock(mock_call, 'call') + + utils.Utils.IpForwardingUtils(self.mock_setup, self.mock_logger, '66') + expected_calls = [mock.call.call(mock.ANY, '66')] + self.assertEqual(mocks.mock_calls, expected_calls) diff --git a/google_compute_engine/distro_lib/sles_11/utils.py b/google_compute_engine/distro_lib/sles_11/utils.py index 448f662..6d1d0f2 100644 --- a/google_compute_engine/distro_lib/sles_11/utils.py +++ b/google_compute_engine/distro_lib/sles_11/utils.py @@ -20,6 +20,7 @@ import subprocess from google_compute_engine import constants from google_compute_engine.distro_lib import helpers +from google_compute_engine.distro_lib import ip_forwarding_utils from google_compute_engine.distro_lib import utils @@ -67,3 +68,12 @@ class Utils(utils.Utils): logger: logger object, used to write to SysLog and serial port. """ helpers.CallHwclock(logger) + + def IpForwardingUtils(self, logger, proto_id=None): + """Get system IP address configuration utilities. + + Args: + logger: logger object, used to write to SysLog and serial port. + proto_id: string, the routing protocol identifier for Google IP changes. + """ + return ip_forwarding_utils.IpForwardingUtilsIproute(logger, proto_id) diff --git a/google_compute_engine/distro_lib/sles_12/tests/utils_test.py b/google_compute_engine/distro_lib/sles_12/tests/utils_test.py index d6f8e25..1f89c2e 100644 --- a/google_compute_engine/distro_lib/sles_12/tests/utils_test.py +++ b/google_compute_engine/distro_lib/sles_12/tests/utils_test.py @@ -100,3 +100,12 @@ class UtilsTest(unittest.TestCase): utils.Utils.HandleClockSync(self.mock_setup, self.mock_logger) expected_calls = [mock.call.call(mock.ANY)] self.assertEqual(mocks.mock_calls, expected_calls) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.IpForwardingUtilsIproute') + def testIpForwardingUtils(self, mock_call): + mocks = mock.Mock() + mocks.attach_mock(mock_call, 'call') + + utils.Utils.IpForwardingUtils(self.mock_setup, self.mock_logger, '66') + expected_calls = [mock.call.call(mock.ANY, '66')] + self.assertEqual(mocks.mock_calls, expected_calls) diff --git a/google_compute_engine/distro_lib/sles_12/utils.py b/google_compute_engine/distro_lib/sles_12/utils.py index fb15830..380df7b 100644 --- a/google_compute_engine/distro_lib/sles_12/utils.py +++ b/google_compute_engine/distro_lib/sles_12/utils.py @@ -20,6 +20,7 @@ import subprocess from google_compute_engine import constants from google_compute_engine.distro_lib import helpers +from google_compute_engine.distro_lib import ip_forwarding_utils from google_compute_engine.distro_lib import utils @@ -89,3 +90,12 @@ class Utils(utils.Utils): logger: logger object, used to write to SysLog and serial port. """ helpers.CallHwclock(logger) + + def IpForwardingUtils(self, logger, proto_id=None): + """Get system IP address configuration utilities. + + Args: + logger: logger object, used to write to SysLog and serial port. + proto_id: string, the routing protocol identifier for Google IP changes. + """ + return ip_forwarding_utils.IpForwardingUtilsIproute(logger, proto_id) diff --git a/google_compute_engine/distro_lib/tests/ip_forwarding_utils_test.py b/google_compute_engine/distro_lib/tests/ip_forwarding_utils_test.py new file mode 100644 index 0000000..e3f4bbc --- /dev/null +++ b/google_compute_engine/distro_lib/tests/ip_forwarding_utils_test.py @@ -0,0 +1,435 @@ +#!/usr/bin/python +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Unittest for ip_forwarding_utils.py module.""" + +from google_compute_engine.distro_lib import ip_forwarding_utils +from google_compute_engine.test_compat import mock +from google_compute_engine.test_compat import unittest + + +def _CreateMockProcess(returncode, stdout, stderr): + mock_process = mock.Mock() + mock_process.returncode = returncode + mock_process.communicate.return_value = (stdout, stderr) + return mock_process + + +class IpForwardingUtilsIprouteTest(unittest.TestCase): + + def setUp(self): + self.mock_logger = mock.Mock() + self.options = {'hello': 'world'} + with mock.patch( + 'google_compute_engine.distro_lib.ip_forwarding_utils' + '.subprocess') as mock_subprocess: + mock_subprocess.Popen.return_value = _CreateMockProcess( + 0, b'out', b'') + self.mock_utils = ip_forwarding_utils.IpForwardingUtilsIproute( + self.mock_logger) + self.mock_utils.proto_id = 'proto' + + def testCreateRouteOptions(self): + # Default options. + expected_options = { + 'proto': 'proto', + 'scope': 'host', + } + self.assertEqual(self.mock_utils._CreateRouteOptions(), expected_options) + + # Update dictionary when arguments are specified. + expected_options = { + 'proto': 'proto', + 'scope': 'host', + 'num': 1, + 'string': 'hello world', + } + self.assertEqual( + self.mock_utils._CreateRouteOptions(num=1, string='hello world'), + expected_options) + + # Update the default options. + expected_options = { + 'proto': 'test 1', + 'scope': 'test 2', + } + self.assertEqual( + self.mock_utils._CreateRouteOptions(proto='test 1', scope='test 2'), + expected_options) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.subprocess') + def testRunIpRoute(self, mock_subprocess): + mock_process = _CreateMockProcess(0, b'out', b'') + mock_subprocess.Popen.return_value = mock_process + args = ['foo', 'bar'] + options = {'one': 'two'} + + self.assertEqual( + self.mock_utils._RunIpRoute(args=args, options=options), 'out') + command = ['ip', 'route', 'foo', 'bar', 'one', 'two'] + mock_subprocess.Popen.assert_called_once_with( + command, stdout=mock_subprocess.PIPE, stderr=mock_subprocess.PIPE) + mock_process.communicate.assert_called_once_with() + self.mock_logger.warning.assert_not_called() + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.subprocess') + def testRunIpRouteReturnCode(self, mock_subprocess): + mock_process = _CreateMockProcess(1, b'out', b'error\n') + mock_subprocess.Popen.return_value = mock_process + + self.assertEqual( + self.mock_utils._RunIpRoute(args=['foo', 'bar'], options=self.options), + '') + command = ['ip', 'route', 'foo', 'bar', 'hello', 'world'] + self.mock_logger.warning.assert_called_once_with( + mock.ANY, command, b'error') + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.subprocess') + def testRunIpRouteException(self, mock_subprocess): + mock_subprocess.Popen.side_effect = OSError('Test Error') + + self.assertEqual( + self.mock_utils._RunIpRoute(args=['foo', 'bar'], options=self.options), + '') + command = ['ip', 'route', 'foo', 'bar', 'hello', 'world'] + self.mock_logger.warning.assert_called_once_with( + mock.ANY, command, 'Test Error') + + def testParseForwardedIps(self): + self.assertEqual(self.mock_utils.ParseForwardedIps(None), []) + self.assertEqual(self.mock_utils.ParseForwardedIps([]), []) + self.assertEqual(self.mock_utils.ParseForwardedIps([None]), []) + self.assertEqual(self.mock_utils.ParseForwardedIps(['invalid']), []) + self.assertEqual(self.mock_utils.ParseForwardedIps(['1a1a1a1']), []) + self.assertEqual(self.mock_utils.ParseForwardedIps(['1.1.1.1.1']), []) + self.assertEqual(self.mock_utils.ParseForwardedIps(['1111.1.1.1']), []) + self.assertEqual(self.mock_utils.ParseForwardedIps(['1.1.1.1111']), []) + expected_calls = [ + mock.call.warning(mock.ANY, None), + mock.call.warning(mock.ANY, 'invalid'), + mock.call.warning(mock.ANY, '1a1a1a1'), + mock.call.warning(mock.ANY, '1.1.1.1.1'), + mock.call.warning(mock.ANY, '1111.1.1.1'), + mock.call.warning(mock.ANY, '1.1.1.1111'), + ] + self.assertEqual(self.mock_logger.mock_calls, expected_calls) + + def testParseForwardedIpsComplex(self): + forwarded_ips = { + '{{}}\n\"hello\"\n!@#$%^&*()\n\n': False, + '1111.1.1.1': False, + '1.1.1.1': True, + 'hello': False, + '123.123.123.123': True, + '1.1.1.': False, + '1.1.1.a': False, + None: False, + '1.0.0.0': True, + '1.1.1.1/1': True, + '1.1.1.1/11': True, + '123.123.123.123/1': True, + '123.123.123.123/123': False, + '123.123.123.123/a': False, + '123.123.123.123/': False, + } + input_ips = forwarded_ips.keys() + valid_ips = [ip for ip, valid in forwarded_ips.items() if valid] + invalid_ips = [ip for ip, valid in forwarded_ips.items() if not valid] + + self.assertEqual(self.mock_utils.ParseForwardedIps(input_ips), valid_ips) + expected_calls = [mock.call.warning(mock.ANY, ip) for ip in invalid_ips] + self.assertEqual(self.mock_logger.mock_calls, expected_calls) + + def testParseForwardedIpsSubnet(self): + forwarded_ips = { + '1.1.1.1': '1.1.1.1', + '1.1.1.1/32': '1.1.1.1', + '1.1.1.1/1': '1.1.1.1/1', + '1.1.1.1/10': '1.1.1.1/10', + '1.1.1.1/24': '1.1.1.1/24', + } + for ip, value in forwarded_ips.items(): + self.assertEqual(self.mock_utils.ParseForwardedIps([ip]), [value]) + + def testGetForwardedIps(self): + mock_options = mock.Mock() + mock_options.return_value = self.options + mock_run = mock.Mock() + mock_run.return_value = 'a\n b \nlocal c' + mock_parse = mock.Mock() + mock_parse.return_value = ['Test'] + self.mock_utils._CreateRouteOptions = mock_options + self.mock_utils._RunIpRoute = mock_run + self.mock_utils.ParseForwardedIps = mock_parse + + self.assertEqual( + self.mock_utils.GetForwardedIps('interface', 'ip'), ['Test']) + mock_options.assert_called_once_with(dev='interface') + mock_run.assert_called_once_with( + args=['ls', 'table', 'local', 'type', 'local'], options=self.options) + mock_parse.assert_called_once_with(['a', 'b', 'c']) + + def testAddForwardedIp(self): + mock_options = mock.Mock() + mock_options.return_value = self.options + mock_run = mock.Mock() + self.mock_utils._CreateRouteOptions = mock_options + self.mock_utils._RunIpRoute = mock_run + + self.mock_utils.AddForwardedIp('1.1.1.1', 'interface') + mock_options.assert_called_once_with(dev='interface') + mock_run.assert_called_once_with( + args=['add', 'to', 'local', '1.1.1.1/32'], options=self.options) + + def testAddIpAlias(self): + mock_options = mock.Mock() + mock_options.return_value = self.options + mock_run = mock.Mock() + self.mock_utils._CreateRouteOptions = mock_options + self.mock_utils._RunIpRoute = mock_run + + self.mock_utils.AddForwardedIp('1.1.1.1/24', 'interface') + mock_options.assert_called_once_with(dev='interface') + mock_run.assert_called_once_with( + args=['add', 'to', 'local', '1.1.1.1/24'], options=self.options) + + def testRemoveForwardedIp(self): + mock_options = mock.Mock() + mock_options.return_value = self.options + mock_run = mock.Mock() + self.mock_utils._CreateRouteOptions = mock_options + self.mock_utils._RunIpRoute = mock_run + + self.mock_utils.RemoveForwardedIp('1.1.1.1', 'interface') + mock_options.assert_called_once_with(dev='interface') + mock_run.assert_called_once_with( + args=['delete', 'to', 'local', '1.1.1.1/32'], options=self.options) + + def testRemoveAliasIp(self): + mock_options = mock.Mock() + mock_options.return_value = self.options + mock_run = mock.Mock() + self.mock_utils._CreateRouteOptions = mock_options + self.mock_utils._RunIpRoute = mock_run + + self.mock_utils.RemoveForwardedIp('1.1.1.1/24', 'interface') + mock_options.assert_called_once_with(dev='interface') + mock_run.assert_called_once_with( + args=['delete', 'to', 'local', '1.1.1.1/24'], options=self.options) + + +class IpForwardingUtilsIfconfigTest(unittest.TestCase): + + def setUp(self): + self.mock_logger = mock.Mock() + with mock.patch( + 'google_compute_engine.distro_lib.ip_forwarding_utils' + '.subprocess') as mock_subprocess: + mock_subprocess.Popen.return_value = _CreateMockProcess( + 0, b'out', b'') + self.mock_utils = ip_forwarding_utils.IpForwardingUtilsIfconfig( + self.mock_logger) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.subprocess') + def testRunIfconfig(self, mock_subprocess): + mock_process = _CreateMockProcess(0, b'out', b'') + mock_subprocess.Popen.return_value = mock_process + args = ['foo', 'bar'] + options = {'one': 'two'} + + self.assertEqual( + self.mock_utils._RunIfconfig(args=args, options=options), 'out') + command = ['ifconfig', 'foo', 'bar', 'one', 'two'] + mock_subprocess.Popen.assert_called_once_with( + command, stdout=mock_subprocess.PIPE, stderr=mock_subprocess.PIPE) + mock_process.communicate.assert_called_once_with() + self.mock_logger.warning.assert_not_called() + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.subprocess') + def testRunIfconfigReturnCode(self, mock_subprocess): + mock_process = _CreateMockProcess(1, b'out', b'error\n') + mock_subprocess.Popen.return_value = mock_process + + self.assertEqual( + self.mock_utils._RunIfconfig(args=['foo', 'bar']), + '') + command = ['ifconfig', 'foo', 'bar'] + self.mock_logger.warning.assert_called_once_with( + mock.ANY, command, b'error') + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.subprocess') + def testRunIfconfigException(self, mock_subprocess): + mock_subprocess.Popen.side_effect = OSError('Test Error') + + self.assertEqual( + self.mock_utils._RunIfconfig(args=['foo', 'bar']), + '') + command = ['ifconfig', 'foo', 'bar'] + self.mock_logger.warning.assert_called_once_with( + mock.ANY, command, 'Test Error') + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.netaddr') + def testParseForwardedIps(self, mock_netaddr): + self.assertEqual(self.mock_utils.ParseForwardedIps(None), []) + self.assertEqual(self.mock_utils.ParseForwardedIps([]), []) + self.assertEqual(self.mock_utils.ParseForwardedIps([None]), []) + self.assertEqual(self.mock_utils.ParseForwardedIps(['invalid']), []) + self.assertEqual(self.mock_utils.ParseForwardedIps(['1a1a1a1']), []) + self.assertEqual(self.mock_utils.ParseForwardedIps(['1.1.1.1.1']), []) + self.assertEqual(self.mock_utils.ParseForwardedIps(['1111.1.1.1']), []) + self.assertEqual(self.mock_utils.ParseForwardedIps(['1.1.1.1111']), []) + expected_calls = [ + mock.call.warning(mock.ANY, None), + mock.call.warning(mock.ANY, 'invalid'), + mock.call.warning(mock.ANY, '1a1a1a1'), + mock.call.warning(mock.ANY, '1.1.1.1.1'), + mock.call.warning(mock.ANY, '1111.1.1.1'), + mock.call.warning(mock.ANY, '1.1.1.1111'), + ] + self.assertEqual(self.mock_logger.mock_calls, expected_calls) + self.assertEqual(mock_netaddr.IPNetwork.mock_calls, []) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.netaddr') + def testParseForwardedIpsComplex(self, mock_netaddr): + def side_effect(arg): + return [arg] + mock_netaddr.IPNetwork.side_effect = side_effect + forwarded_ips = { + '{{}}\n\"hello\"\n!@#$%^&*()\n\n': False, + '1111.1.1.1': False, + '1.1.1.1': True, + 'hello': False, + '123.123.123.123': True, + '1.1.1.': False, + '1.1.1.a': False, + None: False, + '1.0.0.0': True, + '1.1.1.1/1': True, + '1.1.1.1/11': True, + '123.123.123.123/1': True, + '123.123.123.123/123': False, + '123.123.123.123/a': False, + '123.123.123.123/': False, + } + input_ips = forwarded_ips.keys() + valid_ips = [ip for ip, valid in forwarded_ips.items() if valid] + invalid_ips = [ip for ip, valid in forwarded_ips.items() if not valid] + + self.assertEqual(self.mock_utils.ParseForwardedIps(input_ips), valid_ips) + expected_calls = [mock.call.warning(mock.ANY, ip) for ip in invalid_ips] + self.assertEqual(self.mock_logger.mock_calls, expected_calls) + expected_calls = [mock.call.IPNetwork(ip) for ip in valid_ips] + self.assertEqual(mock_netaddr.mock_calls, expected_calls) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.netaddr') + def testParseForwardedIpsSubnet(self, mock_netaddr): + mock_netaddr.IPNetwork.return_value = ['1.1.1.1'] + forwarded_ips = [ + '1.1.1.1', + '1.1.1.1/32', + '1.1.1.1/1', + '1.1.1.1/10', + '1.1.1.1/24' + ] + for ip in forwarded_ips: + self.assertEqual(self.mock_utils.ParseForwardedIps([ip]), ['1.1.1.1']) + expected_calls = [mock.call.IPNetwork(ip) for ip in forwarded_ips] + self.assertEqual(mock_netaddr.mock_calls, expected_calls) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.netifaces') + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.netaddr') + def testGetForwardedIps(self, mock_netaddr, mock_netifaces): + mock_netifaces.AF_INET = 0 + mock_netifaces.ifaddresses.return_value = [[ + {'addr': 'a', 'netmask': 'a mask'}, + {'addr': 'b', 'netmask': 'b mask'}, + {'addr': 'c', 'netmask': 'c mask'}, + ]] + mock_netaddr.IPAddress().netmask_bits.return_value = 32 + mock_parse = mock.Mock() + mock_parse.return_value = ['Test'] + self.mock_utils.ParseForwardedIps = mock_parse + + self.assertEqual( + self.mock_utils.GetForwardedIps('interface', 'ip'), ['Test']) + mock_netifaces.ifaddresses.assert_called_once_with('interface') + mock_parse.assert_called_once_with(['a/32', 'b/32', 'c/32']) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.netifaces') + def testGetForwardedIpsEmpty(self, mock_netifaces): + mock_netifaces.AF_INET = 0 + mock_netifaces.ifaddresses.return_value = [] + + self.assertEqual( + self.mock_utils.GetForwardedIps('interface', 'ip'), []) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.netaddr') + def testAddForwardedIp(self, mock_netaddr): + mock_netaddr.IPNetwork.return_value = ['1.1.1.1'] + mock_run = mock.Mock() + self.mock_utils._RunIfconfig = mock_run + + self.mock_utils.AddForwardedIp('1.1.1.1', 'interface') + mock_netaddr.IPNetwork.assert_called_once_with('1.1.1.1') + mock_run.assert_called_once_with( + args=['interface', 'alias', '1.1.1.1/32']) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.netaddr') + def testAddIpAlias(self, mock_netaddr): + mock_netaddr.IPNetwork.return_value = [ + '1.1.1.0', '1.1.1.1', '1.1.1.2', '1.1.1.3' + ] + mock_run = mock.Mock() + self.mock_utils._RunIfconfig = mock_run + + self.mock_utils.AddForwardedIp('1.1.1.1/30', 'interface') + mock_netaddr.IPNetwork.assert_called_once_with('1.1.1.1/30') + expected_calls = [ + mock.call(args=['interface', 'alias', '1.1.1.0/32']), + mock.call(args=['interface', 'alias', '1.1.1.1/32']), + mock.call(args=['interface', 'alias', '1.1.1.2/32']), + mock.call(args=['interface', 'alias', '1.1.1.3/32']) + ] + self.assertEqual(mock_run.mock_calls, expected_calls) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.netaddr') + def testRemoveForwardedIp(self, mock_netaddr): + mock_ip = mock.Mock() + mock_ip.ip = '1.1.1.1' + mock_netaddr.IPNetwork.return_value = mock_ip + mock_run = mock.Mock() + self.mock_utils._RunIfconfig = mock_run + + self.mock_utils.RemoveForwardedIp('1.1.1.1', 'interface') + mock_netaddr.IPNetwork.assert_called_once_with('1.1.1.1') + mock_run.assert_called_once_with( + args=['interface', '-alias', '1.1.1.1']) + + @mock.patch('google_compute_engine.distro_lib.ip_forwarding_utils.netaddr') + def testRemoveAliasIp(self, mock_netaddr): + mock_ip = mock.Mock() + mock_ip.ip = '1.1.1.1' + mock_netaddr.IPNetwork.return_value = mock_ip + mock_run = mock.Mock() + self.mock_utils._RunIfconfig = mock_run + + self.mock_utils.RemoveForwardedIp('1.1.1.1/24', 'interface') + mock_netaddr.IPNetwork.assert_called_once_with('1.1.1.1/24') + mock_run.assert_called_once_with( + args=['interface', '-alias', '1.1.1.1']) + + +if __name__ == '__main__': + unittest.main() diff --git a/google_compute_engine/distro_lib/utils.py b/google_compute_engine/distro_lib/utils.py index bb26390..75b656e 100644 --- a/google_compute_engine/distro_lib/utils.py +++ b/google_compute_engine/distro_lib/utils.py @@ -45,3 +45,12 @@ class Utils(object): logger: logger object, used to write to SysLog and serial port. """ pass + + def IpForwardingUtils(self, logger, proto_id=None): + """Get system IP address configuration utilities. + + Args: + logger: logger object, used to write to SysLog and serial port. + proto_id: string, the routing protocol identifier for Google IP changes. + """ + pass |
