Example #1
0
    def test_provided_nic_does_not_exist(self, m_fallback_nic):
        """When the provided nic doesn't exist, log a message and no-op."""
        with pytest.raises(NoDHCPLeaseInterfaceError):
            maybe_perform_dhcp_discovery("idontexist")

        self.assertIn(
            "Skip dhcp_discovery: nic idontexist not found in get_devicelist.",
            self.logs.getvalue(),
        )
Example #2
0
    def test_no_fallback_nic_found(self, m_fallback_nic):
        """Log and do nothing when nic is absent and no fallback is found."""
        m_fallback_nic.return_value = None  # No fallback nic found

        with pytest.raises(NoDHCPLeaseInterfaceError):
            maybe_perform_dhcp_discovery()

        self.assertIn(
            "Skip dhcp_discovery: Unable to find fallback nic.",
            self.logs.getvalue(),
        )
Example #3
0
    def test_absent_dhclient_command(self, m_fallback, m_which):
        """When dhclient doesn't exist in the OS, log the issue and no-op."""
        m_fallback.return_value = "eth9"
        m_which.return_value = None  # dhclient isn't found

        with pytest.raises(NoDHCPLeaseMissingDhclientError):
            maybe_perform_dhcp_discovery()

        self.assertIn(
            "Skip dhclient configuration: No dhclient command found.",
            self.logs.getvalue(),
        )
Example #4
0
 def test_no_fallback_nic_found(self, m_fallback_nic):
     """Log and do nothing when nic is absent and no fallback is found."""
     m_fallback_nic.return_value = None  # No fallback nic found
     self.assertEqual([], maybe_perform_dhcp_discovery())
     self.assertIn(
         'Skip dhcp_discovery: Unable to find fallback nic.',
         self.logs.getvalue())
 def test_provided_nic_does_not_exist(self):
     """When the provided nic doesn't exist, log a message and no-op."""
     self.assertEqual([], maybe_perform_dhcp_discovery("idontexist"))
     self.assertIn(
         "Skip dhcp_discovery: nic idontexist not found in get_devicelist.",
         self.logs.getvalue(),
     )
Example #6
0
 def test_no_fallback_nic_found(self, m_fallback_nic):
     """Log and do nothing when nic is absent and no fallback is found."""
     m_fallback_nic.return_value = None  # No fallback nic found
     self.assertEqual([], maybe_perform_dhcp_discovery())
     self.assertIn(
         'Skip dhcp_discovery: Unable to find fallback nic.',
         self.logs.getvalue())
Example #7
0
 def test_absent_dhclient_command(self, m_fallback, m_which):
     """When dhclient doesn't exist in the OS, log the issue and no-op."""
     m_fallback.return_value = 'eth9'
     m_which.return_value = None  # dhclient isn't found
     self.assertEqual([], maybe_perform_dhcp_discovery())
     self.assertIn(
         'Skip dhclient configuration: No dhclient command found.',
         self.logs.getvalue())
Example #8
0
 def test_absent_dhclient_command(self, m_fallback, m_which):
     """When dhclient doesn't exist in the OS, log the issue and no-op."""
     m_fallback.return_value = 'eth9'
     m_which.return_value = None  # dhclient isn't found
     self.assertEqual([], maybe_perform_dhcp_discovery())
     self.assertIn(
         'Skip dhclient configuration: No dhclient command found.',
         self.logs.getvalue())
Example #9
0
 def test_dhclient_run_with_tmpdir(self, m_fallback, m_which, m_dhcp):
     """maybe_perform_dhcp_discovery passes tmpdir to dhcp_discovery."""
     m_fallback.return_value = 'eth9'
     m_which.return_value = '/sbin/dhclient'
     m_dhcp.return_value = {'address': '192.168.2.2'}
     self.assertEqual({'address': '192.168.2.2'},
                      maybe_perform_dhcp_discovery())
     m_dhcp.assert_called_once()
     call = m_dhcp.call_args_list[0]
     self.assertEqual('/sbin/dhclient', call[0][0])
     self.assertEqual('eth9', call[0][1])
     self.assertIn('/tmp/cloud-init-dhcp-', call[0][2])
Example #10
0
    def obtain_lease(self):
        """Perform dhcp discovery in a sandboxed environment if possible.

        @return: A dict representing dhcp options on the most recent lease
            obtained from the dhclient discovery if run, otherwise an error
            is raised.

        @raises: NoDHCPLeaseError if no leases could be obtained.
        """
        if self.lease:
            return self.lease
        leases = maybe_perform_dhcp_discovery(self.iface, self.dhcp_log_func)
        if not leases:
            raise NoDHCPLeaseError()
        self.lease = leases[-1]
        LOG.debug(
            "Received dhcp lease on %s for %s/%s",
            self.lease["interface"],
            self.lease["fixed-address"],
            self.lease["subnet-mask"],
        )
        nmap = {
            "interface":
            "interface",
            "ip":
            "fixed-address",
            "prefix_or_mask":
            "subnet-mask",
            "broadcast":
            "broadcast-address",
            "static_routes": [
                "rfc3442-classless-static-routes",
                "classless-static-routes",
            ],
            "router":
            "routers",
        }
        kwargs = self.extract_dhcp_options_mapping(nmap)
        if not kwargs["broadcast"]:
            kwargs["broadcast"] = net.mask_and_ipv4_to_bcast_addr(
                kwargs["prefix_or_mask"], kwargs["ip"])
        if kwargs["static_routes"]:
            kwargs["static_routes"] = parse_static_routes(
                kwargs["static_routes"])
        if self.connectivity_url_data:
            kwargs["connectivity_url_data"] = self.connectivity_url_data
        ephipv4 = EphemeralIPv4Network(**kwargs)
        ephipv4.__enter__()
        self._ephipv4 = ephipv4
        return self.lease
Example #11
0
    def _get_data(self):
        seed_ret = {}
        if util.read_optional_seed(seed_ret, base=(self.seed_dir + "/")):
            self.userdata_raw = seed_ret['user-data']
            self.metadata = seed_ret['meta-data']
            LOG.debug("Using seeded ec2 data from %s", self.seed_dir)
            self._cloud_platform = Platforms.SEEDED
            return True

        strict_mode, _sleep = read_strict_mode(
            util.get_cfg_by_path(self.sys_cfg, STRICT_ID_PATH,
                                 STRICT_ID_DEFAULT), ("warn", None))

        LOG.debug("strict_mode: %s, cloud_platform=%s", strict_mode,
                  self.cloud_platform)
        if strict_mode == "true" and self.cloud_platform == Platforms.UNKNOWN:
            return False
        elif self.cloud_platform == Platforms.NO_EC2_METADATA:
            return False

        if self.get_network_metadata:  # Setup networking in init-local stage.
            if util.is_FreeBSD():
                LOG.debug("FreeBSD doesn't support running dhclient with -sf")
                return False
            dhcp_leases = dhcp.maybe_perform_dhcp_discovery(
                self.fallback_interface)
            if not dhcp_leases:
                # DataSourceEc2Local failed in init-local stage. DataSourceEc2
                # will still run in init-network stage.
                return False
            dhcp_opts = dhcp_leases[-1]
            net_params = {
                'interface': dhcp_opts.get('interface'),
                'ip': dhcp_opts.get('fixed-address'),
                'prefix_or_mask': dhcp_opts.get('subnet-mask'),
                'broadcast': dhcp_opts.get('broadcast-address'),
                'router': dhcp_opts.get('routers')
            }
            with net.EphemeralIPv4Network(**net_params):
                return util.log_time(logfunc=LOG.debug,
                                     msg='Crawl of metadata service',
                                     func=self._crawl_metadata)
        else:
            return self._crawl_metadata()
Example #12
0
 def test_provided_nic_does_not_exist(self):
     """When the provided nic doesn't exist, log a message and no-op."""
     self.assertEqual([], maybe_perform_dhcp_discovery('idontexist'))
     self.assertIn(
         'Skip dhcp_discovery: nic idontexist not found in get_devicelist.',
         self.logs.getvalue())