OpenStack Networking (Neutron)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1598 lines
66 KiB

  1. # Copyright 2012 OpenStack Foundation
  2. # All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. import abc
  16. import collections
  17. import os
  18. import re
  19. import shutil
  20. import time
  21. import netaddr
  22. from neutron_lib.api.definitions import extra_dhcp_opt as edo_ext
  23. from neutron_lib import constants
  24. from neutron_lib import exceptions
  25. from neutron_lib.utils import file as file_utils
  26. from oslo_log import log as logging
  27. from oslo_utils import excutils
  28. from oslo_utils import fileutils
  29. from oslo_utils import uuidutils
  30. import six
  31. from neutron._i18n import _
  32. from neutron.agent.common import utils as agent_common_utils
  33. from neutron.agent.linux import external_process
  34. from neutron.agent.linux import ip_lib
  35. from neutron.agent.linux import iptables_manager
  36. from neutron.cmd import runtime_checks as checks
  37. from neutron.common import constants as n_const
  38. from neutron.common import exceptions as n_exc
  39. from neutron.common import ipv6_utils
  40. from neutron.common import utils as common_utils
  41. from neutron.ipam import utils as ipam_utils
  42. LOG = logging.getLogger(__name__)
  43. UDP = 'udp'
  44. TCP = 'tcp'
  45. DNS_PORT = 53
  46. DHCPV4_PORT = 67
  47. DHCPV6_PORT = 547
  48. METADATA_DEFAULT_PREFIX = 16
  49. METADATA_DEFAULT_IP = '169.254.169.254'
  50. METADATA_DEFAULT_CIDR = '%s/%d' % (METADATA_DEFAULT_IP,
  51. METADATA_DEFAULT_PREFIX)
  52. METADATA_PORT = 80
  53. WIN2k3_STATIC_DNS = 249
  54. NS_PREFIX = 'qdhcp-'
  55. DNSMASQ_SERVICE_NAME = 'dnsmasq'
  56. DHCP_RELEASE_TRIES = 3
  57. DHCP_RELEASE_TRIES_SLEEP = 0.3
  58. # this variable will be removed when neutron-lib is updated with this value
  59. DHCP_OPT_CLIENT_ID_NUM = 61
  60. class DictModel(dict):
  61. """Convert dict into an object that provides attribute access to values."""
  62. def __init__(self, *args, **kwargs):
  63. """Convert dict values to DictModel values."""
  64. super(DictModel, self).__init__(*args, **kwargs)
  65. def needs_upgrade(item):
  66. """Check if `item` is a dict and needs to be changed to DictModel.
  67. """
  68. return isinstance(item, dict) and not isinstance(item, DictModel)
  69. def upgrade(item):
  70. """Upgrade item if it needs to be upgraded."""
  71. if needs_upgrade(item):
  72. return DictModel(item)
  73. else:
  74. return item
  75. for key, value in self.items():
  76. if isinstance(value, (list, tuple)):
  77. # Keep the same type but convert dicts to DictModels
  78. self[key] = type(value)(
  79. (upgrade(item) for item in value)
  80. )
  81. elif needs_upgrade(value):
  82. # Change dict instance values to DictModel instance values
  83. self[key] = DictModel(value)
  84. def __getattr__(self, name):
  85. try:
  86. return self[name]
  87. except KeyError as e:
  88. raise AttributeError(e)
  89. def __setattr__(self, name, value):
  90. self[name] = value
  91. def __delattr__(self, name):
  92. del self[name]
  93. def __str__(self):
  94. pairs = ['%s=%s' % (k, v) for k, v in self.items()]
  95. return ', '.join(sorted(pairs))
  96. class NetModel(DictModel):
  97. def __init__(self, d):
  98. super(NetModel, self).__init__(d)
  99. self._ns_name = "%s%s" % (NS_PREFIX, self.id)
  100. @property
  101. def namespace(self):
  102. return self._ns_name
  103. @six.add_metaclass(abc.ABCMeta)
  104. class DhcpBase(object):
  105. def __init__(self, conf, network, process_monitor,
  106. version=None, plugin=None):
  107. self.conf = conf
  108. self.network = network
  109. self.process_monitor = process_monitor
  110. self.device_manager = DeviceManager(self.conf, plugin)
  111. self.version = version
  112. @abc.abstractmethod
  113. def enable(self):
  114. """Enables DHCP for this network."""
  115. @abc.abstractmethod
  116. def disable(self, retain_port=False, block=False):
  117. """Disable dhcp for this network."""
  118. def restart(self):
  119. """Restart the dhcp service for the network."""
  120. self.disable(retain_port=True, block=True)
  121. self.enable()
  122. @abc.abstractproperty
  123. def active(self):
  124. """Boolean representing the running state of the DHCP server."""
  125. @abc.abstractmethod
  126. def reload_allocations(self):
  127. """Force the DHCP server to reload the assignment database."""
  128. @classmethod
  129. def existing_dhcp_networks(cls, conf):
  130. """Return a list of existing networks ids that we have configs for."""
  131. raise NotImplementedError()
  132. @classmethod
  133. def check_version(cls):
  134. """Execute version checks on DHCP server."""
  135. raise NotImplementedError()
  136. @classmethod
  137. def get_isolated_subnets(cls, network):
  138. """Returns a dict indicating whether or not a subnet is isolated"""
  139. raise NotImplementedError()
  140. @classmethod
  141. def should_enable_metadata(cls, conf, network):
  142. """True if the metadata-proxy should be enabled for the network."""
  143. raise NotImplementedError()
  144. @six.add_metaclass(abc.ABCMeta)
  145. class DhcpLocalProcess(DhcpBase):
  146. PORTS = []
  147. def __init__(self, conf, network, process_monitor, version=None,
  148. plugin=None):
  149. super(DhcpLocalProcess, self).__init__(conf, network, process_monitor,
  150. version, plugin)
  151. self.confs_dir = self.get_confs_dir(conf)
  152. self.network_conf_dir = os.path.join(self.confs_dir, network.id)
  153. fileutils.ensure_tree(self.network_conf_dir, mode=0o755)
  154. @staticmethod
  155. def get_confs_dir(conf):
  156. return os.path.abspath(os.path.normpath(conf.dhcp_confs))
  157. def get_conf_file_name(self, kind):
  158. """Returns the file name for a given kind of config file."""
  159. return os.path.join(self.network_conf_dir, kind)
  160. def _remove_config_files(self):
  161. shutil.rmtree(self.network_conf_dir, ignore_errors=True)
  162. @staticmethod
  163. def _get_all_subnets(network):
  164. non_local_subnets = getattr(network, 'non_local_subnets', [])
  165. return network.subnets + non_local_subnets
  166. def _enable_dhcp(self):
  167. """check if there is a subnet within the network with dhcp enabled."""
  168. for subnet in self.network.subnets:
  169. if subnet.enable_dhcp:
  170. return True
  171. return False
  172. def enable(self):
  173. """Enables DHCP for this network by spawning a local process."""
  174. try:
  175. common_utils.wait_until_true(self._enable, timeout=300)
  176. except common_utils.WaitTimeout:
  177. LOG.error("Failed to start DHCP process for network %s",
  178. self.network.id)
  179. def _enable(self):
  180. try:
  181. if self.active:
  182. self.restart()
  183. elif self._enable_dhcp():
  184. fileutils.ensure_tree(self.network_conf_dir, mode=0o755)
  185. interface_name = self.device_manager.setup(self.network)
  186. self.interface_name = interface_name
  187. self.spawn_process()
  188. return True
  189. except n_exc.ProcessExecutionError as error:
  190. LOG.debug("Spawning DHCP process for network %s failed; "
  191. "Error: %s", self.network.id, error)
  192. return False
  193. def _get_process_manager(self, cmd_callback=None):
  194. return external_process.ProcessManager(
  195. conf=self.conf,
  196. uuid=self.network.id,
  197. namespace=self.network.namespace,
  198. default_cmd_callback=cmd_callback,
  199. pid_file=self.get_conf_file_name('pid'),
  200. run_as_root=True)
  201. def disable(self, retain_port=False, block=False):
  202. """Disable DHCP for this network by killing the local process."""
  203. self.process_monitor.unregister(self.network.id, DNSMASQ_SERVICE_NAME)
  204. self._get_process_manager().disable()
  205. if block:
  206. common_utils.wait_until_true(lambda: not self.active)
  207. if not retain_port:
  208. self._destroy_namespace_and_port()
  209. self._remove_config_files()
  210. def _destroy_namespace_and_port(self):
  211. try:
  212. self.device_manager.destroy(self.network, self.interface_name)
  213. except RuntimeError:
  214. LOG.warning('Failed trying to delete interface: %s',
  215. self.interface_name)
  216. if not ip_lib.network_namespace_exists(self.network.namespace):
  217. LOG.debug("Namespace already deleted: %s", self.network.namespace)
  218. return
  219. try:
  220. ip_lib.delete_network_namespace(self.network.namespace)
  221. except RuntimeError:
  222. LOG.warning('Failed trying to delete namespace: %s',
  223. self.network.namespace)
  224. def _get_value_from_conf_file(self, kind, converter=None):
  225. """A helper function to read a value from one of the state files."""
  226. file_name = self.get_conf_file_name(kind)
  227. msg = _('Error while reading %s')
  228. try:
  229. with open(file_name, 'r') as f:
  230. try:
  231. return converter(f.read()) if converter else f.read()
  232. except ValueError:
  233. msg = _('Unable to convert value in %s')
  234. except IOError:
  235. msg = _('Unable to access %s')
  236. LOG.debug(msg, file_name)
  237. return None
  238. @property
  239. def interface_name(self):
  240. return self._get_value_from_conf_file('interface')
  241. @interface_name.setter
  242. def interface_name(self, value):
  243. interface_file_path = self.get_conf_file_name('interface')
  244. file_utils.replace_file(interface_file_path, value)
  245. @property
  246. def active(self):
  247. return self._get_process_manager().active
  248. @abc.abstractmethod
  249. def spawn_process(self):
  250. pass
  251. class Dnsmasq(DhcpLocalProcess):
  252. # The ports that need to be opened when security policies are active
  253. # on the Neutron port used for DHCP. These are provided as a convenience
  254. # for users of this class.
  255. PORTS = {constants.IP_VERSION_4:
  256. [(UDP, DNS_PORT), (TCP, DNS_PORT), (UDP, DHCPV4_PORT)],
  257. constants.IP_VERSION_6:
  258. [(UDP, DNS_PORT), (TCP, DNS_PORT), (UDP, DHCPV6_PORT)],
  259. }
  260. _SUBNET_TAG_PREFIX = 'subnet-%s'
  261. _PORT_TAG_PREFIX = 'port-%s'
  262. _ID = 'id:'
  263. _IS_DHCP_RELEASE6_SUPPORTED = None
  264. @classmethod
  265. def check_version(cls):
  266. pass
  267. @classmethod
  268. def existing_dhcp_networks(cls, conf):
  269. """Return a list of existing networks ids that we have configs for."""
  270. confs_dir = cls.get_confs_dir(conf)
  271. try:
  272. return [
  273. c for c in os.listdir(confs_dir)
  274. if uuidutils.is_uuid_like(c)
  275. ]
  276. except OSError:
  277. return []
  278. def _build_cmdline_callback(self, pid_file):
  279. # We ignore local resolv.conf if dns servers are specified
  280. # or if local resolution is explicitly disabled.
  281. _no_resolv = (
  282. '--no-resolv' if self.conf.dnsmasq_dns_servers or
  283. not self.conf.dnsmasq_local_resolv else '')
  284. cmd = [
  285. 'dnsmasq',
  286. '--no-hosts',
  287. _no_resolv,
  288. '--pid-file=%s' % pid_file,
  289. '--dhcp-hostsfile=%s' % self.get_conf_file_name('host'),
  290. '--addn-hosts=%s' % self.get_conf_file_name('addn_hosts'),
  291. '--dhcp-optsfile=%s' % self.get_conf_file_name('opts'),
  292. '--dhcp-leasefile=%s' % self.get_conf_file_name('leases'),
  293. '--dhcp-match=set:ipxe,175',
  294. '--local-service',
  295. '--bind-dynamic',
  296. ]
  297. if not self.device_manager.driver.bridged:
  298. cmd += [
  299. '--bridge-interface=%s,tap*' % self.interface_name,
  300. ]
  301. possible_leases = 0
  302. for subnet in self._get_all_subnets(self.network):
  303. mode = None
  304. # if a subnet is specified to have dhcp disabled
  305. if not subnet.enable_dhcp:
  306. continue
  307. if subnet.ip_version == 4:
  308. mode = 'static'
  309. else:
  310. # Note(scollins) If the IPv6 attributes are not set, set it as
  311. # static to preserve previous behavior
  312. addr_mode = getattr(subnet, 'ipv6_address_mode', None)
  313. ra_mode = getattr(subnet, 'ipv6_ra_mode', None)
  314. if (addr_mode in [constants.DHCPV6_STATEFUL,
  315. constants.DHCPV6_STATELESS] or
  316. not addr_mode and not ra_mode):
  317. mode = 'static'
  318. cidr = netaddr.IPNetwork(subnet.cidr)
  319. if self.conf.dhcp_lease_duration == -1:
  320. lease = 'infinite'
  321. else:
  322. lease = '%ss' % self.conf.dhcp_lease_duration
  323. # mode is optional and is not set - skip it
  324. if mode:
  325. if subnet.ip_version == 4:
  326. cmd.append('--dhcp-range=%s%s,%s,%s,%s,%s' %
  327. ('set:', self._SUBNET_TAG_PREFIX % subnet.id,
  328. cidr.network, mode, cidr.netmask, lease))
  329. else:
  330. if cidr.prefixlen < 64:
  331. LOG.debug('Ignoring subnet %(subnet)s, CIDR has '
  332. 'prefix length < 64: %(cidr)s',
  333. {'subnet': subnet.id, 'cidr': cidr})
  334. continue
  335. cmd.append('--dhcp-range=%s%s,%s,%s,%d,%s' %
  336. ('set:', self._SUBNET_TAG_PREFIX % subnet.id,
  337. cidr.network, mode,
  338. cidr.prefixlen, lease))
  339. possible_leases += cidr.size
  340. mtu = getattr(self.network, 'mtu', 0)
  341. # Do not advertise unknown mtu
  342. if mtu > 0:
  343. cmd.append('--dhcp-option-force=option:mtu,%d' % mtu)
  344. # Cap the limit because creating lots of subnets can inflate
  345. # this possible lease cap.
  346. cmd.append('--dhcp-lease-max=%d' %
  347. min(possible_leases, self.conf.dnsmasq_lease_max))
  348. if self.conf.dhcp_renewal_time > 0:
  349. cmd.append('--dhcp-option-force=option:T1,%ds' %
  350. self.conf.dhcp_renewal_time)
  351. if self.conf.dhcp_rebinding_time > 0:
  352. cmd.append('--dhcp-option-force=option:T2,%ds' %
  353. self.conf.dhcp_rebinding_time)
  354. cmd.append('--conf-file=%s' % self.conf.dnsmasq_config_file)
  355. for server in self.conf.dnsmasq_dns_servers:
  356. cmd.append('--server=%s' % server)
  357. if self.conf.dns_domain:
  358. cmd.append('--domain=%s' % self.conf.dns_domain)
  359. if self.conf.dhcp_broadcast_reply:
  360. cmd.append('--dhcp-broadcast')
  361. if self.conf.dnsmasq_base_log_dir:
  362. log_dir = os.path.join(
  363. self.conf.dnsmasq_base_log_dir,
  364. self.network.id)
  365. try:
  366. if not os.path.exists(log_dir):
  367. os.makedirs(log_dir)
  368. except OSError:
  369. LOG.error('Error while create dnsmasq log dir: %s', log_dir)
  370. else:
  371. log_filename = os.path.join(log_dir, 'dhcp_dns_log')
  372. cmd.append('--log-queries')
  373. cmd.append('--log-dhcp')
  374. cmd.append('--log-facility=%s' % log_filename)
  375. return cmd
  376. def spawn_process(self):
  377. """Spawn the process, if it's not spawned already."""
  378. # we only need to generate the lease file the first time dnsmasq starts
  379. # rather than on every reload since dnsmasq will keep the file current
  380. self._output_init_lease_file()
  381. self._spawn_or_reload_process(reload_with_HUP=False)
  382. def _spawn_or_reload_process(self, reload_with_HUP):
  383. """Spawns or reloads a Dnsmasq process for the network.
  384. When reload_with_HUP is True, dnsmasq receives a HUP signal,
  385. or it's reloaded if the process is not running.
  386. """
  387. self._output_config_files()
  388. pm = self._get_process_manager(
  389. cmd_callback=self._build_cmdline_callback)
  390. pm.enable(reload_cfg=reload_with_HUP)
  391. self.process_monitor.register(uuid=self.network.id,
  392. service_name=DNSMASQ_SERVICE_NAME,
  393. monitored_process=pm)
  394. def _is_dhcp_release6_supported(self):
  395. if self._IS_DHCP_RELEASE6_SUPPORTED is None:
  396. self._IS_DHCP_RELEASE6_SUPPORTED = checks.dhcp_release6_supported()
  397. if not self._IS_DHCP_RELEASE6_SUPPORTED:
  398. LOG.warning("dhcp_release6 is not present on this system, "
  399. "will not call it again.")
  400. return self._IS_DHCP_RELEASE6_SUPPORTED
  401. def _release_lease(self, mac_address, ip, ip_version, client_id=None,
  402. server_id=None, iaid=None):
  403. """Release a DHCP lease."""
  404. if ip_version == constants.IP_VERSION_6:
  405. if not self._is_dhcp_release6_supported():
  406. return
  407. cmd = ['dhcp_release6', '--iface', self.interface_name,
  408. '--ip', ip, '--client-id', client_id,
  409. '--server-id', server_id, '--iaid', iaid]
  410. else:
  411. cmd = ['dhcp_release', self.interface_name, ip, mac_address]
  412. if client_id:
  413. cmd.append(client_id)
  414. ip_wrapper = ip_lib.IPWrapper(namespace=self.network.namespace)
  415. try:
  416. ip_wrapper.netns.execute(cmd, run_as_root=True)
  417. except RuntimeError as e:
  418. # when failed to release single lease there's
  419. # no need to propagate error further
  420. LOG.warning('DHCP release failed for %(cmd)s. '
  421. 'Reason: %(e)s', {'cmd': cmd, 'e': e})
  422. def _output_config_files(self):
  423. self._output_hosts_file()
  424. self._output_addn_hosts_file()
  425. self._output_opts_file()
  426. def reload_allocations(self):
  427. """Rebuild the dnsmasq config and signal the dnsmasq to reload."""
  428. # If all subnets turn off dhcp, kill the process.
  429. if not self._enable_dhcp():
  430. self.disable()
  431. LOG.debug('Killing dnsmasq for network since all subnets have '
  432. 'turned off DHCP: %s', self.network.id)
  433. return
  434. if not self.interface_name:
  435. # we land here if above has been called and we receive port
  436. # delete notifications for the network
  437. LOG.debug('Agent does not have an interface on this network '
  438. 'anymore, skipping reload: %s', self.network.id)
  439. return
  440. self._release_unused_leases()
  441. self._spawn_or_reload_process(reload_with_HUP=True)
  442. LOG.debug('Reloading allocations for network: %s', self.network.id)
  443. self.device_manager.update(self.network, self.interface_name)
  444. def _sort_fixed_ips_for_dnsmasq(self, fixed_ips, v6_nets):
  445. """Sort fixed_ips so that stateless IPv6 subnets appear first.
  446. For example, If a port with v6 extra_dhcp_opts is on a network with
  447. IPv4 and IPv6 stateless subnets. Then dhcp host file will have
  448. below 2 entries for same MAC,
  449. fa:16:3e:8f:9d:65,30.0.0.5,set:aabc7d33-4874-429e-9637-436e4232d2cd
  450. (entry for IPv4 dhcp)
  451. fa:16:3e:8f:9d:65,set:aabc7d33-4874-429e-9637-436e4232d2cd
  452. (entry for stateless IPv6 for v6 options)
  453. dnsmasq internal details for processing host file entries
  454. 1) dnsmasq reads the host file from EOF.
  455. 2) So it first picks up stateless IPv6 entry,
  456. fa:16:3e:8f:9d:65,set:aabc7d33-4874-429e-9637-436e4232d2cd
  457. 3) But dnsmasq doesn't have sufficient checks to skip this entry and
  458. pick next entry, to process dhcp IPv4 request.
  459. 4) So dnsmasq uses this entry to process dhcp IPv4 request.
  460. 5) As there is no ip in this entry, dnsmasq logs "no address available"
  461. and fails to send DHCPOFFER message.
  462. As we rely on internal details of dnsmasq to understand and fix the
  463. issue, Ihar sent a mail to dnsmasq-discuss mailing list
  464. http://lists.thekelleys.org.uk/pipermail/dnsmasq-discuss/2015q2/
  465. 009650.html
  466. So if we reverse the order of writing entries in host file,
  467. so that entry for stateless IPv6 comes first,
  468. then dnsmasq can correctly fetch the IPv4 address.
  469. """
  470. return sorted(
  471. fixed_ips,
  472. key=lambda fip: ((fip.subnet_id in v6_nets) and (
  473. v6_nets[fip.subnet_id].ipv6_address_mode == (
  474. constants.DHCPV6_STATELESS))),
  475. reverse=True)
  476. def _iter_hosts(self):
  477. """Iterate over hosts.
  478. For each host on the network we yield a tuple containing:
  479. (
  480. port, # a DictModel instance representing the port.
  481. alloc, # a DictModel instance of the allocated ip and subnet.
  482. # if alloc is None, it means there is no need to allocate
  483. # an IPv6 address because of stateless DHCPv6 network.
  484. host_name, # Host name.
  485. name, # Canonical hostname in the format 'hostname[.domain]'.
  486. no_dhcp, # A flag indicating that the address doesn't need a DHCP
  487. # IP address.
  488. no_opts, # A flag indication that options shouldn't be written
  489. )
  490. """
  491. v6_nets = dict((subnet.id, subnet) for subnet in
  492. self._get_all_subnets(self.network)
  493. if subnet.ip_version == 6)
  494. for port in self.network.ports:
  495. fixed_ips = self._sort_fixed_ips_for_dnsmasq(port.fixed_ips,
  496. v6_nets)
  497. # Confirm whether Neutron server supports dns_name attribute in the
  498. # ports API
  499. dns_assignment = getattr(port, 'dns_assignment', None)
  500. if dns_assignment:
  501. dns_ip_map = {d.ip_address: d for d in dns_assignment}
  502. for alloc in fixed_ips:
  503. no_dhcp = False
  504. no_opts = False
  505. if alloc.subnet_id in v6_nets:
  506. addr_mode = v6_nets[alloc.subnet_id].ipv6_address_mode
  507. no_dhcp = addr_mode in (constants.IPV6_SLAAC,
  508. constants.DHCPV6_STATELESS)
  509. # we don't setup anything for SLAAC. It doesn't make sense
  510. # to provide options for a client that won't use DHCP
  511. no_opts = addr_mode == constants.IPV6_SLAAC
  512. # If dns_name attribute is supported by ports API, return the
  513. # dns_assignment generated by the Neutron server. Otherwise,
  514. # generate hostname and fqdn locally (previous behaviour)
  515. if dns_assignment:
  516. hostname = dns_ip_map[alloc.ip_address].hostname
  517. fqdn = dns_ip_map[alloc.ip_address].fqdn
  518. else:
  519. hostname = 'host-%s' % alloc.ip_address.replace(
  520. '.', '-').replace(':', '-')
  521. fqdn = hostname
  522. if self.conf.dns_domain:
  523. fqdn = '%s.%s' % (fqdn, self.conf.dns_domain)
  524. yield (port, alloc, hostname, fqdn, no_dhcp, no_opts)
  525. def _get_port_extra_dhcp_opts(self, port):
  526. return getattr(port, edo_ext.EXTRADHCPOPTS, False)
  527. def _output_init_lease_file(self):
  528. """Write a fake lease file to bootstrap dnsmasq.
  529. The generated file is passed to the --dhcp-leasefile option of dnsmasq.
  530. This is used as a bootstrapping mechanism to avoid NAKing active leases
  531. when a dhcp server is scheduled to another agent. Using a leasefile
  532. will also prevent dnsmasq from NAKing or ignoring renewals after a
  533. restart.
  534. Format is as follows:
  535. epoch-timestamp mac_addr ip_addr hostname client-ID
  536. """
  537. filename = self.get_conf_file_name('leases')
  538. buf = six.StringIO()
  539. LOG.debug('Building initial lease file: %s', filename)
  540. # we make up a lease time for the database entry
  541. if self.conf.dhcp_lease_duration == -1:
  542. # Even with an infinite lease, a client may choose to renew a
  543. # previous lease on reboot or interface bounce so we should have
  544. # an entry for it.
  545. # Dnsmasq timestamp format for an infinite lease is 0.
  546. timestamp = 0
  547. else:
  548. timestamp = int(time.time()) + self.conf.dhcp_lease_duration
  549. dhcpv4_enabled_subnet_ids = [
  550. s.id for s in self._get_all_subnets(self.network)
  551. if s.enable_dhcp and s.ip_version == constants.IP_VERSION_4]
  552. for host_tuple in self._iter_hosts():
  553. port, alloc, hostname, name, no_dhcp, no_opts = host_tuple
  554. # don't write ip address which belongs to a dhcp disabled subnet
  555. # or an IPv6 subnet.
  556. if no_dhcp or alloc.subnet_id not in dhcpv4_enabled_subnet_ids:
  557. continue
  558. # all that matters is the mac address and IP. the hostname and
  559. # client ID will be overwritten on the next renewal.
  560. buf.write('%s %s %s * *\n' %
  561. (timestamp, port.mac_address, alloc.ip_address))
  562. contents = buf.getvalue()
  563. file_utils.replace_file(filename, contents)
  564. LOG.debug('Done building initial lease file %s with contents:\n%s',
  565. filename, contents)
  566. return filename
  567. @staticmethod
  568. def _format_address_for_dnsmasq(address):
  569. # (dzyu) Check if it is legal ipv6 address, if so, need wrap
  570. # it with '[]' to let dnsmasq to distinguish MAC address from
  571. # IPv6 address.
  572. if netaddr.valid_ipv6(address):
  573. return '[%s]' % address
  574. return address
  575. def _output_hosts_file(self):
  576. """Writes a dnsmasq compatible dhcp hosts file.
  577. The generated file is sent to the --dhcp-hostsfile option of dnsmasq,
  578. and lists the hosts on the network which should receive a dhcp lease.
  579. Each line in this file is in the form::
  580. 'mac_address,FQDN,ip_address'
  581. IMPORTANT NOTE: a dnsmasq instance does not resolve hosts defined in
  582. this file if it did not give a lease to a host listed in it (e.g.:
  583. multiple dnsmasq instances on the same network if this network is on
  584. multiple network nodes). This file is only defining hosts which
  585. should receive a dhcp lease, the hosts resolution in itself is
  586. defined by the `_output_addn_hosts_file` method.
  587. """
  588. buf = six.StringIO()
  589. filename = self.get_conf_file_name('host')
  590. LOG.debug('Building host file: %s', filename)
  591. dhcp_enabled_subnet_ids = [s.id for s in
  592. self._get_all_subnets(self.network)
  593. if s.enable_dhcp]
  594. # NOTE(ihrachyshka): the loop should not log anything inside it, to
  595. # avoid potential performance drop when lots of hosts are dumped
  596. for host_tuple in self._iter_hosts():
  597. port, alloc, hostname, name, no_dhcp, no_opts = host_tuple
  598. if no_dhcp:
  599. if not no_opts and self._get_port_extra_dhcp_opts(port):
  600. buf.write('%s,%s%s\n' % (
  601. port.mac_address,
  602. 'set:', self._PORT_TAG_PREFIX % port.id))
  603. continue
  604. # don't write ip address which belongs to a dhcp disabled subnet.
  605. if alloc.subnet_id not in dhcp_enabled_subnet_ids:
  606. continue
  607. ip_address = self._format_address_for_dnsmasq(alloc.ip_address)
  608. if self._get_port_extra_dhcp_opts(port):
  609. client_id = self._get_client_id(port)
  610. if client_id and len(port.extra_dhcp_opts) > 1:
  611. buf.write('%s,%s%s,%s,%s,%s%s\n' %
  612. (port.mac_address, self._ID, client_id, name,
  613. ip_address, 'set:',
  614. self._PORT_TAG_PREFIX % port.id))
  615. elif client_id and len(port.extra_dhcp_opts) == 1:
  616. buf.write('%s,%s%s,%s,%s\n' %
  617. (port.mac_address, self._ID, client_id, name,
  618. ip_address))
  619. else:
  620. buf.write('%s,%s,%s,%s%s\n' %
  621. (port.mac_address, name, ip_address,
  622. 'set:', self._PORT_TAG_PREFIX % port.id))
  623. else:
  624. buf.write('%s,%s,%s\n' %
  625. (port.mac_address, name, ip_address))
  626. file_utils.replace_file(filename, buf.getvalue())
  627. LOG.debug('Done building host file %s', filename)
  628. return filename
  629. def _get_client_id(self, port):
  630. if self._get_port_extra_dhcp_opts(port):
  631. for opt in port.extra_dhcp_opts:
  632. if opt.opt_name in (edo_ext.DHCP_OPT_CLIENT_ID,
  633. DHCP_OPT_CLIENT_ID_NUM):
  634. return opt.opt_value
  635. def _read_hosts_file_leases(self, filename):
  636. leases = set()
  637. try:
  638. with open(filename) as f:
  639. for l in f.readlines():
  640. host = l.strip().split(',')
  641. mac = host[0]
  642. client_id = None
  643. if host[1].startswith('set:'):
  644. continue
  645. if host[1].startswith(self._ID):
  646. ip = host[3].strip('[]')
  647. client_id = host[1][len(self._ID):]
  648. else:
  649. ip = host[2].strip('[]')
  650. leases.add((ip, mac, client_id))
  651. except (OSError, IOError):
  652. LOG.debug('Error while reading hosts file %s', filename)
  653. return leases
  654. def _read_leases_file_leases(self, filename, ip_version=None):
  655. """
  656. Read information from leases file, which is needed to pass to
  657. dhcp_release6 command line utility if some of these leases are not
  658. needed anymore
  659. each line in dnsmasq leases file is one of the following
  660. * duid entry: duid server_duid
  661. There MUST be single duid entry per file
  662. * ipv4 entry: space separated list
  663. - The expiration time (seconds since unix epoch) or duration
  664. (if dnsmasq is compiled with HAVE_BROKEN_RTC) of the lease.
  665. 0 means infinite.
  666. - The link address, in format XX-YY:YY:YY[...], where XX is the ARP
  667. hardware type. "XX-" may be omitted for Ethernet.
  668. - The IPv4 address
  669. - The hostname (sent by the client or assigned by dnsmasq)
  670. or '*' for none.
  671. - The client identifier (colon-separated hex bytes)
  672. or '*' for none.
  673. * ipv6 entry: space separated list
  674. - The expiration time or duration
  675. - The IAID as a Big Endian decimal number, prefixed by T for
  676. IA_TAs (temporary addresses).
  677. - The IPv6 address
  678. - The hostname or '*'
  679. - The client DUID (colon-separated hex bytes) or '*' if unknown
  680. original discussion is in dnsmasq mailing list
  681. http://lists.thekelleys.org.uk/pipermail/\
  682. dnsmasq-discuss/2016q2/010595.html
  683. :param filename: leases file
  684. :param ip_version: IP version of entries to return, or None for all
  685. :return: dict, keys are IP(v6) addresses, values are dicts containing
  686. iaid, client_id and server_id
  687. """
  688. leases = {}
  689. server_id = None
  690. if os.path.exists(filename):
  691. with open(filename) as f:
  692. for l in f.readlines():
  693. if l.startswith('duid'):
  694. if not server_id:
  695. server_id = l.strip().split()[1]
  696. continue
  697. else:
  698. LOG.warning('Multiple DUID entries in %s '
  699. 'lease file, dnsmasq is possibly '
  700. 'not functioning properly',
  701. filename)
  702. continue
  703. parts = l.strip().split()
  704. if len(parts) != 5:
  705. LOG.warning('Invalid lease entry %s found in %s '
  706. 'lease file, ignoring', parts, filename)
  707. continue
  708. (iaid, ip, client_id) = parts[1], parts[2], parts[4]
  709. ip = ip.strip('[]')
  710. if (ip_version and
  711. netaddr.IPAddress(ip).version != ip_version):
  712. continue
  713. leases[ip] = {'iaid': iaid,
  714. 'client_id': client_id,
  715. 'server_id': server_id
  716. }
  717. return leases
  718. def _release_unused_leases(self):
  719. filename = self.get_conf_file_name('host')
  720. old_leases = self._read_hosts_file_leases(filename)
  721. leases_filename = self.get_conf_file_name('leases')
  722. cur_leases = self._read_leases_file_leases(leases_filename)
  723. if not cur_leases:
  724. return
  725. v4_leases = set()
  726. for (k, v) in cur_leases.items():
  727. # IPv4 leases have a MAC, IPv6 ones do not, so we must ignore
  728. if netaddr.IPAddress(k).version == constants.IP_VERSION_4:
  729. # treat '*' as None, see note in _read_leases_file_leases()
  730. client_id = v['client_id']
  731. if client_id is '*':
  732. client_id = None
  733. v4_leases.add((k, v['iaid'], client_id))
  734. new_leases = set()
  735. for port in self.network.ports:
  736. client_id = self._get_client_id(port)
  737. for alloc in port.fixed_ips:
  738. new_leases.add((alloc.ip_address, port.mac_address, client_id))
  739. # If an entry is in the leases or host file(s), but doesn't have
  740. # a fixed IP on a corresponding neutron port, consider it stale.
  741. entries_to_release = (v4_leases | old_leases) - new_leases
  742. if not entries_to_release:
  743. return
  744. # If the VM advertises a client ID in its lease, but its not set in
  745. # the port's Extra DHCP Opts, the lease will not be filtered above.
  746. # Release the lease only if client ID is set in port DB and a mismatch
  747. # Otherwise the lease is released when other ports are deleted/updated
  748. entries_with_no_client_id = set()
  749. for ip, mac, client_id in entries_to_release:
  750. if client_id:
  751. entry_no_client_id = (ip, mac, None)
  752. if (entry_no_client_id in old_leases and
  753. entry_no_client_id in new_leases):
  754. entries_with_no_client_id.add((ip, mac, client_id))
  755. entries_to_release -= entries_with_no_client_id
  756. # Try DHCP_RELEASE_TRIES times to release a lease, re-reading the
  757. # file each time to see if it's still there. We loop +1 times to
  758. # check the lease file one last time before logging any remaining
  759. # entries.
  760. for i in range(DHCP_RELEASE_TRIES + 1):
  761. entries_not_present = set()
  762. for ip, mac, client_id in entries_to_release:
  763. try:
  764. entry = cur_leases[ip]
  765. except KeyError:
  766. entries_not_present.add((ip, mac, client_id))
  767. continue
  768. # if not the final loop, try and release
  769. if i < DHCP_RELEASE_TRIES:
  770. ip_version = netaddr.IPAddress(ip).version
  771. if ip_version == constants.IP_VERSION_6:
  772. client_id = entry['client_id']
  773. self._release_lease(mac, ip, ip_version, client_id,
  774. entry['server_id'], entry['iaid'])
  775. # Remove elements that were not in the current leases file,
  776. # no need to look for them again, and see if we're done.
  777. entries_to_release -= entries_not_present
  778. if not entries_to_release:
  779. break
  780. if i < DHCP_RELEASE_TRIES:
  781. time.sleep(DHCP_RELEASE_TRIES_SLEEP)
  782. cur_leases = self._read_leases_file_leases(leases_filename)
  783. if not cur_leases:
  784. break
  785. else:
  786. LOG.warning("Could not release DHCP leases for these IP "
  787. "addresses after %d tries: %s",
  788. DHCP_RELEASE_TRIES,
  789. ', '.join(ip for ip, m, c in entries_to_release))
  790. def _output_addn_hosts_file(self):
  791. """Writes a dnsmasq compatible additional hosts file.
  792. The generated file is sent to the --addn-hosts option of dnsmasq,
  793. and lists the hosts on the network which should be resolved even if
  794. the dnsmasq instance did not give a lease to the host (see the
  795. `_output_hosts_file` method).
  796. Each line in this file is in the same form as a standard /etc/hosts
  797. file.
  798. """
  799. buf = six.StringIO()
  800. for host_tuple in self._iter_hosts():
  801. port, alloc, hostname, fqdn, no_dhcp, no_opts = host_tuple
  802. # It is compulsory to write the `fqdn` before the `hostname` in
  803. # order to obtain it in PTR responses.
  804. if alloc:
  805. buf.write('%s\t%s %s\n' % (alloc.ip_address, fqdn, hostname))
  806. addn_hosts = self.get_conf_file_name('addn_hosts')
  807. file_utils.replace_file(addn_hosts, buf.getvalue())
  808. return addn_hosts
  809. def _output_opts_file(self):
  810. """Write a dnsmasq compatible options file."""
  811. options, subnet_index_map = self._generate_opts_per_subnet()
  812. options += self._generate_opts_per_port(subnet_index_map)
  813. name = self.get_conf_file_name('opts')
  814. file_utils.replace_file(name, '\n'.join(options))
  815. return name
  816. def _generate_opts_per_subnet(self):
  817. options = []
  818. subnets_without_nameservers = set()
  819. if self.conf.enable_isolated_metadata or self.conf.force_metadata:
  820. subnet_to_interface_ip = self._make_subnet_interface_ip_map()
  821. isolated_subnets = self.get_isolated_subnets(self.network)
  822. for subnet in self._get_all_subnets(self.network):
  823. addr_mode = getattr(subnet, 'ipv6_address_mode', None)
  824. segment_id = getattr(subnet, 'segment_id', None)
  825. if (not subnet.enable_dhcp or
  826. (subnet.ip_version == 6 and
  827. addr_mode == constants.IPV6_SLAAC)):
  828. continue
  829. if subnet.dns_nameservers:
  830. if ((subnet.ip_version == 4 and
  831. subnet.dns_nameservers == ['0.0.0.0']) or
  832. (subnet.ip_version == 6 and
  833. subnet.dns_nameservers == ['::'])):
  834. # Special case: Do not announce DNS servers
  835. options.append(
  836. self._format_option(
  837. subnet.ip_version,
  838. self._SUBNET_TAG_PREFIX % subnet.id,
  839. 'dns-server'))
  840. else:
  841. options.append(
  842. self._format_option(
  843. subnet.ip_version,
  844. self._SUBNET_TAG_PREFIX % subnet.id,
  845. 'dns-server', ','.join(
  846. Dnsmasq._convert_to_literal_addrs(
  847. subnet.ip_version,
  848. subnet.dns_nameservers))))
  849. else:
  850. # use the dnsmasq ip as nameservers only if there is no
  851. # dns-server submitted by the server
  852. # Here is something to check still
  853. subnets_without_nameservers.add(subnet.id)
  854. if self.conf.dns_domain and subnet.ip_version == 6:
  855. # This should be change also
  856. options.append(
  857. self._format_option(
  858. subnet.ip_version, self._SUBNET_TAG_PREFIX % subnet.id,
  859. "domain-search", ''.join(self.conf.dns_domain)))
  860. gateway = subnet.gateway_ip
  861. host_routes = []
  862. for hr in subnet.host_routes:
  863. if hr.destination == constants.IPv4_ANY:
  864. if not gateway:
  865. gateway = hr.nexthop
  866. else:
  867. host_routes.append("%s,%s" % (hr.destination, hr.nexthop))
  868. # Add host routes for isolated network segments
  869. if ((self.conf.force_metadata or
  870. (isolated_subnets[subnet.id] and
  871. self.conf.enable_isolated_metadata)) and
  872. subnet.ip_version == 4):
  873. subnet_dhcp_ip = subnet_to_interface_ip.get(subnet.id)
  874. if subnet_dhcp_ip:
  875. host_routes.append(
  876. '%s/32,%s' % (METADATA_DEFAULT_IP, subnet_dhcp_ip)
  877. )
  878. elif not isolated_subnets[subnet.id] and gateway:
  879. host_routes.append(
  880. '%s/32,%s' % (METADATA_DEFAULT_IP, gateway)
  881. )
  882. if subnet.ip_version == 4:
  883. for s in self._get_all_subnets(self.network):
  884. sub_segment_id = getattr(s, 'segment_id', None)
  885. if (s.ip_version == 4 and
  886. s.cidr != subnet.cidr and
  887. sub_segment_id == segment_id):
  888. host_routes.append("%s,0.0.0.0" % s.cidr)
  889. if host_routes:
  890. if gateway:
  891. host_routes.append("%s,%s" % (constants.IPv4_ANY,
  892. gateway))
  893. options.append(
  894. self._format_option(
  895. subnet.ip_version,
  896. self._SUBNET_TAG_PREFIX % subnet.id,
  897. 'classless-static-route',
  898. ','.join(host_routes)))
  899. options.append(
  900. self._format_option(
  901. subnet.ip_version,
  902. self._SUBNET_TAG_PREFIX % subnet.id,
  903. WIN2k3_STATIC_DNS,
  904. ','.join(host_routes)))
  905. if gateway:
  906. options.append(self._format_option(
  907. subnet.ip_version, self._SUBNET_TAG_PREFIX % subnet.id,
  908. 'router', gateway))
  909. else:
  910. options.append(self._format_option(
  911. subnet.ip_version, self._SUBNET_TAG_PREFIX % subnet.id,
  912. 'router'))
  913. return options, subnets_without_nameservers
  914. def _generate_opts_per_port(self, subnets_without_nameservers):
  915. options = []
  916. dhcp_ips = collections.defaultdict(list)
  917. for port in self.network.ports:
  918. if self._get_port_extra_dhcp_opts(port):
  919. port_ip_versions = set(
  920. [netaddr.IPAddress(ip.ip_address).version
  921. for ip in port.fixed_ips])
  922. for opt in port.extra_dhcp_opts:
  923. if opt.opt_name in (edo_ext.DHCP_OPT_CLIENT_ID,
  924. DHCP_OPT_CLIENT_ID_NUM):
  925. continue
  926. opt_ip_version = opt.ip_version
  927. if opt_ip_version in port_ip_versions:
  928. options.append(
  929. self._format_option(
  930. opt_ip_version,
  931. self._PORT_TAG_PREFIX % port.id,
  932. opt.opt_name, opt.opt_value))
  933. else:
  934. LOG.info("Cannot apply dhcp option %(opt)s "
  935. "because it's ip_version %(version)d "
  936. "is not in port's address IP versions",
  937. {'opt': opt.opt_name,
  938. 'version': opt_ip_version})
  939. # provides all dnsmasq ip as dns-server if there is more than
  940. # one dnsmasq for a subnet and there is no dns-server submitted
  941. # by the server
  942. if port.device_owner == constants.DEVICE_OWNER_DHCP:
  943. for ip in port.fixed_ips:
  944. if ip.subnet_id not in subnets_without_nameservers:
  945. continue
  946. dhcp_ips[ip.subnet_id].append(ip.ip_address)
  947. for subnet_id, ips in dhcp_ips.items():
  948. for ip_version in (4, 6):
  949. vx_ips = [ip for ip in ips
  950. if netaddr.IPAddress(ip).version == ip_version]
  951. if len(vx_ips) > 1:
  952. options.append(
  953. self._format_option(
  954. ip_version, self._SUBNET_TAG_PREFIX % subnet_id,
  955. 'dns-server',
  956. ','.join(
  957. Dnsmasq._convert_to_literal_addrs(ip_version,
  958. vx_ips))))
  959. return options
  960. def _make_subnet_interface_ip_map(self):
  961. ip_dev = ip_lib.IPDevice(self.interface_name,
  962. namespace=self.network.namespace)
  963. subnet_lookup = dict(
  964. (netaddr.IPNetwork(subnet.cidr), subnet.id)
  965. for subnet in self.network.subnets
  966. )
  967. retval = {}
  968. for addr in ip_dev.addr.list():
  969. ip_net = netaddr.IPNetwork(addr['cidr'])
  970. if ip_net in subnet_lookup:
  971. retval[subnet_lookup[ip_net]] = addr['cidr'].split('/')[0]
  972. return retval
  973. def _format_option(self, ip_version, tag, option, *args):
  974. """Format DHCP option by option name or code."""
  975. option = str(option)
  976. pattern = "(tag:(.*),)?(.*)$"
  977. matches = re.match(pattern, option)
  978. extra_tag = matches.groups()[0]
  979. option = matches.groups()[2]
  980. if not option.isdigit():
  981. if ip_version == 4:
  982. option = 'option:%s' % option
  983. else:
  984. option = 'option6:%s' % option
  985. if extra_tag:
  986. tags = ('tag:' + tag, extra_tag[:-1], '%s' % option)
  987. else:
  988. tags = ('tag:' + tag, '%s' % option)
  989. return ','.join(tags + args)
  990. @staticmethod
  991. def _convert_to_literal_addrs(ip_version, ips):
  992. if ip_version == 4:
  993. return ips
  994. return ['[' + ip + ']' for ip in ips]
  995. @classmethod
  996. def get_isolated_subnets(cls, network):
  997. """Returns a dict indicating whether or not a subnet is isolated
  998. A subnet is considered non-isolated if there is a port connected to
  999. the subnet, and the port's ip address matches that of the subnet's
  1000. gateway. The port must be owned by a neutron router.
  1001. """
  1002. isolated_subnets = collections.defaultdict(lambda: True)
  1003. all_subnets = cls._get_all_subnets(network)
  1004. subnets = dict((subnet.id, subnet) for subnet in all_subnets)
  1005. for port in network.ports:
  1006. if port.device_owner not in constants.ROUTER_INTERFACE_OWNERS:
  1007. continue
  1008. for alloc in port.fixed_ips:
  1009. if (alloc.subnet_id in subnets and
  1010. subnets[alloc.subnet_id].gateway_ip == alloc.ip_address):
  1011. isolated_subnets[alloc.subnet_id] = False
  1012. return isolated_subnets
  1013. @staticmethod
  1014. def has_metadata_subnet(subnets):
  1015. """Check if the subnets has a metadata subnet."""
  1016. meta_cidr = netaddr.IPNetwork(METADATA_DEFAULT_CIDR)
  1017. if any(netaddr.IPNetwork(s.cidr) in meta_cidr
  1018. for s in subnets):
  1019. return True
  1020. return False
  1021. @classmethod
  1022. def should_enable_metadata(cls, conf, network):
  1023. """Determine whether the metadata proxy is needed for a network
  1024. This method returns True for truly isolated networks (ie: not attached
  1025. to a router) when enable_isolated_metadata is True, or for all the
  1026. networks when the force_metadata flags is True.
  1027. This method also returns True when enable_metadata_network is True,
  1028. and the network passed as a parameter has a subnet in the link-local
  1029. CIDR, thus characterizing it as a "metadata" network. The metadata
  1030. network is used by solutions which do not leverage the l3 agent for
  1031. providing access to the metadata service via logical routers built
  1032. with 3rd party backends.
  1033. """
  1034. # Only IPv4 subnets, with dhcp enabled, will use the metadata proxy.
  1035. all_subnets = cls._get_all_subnets(network)
  1036. v4_dhcp_subnets = [s for s in all_subnets
  1037. if s.ip_version == 4 and s.enable_dhcp]
  1038. if not v4_dhcp_subnets:
  1039. return False
  1040. if conf.force_metadata:
  1041. return True
  1042. if not conf.enable_isolated_metadata:
  1043. return False
  1044. if (conf.enable_metadata_network and
  1045. cls.has_metadata_subnet(all_subnets)):
  1046. return True
  1047. isolated_subnets = cls.get_isolated_subnets(network)
  1048. return any(isolated_subnets[s.id] for s in v4_dhcp_subnets)
  1049. class DeviceManager(object):
  1050. def __init__(self, conf, plugin):
  1051. self.conf = conf
  1052. self.plugin = plugin
  1053. self.driver = agent_common_utils.load_interface_driver(conf)
  1054. def get_interface_name(self, network, port):
  1055. """Return interface(device) name for use by the DHCP process."""
  1056. return self.driver.get_device_name(port)
  1057. def get_device_id(self, network):
  1058. """Return a unique DHCP device ID for this host on the network."""
  1059. # There could be more than one dhcp server per network, so create
  1060. # a device id that combines host and network ids
  1061. return common_utils.get_dhcp_agent_device_id(network.id,
  1062. self.conf.host)
  1063. def _set_default_route_ip_version(self, network, device_name, ip_version):
  1064. device = ip_lib.IPDevice(device_name, namespace=network.namespace)
  1065. gateway = device.route.get_gateway(ip_version=ip_version)
  1066. if gateway:
  1067. gateway = gateway.get('gateway')
  1068. for subnet in network.subnets:
  1069. skip_subnet = (
  1070. subnet.ip_version != ip_version
  1071. or not subnet.enable_dhcp
  1072. or subnet.gateway_ip is None)
  1073. if skip_subnet:
  1074. continue
  1075. if subnet.ip_version == constants.IP_VERSION_6:
  1076. # This is duplicating some of the API checks already done,
  1077. # but some of the functional tests call directly
  1078. prefixlen = netaddr.IPNetwork(subnet.cidr).prefixlen
  1079. if prefixlen == 0 or prefixlen > 126:
  1080. continue
  1081. modes = [constants.IPV6_SLAAC, constants.DHCPV6_STATELESS]
  1082. addr_mode = getattr(subnet, 'ipv6_address_mode', None)
  1083. ra_mode = getattr(subnet, 'ipv6_ra_mode', None)
  1084. if (prefixlen != 64 and
  1085. (addr_mode in modes or ra_mode in modes)):
  1086. continue
  1087. if gateway != subnet.gateway_ip:
  1088. LOG.debug('Setting IPv%(version)s gateway for dhcp netns '
  1089. 'on net %(n)s to %(ip)s',
  1090. {'n': network.id, 'ip': subnet.gateway_ip,
  1091. 'version': ip_version})
  1092. # Check for and remove the on-link route for the old
  1093. # gateway being replaced, if it is outside the subnet
  1094. is_old_gateway_not_in_subnet = (gateway and
  1095. not ipam_utils.check_subnet_ip(
  1096. subnet.cidr, gateway))
  1097. if is_old_gateway_not_in_subnet:
  1098. onlink = device.route.list_onlink_routes(ip_version)
  1099. existing_onlink_routes = set(r['cidr'] for r in onlink)
  1100. if gateway in existing_onlink_routes:
  1101. device.route.delete_route(gateway, scope='link')
  1102. is_new_gateway_not_in_subnet = (subnet.gateway_ip and
  1103. not ipam_utils.check_subnet_ip(
  1104. subnet.cidr,
  1105. subnet.gateway_ip))
  1106. if is_new_gateway_not_in_subnet:
  1107. device.route.add_route(subnet.gateway_ip, scope='link')
  1108. device.route.add_gateway(subnet.gateway_ip)
  1109. return
  1110. # No subnets on the network have a valid gateway. Clean it up to avoid
  1111. # confusion from seeing an invalid gateway here.
  1112. if gateway is not None:
  1113. LOG.debug('Removing IPv%(version)s gateway for dhcp netns on '
  1114. 'net %(n)s',
  1115. {'n': network.id, 'version': ip_version})
  1116. device.route.delete_gateway(gateway)
  1117. def _set_default_route(self, network, device_name):
  1118. """Sets the default gateway for this dhcp namespace.
  1119. This method is idempotent and will only adjust the route if adjusting
  1120. it would change it from what it already is. This makes it safe to call
  1121. and avoids unnecessary perturbation of the system.
  1122. """
  1123. for ip_version in (constants.IP_VERSION_4, constants.IP_VERSION_6):
  1124. self._set_default_route_ip_version(network, device_name,
  1125. ip_version)
  1126. def _setup_existing_dhcp_port(self, network, device_id, dhcp_subnets):
  1127. """Set up the existing DHCP port, if there is one."""
  1128. # To avoid pylint thinking that port might be undefined after
  1129. # the following loop...
  1130. port = None
  1131. # Look for an existing DHCP port for this network.
  1132. for port in network.ports:
  1133. port_device_id = getattr(port, 'device_id', None)
  1134. if port_device_id == device_id:
  1135. # If using gateway IPs on this port, we can skip the
  1136. # following code, whose purpose is just to review and
  1137. # update the Neutron-allocated IP addresses for the
  1138. # port.
  1139. if self.driver.use_gateway_ips:
  1140. return port
  1141. # Otherwise break out, as we now have the DHCP port
  1142. # whose subnets and addresses we need to review.
  1143. break
  1144. else:
  1145. return None
  1146. # Compare what the subnets should be against what is already
  1147. # on the port.
  1148. dhcp_enabled_subnet_ids = set(dhcp_subnets)
  1149. port_subnet_ids = set(ip.subnet_id for ip in port.fixed_ips)
  1150. # If those differ, we need to call update.
  1151. if dhcp_enabled_subnet_ids != port_subnet_ids:
  1152. # Collect the subnets and fixed IPs that the port already
  1153. # has, for subnets that are still in the DHCP-enabled set.
  1154. wanted_fixed_ips = []
  1155. for fixed_ip in port.fixed_ips:
  1156. if fixed_ip.subnet_id in dhcp_enabled_subnet_ids:
  1157. wanted_fixed_ips.append(
  1158. {'subnet_id': fixed_ip.subnet_id,
  1159. 'ip_address': fixed_ip.ip_address})
  1160. # Add subnet IDs for new DHCP-enabled subnets.
  1161. wanted_fixed_ips.extend(
  1162. dict(subnet_id=s)
  1163. for s in dhcp_enabled_subnet_ids - port_subnet_ids)
  1164. # Update the port to have the calculated subnets and fixed
  1165. # IPs. The Neutron server will allocate a fresh IP for
  1166. # each subnet that doesn't already have one.
  1167. port = self.plugin.update_dhcp_port(
  1168. port.id,
  1169. {'port': {'network_id': network.id,
  1170. 'fixed_ips': wanted_fixed_ips}})
  1171. if not port:
  1172. raise exceptions.Conflict()
  1173. return port
  1174. def _setup_reserved_dhcp_port(self, network, device_id, dhcp_subnets):
  1175. """Setup the reserved DHCP port, if there is one."""
  1176. LOG.debug('DHCP port %(device_id)s on network %(network_id)s'
  1177. ' does not yet exist. Checking for a reserved port.',
  1178. {'device_id': device_id, 'network_id': network.id})
  1179. for port in network.ports:
  1180. port_device_id = getattr(port, 'device_id', None)
  1181. if port_device_id == constants.DEVICE_ID_RESERVED_DHCP_PORT:
  1182. port = self.plugin.update_dhcp_port(
  1183. port.id, {'port': {'network_id': network.id,
  1184. 'device_id': device_id}})
  1185. if port:
  1186. return port
  1187. def _setup_new_dhcp_port(self, network, device_id, dhcp_subnets):
  1188. """Create and set up new DHCP port for the specified network."""
  1189. LOG.debug('DHCP port %(device_id)s on network %(network_id)s'
  1190. ' does not yet exist. Creating new one.',
  1191. {'device_id': device_id, 'network_id': network.id})
  1192. # Make a list of the subnets that need a unique IP address for
  1193. # this DHCP port.
  1194. if self.driver.use_gateway_ips:
  1195. unique_ip_subnets = []
  1196. else:
  1197. unique_ip_subnets = [dict(subnet_id=s) for s in dhcp_subnets]
  1198. port_dict = dict(
  1199. name='',
  1200. admin_state_up=True,
  1201. device_id=device_id,
  1202. network_id=network.id,
  1203. tenant_id=network.tenant_id,
  1204. fixed_ips=unique_ip_subnets)
  1205. return self.plugin.create_dhcp_port({'port': port_dict})
  1206. def setup_dhcp_port(self, network):
  1207. """Create/update DHCP port for the host if needed and return port."""
  1208. # The ID that the DHCP port will have (or already has).
  1209. device_id = self.get_device_id(network)
  1210. # Get the set of DHCP-enabled local subnets on this network.
  1211. dhcp_subnets = {subnet.id: subnet for subnet in network.subnets
  1212. if subnet.enable_dhcp}
  1213. # There are 3 cases: either the DHCP port already exists (but
  1214. # might need to be updated for a changed set of subnets); or
  1215. # some other code has already prepared a 'reserved' DHCP port,
  1216. # and we just need to adopt that; or we need to create a new
  1217. # DHCP port. Try each of those in turn until we have a DHCP
  1218. # port.
  1219. for setup_method in (self._setup_existing_dhcp_port,
  1220. self._setup_reserved_dhcp_port,
  1221. self._setup_new_dhcp_port):
  1222. dhcp_port = setup_method(network, device_id, dhcp_subnets)
  1223. if dhcp_port:
  1224. break
  1225. else:
  1226. raise exceptions.Conflict()
  1227. # FIXME(kevinbenton): ensure we have the IPs we actually need.
  1228. # can be removed once bug/1627480 is fixed
  1229. if not self.driver.use_gateway_ips:
  1230. expected = set(dhcp_subnets)
  1231. actual = {fip.subnet_id for fip in dhcp_port.fixed_ips}
  1232. missing = expected - actual
  1233. if missing:
  1234. LOG.debug("Requested DHCP port with IPs on subnets "
  1235. "%(expected)s but only got IPs on subnets "
  1236. "%(actual)s.", {'expected': expected,
  1237. 'actual': actual})
  1238. raise exceptions.SubnetMismatchForPort(
  1239. port_id=dhcp_port.id, subnet_id=list(missing)[0])
  1240. # Convert subnet_id to subnet dict
  1241. fixed_ips = [dict(subnet_id=fixed_ip.subnet_id,
  1242. ip_address=fixed_ip.ip_address,
  1243. subnet=dhcp_subnets[fixed_ip.subnet_id])
  1244. for fixed_ip in dhcp_port.fixed_ips
  1245. # we don't care about any ips on subnets irrelevant
  1246. # to us (e.g. auto ipv6 addresses)
  1247. if fixed_ip.subnet_id in dhcp_subnets]
  1248. ips = [DictModel(item) if isinstance(item, dict) else item
  1249. for item in fixed_ips]
  1250. dhcp_port.fixed_ips = ips
  1251. return dhcp_port
  1252. def _update_dhcp_port(self, network, port):
  1253. for index in range(len(network.ports)):
  1254. if network.ports[index].id == port.id:
  1255. network.ports[index] = port
  1256. break
  1257. else:
  1258. network.ports.append(port)
  1259. def _cleanup_stale_devices(self, network, dhcp_port):
  1260. """Unplug any devices found in the namespace except for dhcp_port."""
  1261. LOG.debug("Cleaning stale devices for network %s", network.id)
  1262. skip_dev_name = (self.driver.get_device_name(dhcp_port)
  1263. if dhcp_port else None)
  1264. ns_ip = ip_lib.IPWrapper(namespace=network.namespace)
  1265. if not ns_ip.netns.exists(network.namespace):
  1266. return
  1267. for d in ns_ip.get_devices():
  1268. # delete all devices except current active DHCP port device
  1269. if d.name != skip_dev_name:
  1270. LOG.debug("Found stale device %s, deleting", d.name)
  1271. try:
  1272. self.unplug(d.name, network)
  1273. except Exception:
  1274. LOG.exception("Exception during stale "
  1275. "dhcp device cleanup")
  1276. def plug(self, network, port, interface_name):
  1277. """Plug device settings for the network's DHCP on this host."""
  1278. self.driver.plug(network.id,
  1279. port.id,
  1280. interface_name,
  1281. port.mac_address,
  1282. namespace=network.namespace,
  1283. mtu=network.get('mtu'))
  1284. def setup(self, network):
  1285. """Create and initialize a device for network's DHCP on this host."""
  1286. try:
  1287. port = self.setup_dhcp_port(network)
  1288. except Exception:
  1289. with excutils.save_and_reraise_exception():
  1290. # clear everything out so we don't leave dangling interfaces
  1291. # if setup never succeeds in the future.
  1292. self._cleanup_stale_devices(network, dhcp_port=None)
  1293. self._update_dhcp_port(network, port)
  1294. interface_name = self.get_interface_name(network, port)
  1295. # Disable acceptance of RAs in the namespace so we don't
  1296. # auto-configure an IPv6 address since we explicitly configure
  1297. # them on the device. This must be done before any interfaces
  1298. # are plugged since it could receive an RA by the time
  1299. # plug() returns, so we have to create the namespace first.
  1300. # It must also be done in the case there is an existing IPv6
  1301. # address here created via SLAAC, since it will be deleted
  1302. # and added back statically in the call to init_l3() below.
  1303. if network.namespace:
  1304. ip_lib.IPWrapper().ensure_namespace(network.namespace)
  1305. ip_lib.set_ip_nonlocal_bind_for_namespace(network.namespace, 1,
  1306. root_namespace=True)
  1307. if ipv6_utils.is_enabled_and_bind_by_default():
  1308. self.driver.configure_ipv6_ra(network.namespace, 'default',
  1309. n_const.ACCEPT_RA_DISABLED)
  1310. if ip_lib.ensure_device_is_ready(interface_name,
  1311. namespace=network.namespace):
  1312. LOG.debug('Reusing existing device: %s.', interface_name)
  1313. # force mtu on the port for in case it was changed for the network
  1314. mtu = getattr(network, 'mtu', 0)
  1315. if mtu:
  1316. self.driver.set_mtu(interface_name, mtu,
  1317. namespace=network.namespace)
  1318. else:
  1319. try:
  1320. self.plug(network, port, interface_name)
  1321. except Exception:
  1322. with excutils.save_and_reraise_exception():
  1323. LOG.exception('Unable to plug DHCP port for '
  1324. 'network %s. Releasing port.',
  1325. network.id)
  1326. # We should unplug the interface in bridge side.
  1327. self.unplug(interface_name, network)
  1328. self.plugin.release_dhcp_port(network.id, port.device_id)
  1329. self.fill_dhcp_udp_checksums(namespace=network.namespace)
  1330. ip_cidrs = []
  1331. for fixed_ip in port.fixed_ips:
  1332. subnet = fixed_ip.subnet
  1333. net = netaddr.IPNetwork(subnet.cidr)
  1334. ip_cidr = '%s/%s' % (fixed_ip.ip_address, net.prefixlen)
  1335. ip_cidrs.append(ip_cidr)
  1336. if self.driver.use_gateway_ips:
  1337. # For each DHCP-enabled subnet, add that subnet's gateway
  1338. # IP address to the Linux device for the DHCP port.
  1339. for subnet in network.subnets:
  1340. if not subnet.enable_dhcp:
  1341. continue
  1342. gateway = subnet.gateway_ip
  1343. if gateway:
  1344. net = netaddr.IPNetwork(subnet.cidr)
  1345. ip_cidrs.append('%s/%s' % (gateway, net.prefixlen))
  1346. if self.conf.force_metadata or self.conf.enable_isolated_metadata:
  1347. ip_cidrs.append(METADATA_DEFAULT_CIDR)
  1348. self.driver.init_l3(interface_name, ip_cidrs,
  1349. namespace=network.namespace)
  1350. self._set_default_route(network, interface_name)
  1351. self._cleanup_stale_devices(network, port)
  1352. return interface_name
  1353. def update(self, network, device_name):
  1354. """Update device settings for the network's DHCP on this host."""
  1355. self._set_default_route(network, device_name)
  1356. def unplug(self, device_name, network):
  1357. """Unplug device settings for the network's DHCP on this host."""
  1358. self.driver.unplug(device_name, namespace=network.namespace)
  1359. def destroy(self, network, device_name):
  1360. """Destroy the device used for the network's DHCP on this host."""
  1361. if device_name:
  1362. self.unplug(device_name, network)
  1363. else:
  1364. LOG.debug('No interface exists for network %s', network.id)
  1365. self.plugin.release_dhcp_port(network.id,
  1366. self.get_device_id(network))
  1367. def fill_dhcp_udp_checksums(self, namespace):
  1368. """Ensure DHCP reply packets always have correct UDP checksums."""
  1369. iptables_mgr = iptables_manager.IptablesManager(use_ipv6=True,
  1370. namespace=namespace)
  1371. ipv4_rule = ('-p udp -m udp --dport %d -j CHECKSUM --checksum-fill'
  1372. % constants.DHCP_RESPONSE_PORT)
  1373. ipv6_rule = ('-p udp -m udp --dport %d -j CHECKSUM --checksum-fill'
  1374. % n_const.DHCPV6_CLIENT_PORT)
  1375. iptables_mgr.ipv4['mangle'].add_rule('POSTROUTING', ipv4_rule)
  1376. iptables_mgr.ipv6['mangle'].add_rule('POSTROUTING', ipv6_rule)
  1377. iptables_mgr.apply()