This file is indexed.

/usr/lib/python3/dist-packages/maasserver/dhcp.py is in python3-django-maas 2.4.0~beta2-6865-gec43e47e6-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
# Copyright 2012-2016 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""DHCP management module."""

__all__ = [
    'configure_dhcp',
    'validate_dhcp_config',
    ]

from collections import (
    defaultdict,
    namedtuple,
)
from itertools import groupby
from operator import itemgetter
from typing import (
    Iterable,
    Optional,
    Union,
)

from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models import Q
from maasserver.dns.zonegenerator import (
    get_dns_search_paths,
    get_dns_server_addresses,
)
from maasserver.enum import (
    INTERFACE_TYPE,
    IPADDRESS_TYPE,
    IPRANGE_TYPE,
    SERVICE_STATUS,
)
from maasserver.exceptions import UnresolvableHost
from maasserver.models import (
    Config,
    DHCPSnippet,
    Domain,
    RackController,
    Service,
    StaticIPAddress,
    Subnet,
)
from maasserver.rpc import (
    getAllClients,
    getClientFor,
    getRandomClient,
)
from maasserver.utils.orm import transactional
from maasserver.utils.threads import deferToDatabase
from netaddr import (
    IPAddress,
    IPNetwork,
)
from provisioningserver.dhcp.omshell import generate_omapi_key
from provisioningserver.logger import LegacyLogger
from provisioningserver.rpc.cluster import (
    ConfigureDHCPv4,
    ConfigureDHCPv4_V2,
    ConfigureDHCPv6,
    ConfigureDHCPv6_V2,
    ValidateDHCPv4Config,
    ValidateDHCPv4Config_V2,
    ValidateDHCPv6Config,
    ValidateDHCPv6Config_V2,
)
from provisioningserver.rpc.dhcp import downgrade_shared_networks
from provisioningserver.rpc.exceptions import NoConnectionsAvailable
from provisioningserver.utils import typed
from provisioningserver.utils.text import split_string_list
from provisioningserver.utils.twisted import (
    asynchronous,
    synchronous,
)
from twisted.internet.defer import inlineCallbacks
from twisted.protocols import amp


log = LegacyLogger()


def get_omapi_key():
    """Return the OMAPI key for all DHCP servers that are ran by MAAS."""
    key = Config.objects.get_config("omapi_key")
    if key is None or key == '':
        key = generate_omapi_key()
        Config.objects.set_config("omapi_key", key)
    return key


def split_managed_ipv4_ipv6_subnets(subnets: Iterable[Subnet]):
    """Divide `subnets` into IPv4 ones and IPv6 ones.

    :param subnets: A sequence of subnets.
    :return: A tuple of two separate sequences: IPv4 subnets and IPv6 subnets.
    """
    split = defaultdict(list)
    for subnet in (s for s in subnets if s.managed is True):
        split[subnet.get_ipnetwork().version].append(subnet)
    assert len(split) <= 2, (
        "Unexpected IP version(s): %s" % ', '.join(list(split.keys())))
    return split[4], split[6]


def ip_is_sticky_or_auto(ip_address):
    """Return True if the `ip_address` alloc_type is STICKY or AUTO."""
    return ip_address.alloc_type in [
        IPADDRESS_TYPE.STICKY, IPADDRESS_TYPE.AUTO]


def get_best_interface(interfaces):
    """Return `Interface` from `interfaces` that is the best.

    This is used by `get_subnet_to_interface_mapping` to select the very best
    interface on a `Subnet`. Bond interfaces are selected over physical/vlan
    interfaces.
    """
    best_interface = None
    for interface in interfaces:
        if best_interface is None:
            best_interface = interface
        elif (best_interface.type == INTERFACE_TYPE.PHYSICAL and
                interface.type == INTERFACE_TYPE.BOND):
            best_interface = interface
        elif (best_interface.type == INTERFACE_TYPE.VLAN and
                interface.type == INTERFACE_TYPE.PHYSICAL):
            best_interface = interface
    return best_interface


def ip_is_version(ip_address, ip_version):
    """Return True if `ip_address` is the same IP version as `ip_version`."""
    return (
        ip_address.ip is not None and
        ip_address.ip != "" and
        IPAddress(ip_address.ip).version == ip_version)


def _key_interface_subnet_dynamic_range_count(interface):
    """Return the number of dynamic ranges for the subnet on the interface."""
    count = 0
    for ip_address in interface.ip_addresses.all():
        for ip_range in ip_address.subnet.iprange_set.all():
            if ip_range.type == IPRANGE_TYPE.DYNAMIC:
                count += 1
    return count


def get_interfaces_with_ip_on_vlan(rack_controller, vlan, ip_version):
    """Return a list of interfaces that have an assigned IP address on `vlan`.

    The assigned IP address needs to be of same `ip_version`. Only a list of
    STICKY or AUTO addresses will be returned, unless none exists which will
    fallback to DISCOVERED addresses.

    The interfaces will be ordered so that interfaces with IP address on
    subnets for the VLAN that have dynamic IP ranges defined.
    """
    interfaces_with_static = []
    interfaces_with_discovered = []
    for interface in rack_controller.interface_set.all().prefetch_related(
            "ip_addresses__subnet__vlan",
            "ip_addresses__subnet__iprange_set"):
        for ip_address in interface.ip_addresses.all():
            if ip_address.alloc_type in [
                    IPADDRESS_TYPE.AUTO, IPADDRESS_TYPE.STICKY]:
                if (ip_is_version(ip_address, ip_version) and
                        ip_address.subnet is not None and
                        ip_address.subnet.vlan == vlan):
                    interfaces_with_static.append(interface)
                    break
            elif ip_address.alloc_type == IPADDRESS_TYPE.DISCOVERED:
                if (ip_is_version(ip_address, ip_version) and
                        ip_address.subnet is not None and
                        ip_address.subnet.vlan == vlan):
                    interfaces_with_discovered.append(interface)
                    break
    if len(interfaces_with_static) == 1:
        return interfaces_with_static
    elif len(interfaces_with_static) > 1:
        return sorted(
            interfaces_with_static,
            key=_key_interface_subnet_dynamic_range_count,
            reverse=True)
    elif len(interfaces_with_discovered) == 1:
        return interfaces_with_discovered
    elif len(interfaces_with_discovered) > 1:
        return sorted(
            interfaces_with_discovered,
            key=_key_interface_subnet_dynamic_range_count,
            reverse=True)
    else:
        return []


def gen_managed_vlans_for(rack_controller):
    """Yeilds each `VLAN` for the `rack_controller` when DHCP is enabled and
    `rack_controller` is either the `primary_rack` or the `secondary_rack`.
    """
    interfaces = rack_controller.interface_set.filter(
        Q(vlan__dhcp_on=True) & (
            Q(vlan__primary_rack=rack_controller) |
            Q(vlan__secondary_rack=rack_controller)))
    interfaces = interfaces.prefetch_related("vlan__relay_vlans")
    for interface in interfaces:
        yield interface.vlan
        for relayed_vlan in interface.vlan.relay_vlans.all():
            yield relayed_vlan


def ip_is_on_vlan(ip_address, vlan):
    """Return True if `ip_address` is on `vlan`."""
    return (
        ip_is_sticky_or_auto(ip_address) and
        ip_address.subnet is not None and
        ip_address.subnet.vlan_id == vlan.id and
        ip_address.ip is not None and
        ip_address.ip != "")


def get_ip_address_for_interface(interface, vlan):
    """Return the IP address for `interface` on `vlan`."""
    for ip_address in interface.ip_addresses.all():
        if ip_is_on_vlan(ip_address, vlan):
            return ip_address
    return None


def get_ip_address_for_rack_controller(rack_controller, vlan):
    """Return the IP address for `rack_controller` on `vlan`."""
    # First we build a list of all interfaces that have an IP address
    # on that vlan. Then we pick the best interface for that vlan
    # based on the `get_best_interface` function.
    interfaces = rack_controller.interface_set.all().prefetch_related(
        "ip_addresses__subnet")
    matching_interfaces = set()
    for interface in interfaces:
        for ip_address in interface.ip_addresses.all():
            if ip_is_on_vlan(ip_address, vlan):
                matching_interfaces.add(interface)
    interface = get_best_interface(matching_interfaces)
    return get_ip_address_for_interface(interface, vlan)


@typed
def get_ntp_server_addresses_for_rack(rack: RackController) -> dict:
    """Return a map of rack IP addresses suitable for NTP.

    These are keyed by `(subnet-space-id, subnet-ip-address-family)`, e.g.::

      {(73, 4): "192.168.1.1"}

    Only a single routable address for the rack will be returned in each
    space+family group even if there are multiple.
    """
    rack_addresses = StaticIPAddress.objects.filter(
        interface__enabled=True, interface__node=rack, alloc_type__in={
            IPADDRESS_TYPE.STICKY, IPADDRESS_TYPE.USER_RESERVED})
    rack_addresses = rack_addresses.exclude(subnet__isnull=True)
    rack_addresses = rack_addresses.order_by(
        # Prefer subnets with DHCP enabled.
        "-subnet__vlan__dhcp_on",
        "subnet__vlan__space_id",
        "subnet__cidr",
        "ip"
    )
    rack_addresses = rack_addresses.values_list(
        "subnet__vlan__dhcp_on",
        "subnet__vlan__space_id",
        "subnet__cidr",
        "ip"
    )

    def get_space_id_and_family(record):
        dhcp_on, space_id, cidr, ip = record
        return space_id, IPNetwork(cidr).version

    def sort_key__dhcp_on__ip(record):
        dhcp_on, space_id, cidr, ip = record
        return -int(dhcp_on), IPAddress(ip)

    best_ntp_servers = {
        space_id_and_family:
            min(group, key=sort_key__dhcp_on__ip)
            for space_id_and_family, group in groupby(
                rack_addresses, get_space_id_and_family)
    }
    return {
        key: value[3]
        for key, value in best_ntp_servers.items()
    }


def make_interface_hostname(interface):
    """Return the host decleration name for DHCPD for this `interface`."""
    interface_name = interface.name.replace(".", "-")
    if interface.type == INTERFACE_TYPE.UNKNOWN and interface.node is None:
        return "unknown-%d-%s" % (interface.id, interface_name)
    else:
        return "%s-%s" % (interface.node.hostname, interface_name)


def make_dhcp_snippet(dhcp_snippet):
    """Return the DHCPSnippet as a dictionary."""
    return {
        "name": dhcp_snippet.name,
        "description": dhcp_snippet.description,
        "value": dhcp_snippet.value.data,
    }


def make_hosts_for_subnets(subnets, nodes_dhcp_snippets: list=None):
    """Return list of host entries to create in the DHCP configuration for the
    given `subnets`.
    """
    if nodes_dhcp_snippets is None:
        nodes_dhcp_snippets = []

    def get_dhcp_snippets_for_interface(interface):
        dhcp_snippets = list()
        for dhcp_snippet in nodes_dhcp_snippets:
            if dhcp_snippet.node == interface.node:
                dhcp_snippets.append(make_dhcp_snippet(dhcp_snippet))
        return dhcp_snippets

    sips = StaticIPAddress.objects.filter(
        alloc_type__in=[
            IPADDRESS_TYPE.AUTO,
            IPADDRESS_TYPE.STICKY,
            IPADDRESS_TYPE.USER_RESERVED,
            ],
        subnet__in=subnets, ip__isnull=False).order_by('id')
    hosts = []
    interface_ids = set()
    for sip in sips:
        # Skip blank IP addresses.
        if sip.ip == '':
            continue

        # Add all interfaces attached to this IP address.
        for interface in sip.interface_set.order_by('id'):
            # Only allow an interface to be in hosts once.
            if interface.id in interface_ids:
                continue
            else:
                interface_ids.add(interface.id)

            # Bond interfaces get all its parent interfaces created as
            # hosts as well.
            if interface.type == INTERFACE_TYPE.BOND:
                for parent in interface.parents.all():
                    # Only add parents that MAC address is different from
                    # from the bond.
                    if parent.mac_address != interface.mac_address:
                        interface_ids.add(parent.id)
                        hosts.append({
                            'host': make_interface_hostname(parent),
                            'mac': str(parent.mac_address),
                            'ip': str(sip.ip),
                            'dhcp_snippets': get_dhcp_snippets_for_interface(
                                parent),
                        })
                hosts.append({
                    'host': make_interface_hostname(interface),
                    'mac': str(interface.mac_address),
                    'ip': str(sip.ip),
                    'dhcp_snippets': get_dhcp_snippets_for_interface(
                        interface),
                })
            else:
                hosts.append({
                    'host': make_interface_hostname(interface),
                    'mac': str(interface.mac_address),
                    'ip': str(sip.ip),
                    'dhcp_snippets': get_dhcp_snippets_for_interface(
                        interface),
                })
    return hosts


def make_pools_for_subnet(subnet, failover_peer=None):
    """Return list of pools to create in the DHCP config for `subnet`."""
    pools = []
    for ip_range in subnet.get_dynamic_ranges().order_by('id'):
        pool = {
            "ip_range_low": ip_range.start_ip,
            "ip_range_high": ip_range.end_ip,
        }
        if failover_peer is not None:
            pool["failover_peer"] = failover_peer
        pools.append(pool)
    return pools


@typed
def make_subnet_config(
        rack_controller, subnet, default_dns_servers: Optional[list],
        ntp_servers: Union[list, dict], default_domain, search_list=None,
        failover_peer=None, subnets_dhcp_snippets: list=None, peer_rack=None):
    """Return DHCP subnet configuration dict for a rack interface.

    :param ntp_servers: Either a list of NTP server addresses or hostnames to
        include in DHCP responses, or a dict; if the latter, it ought to match
        the output from `get_ntp_server_addresses_for_rack`.
    """
    ip_network = subnet.get_ipnetwork()
    if subnet.dns_servers is not None and len(subnet.dns_servers) > 0:
        # Replace MAAS DNS with the servers defined on the subnet.
        dns_servers = [IPAddress(server) for server in subnet.dns_servers]
    elif default_dns_servers is not None and len(default_dns_servers) > 0:
        dns_servers = default_dns_servers
    else:
        dns_servers = []
    if subnets_dhcp_snippets is None:
        subnets_dhcp_snippets = []

    subnet_config = {
        'subnet': str(ip_network.network),
        'subnet_mask': str(ip_network.netmask),
        'subnet_cidr': str(ip_network.cidr),
        'broadcast_ip': str(ip_network.broadcast),
        'router_ip': (
            '' if not subnet.gateway_ip
            else str(subnet.gateway_ip)),
        'dns_servers': dns_servers,
        'ntp_servers': get_ntp_servers(ntp_servers, subnet, peer_rack),
        'domain_name': default_domain.name,
        'pools': make_pools_for_subnet(subnet, failover_peer),
        'dhcp_snippets': [
            make_dhcp_snippet(dhcp_snippet)
            for dhcp_snippet in subnets_dhcp_snippets
            if dhcp_snippet.subnet == subnet
            ],
        }
    if search_list is not None:
        subnet_config['search_list'] = search_list
    return subnet_config


def make_failover_peer_config(vlan, rack_controller):
    """Return DHCP failover peer configuration dict for a rack controller."""
    is_primary = vlan.primary_rack_id == rack_controller.id
    interface_ip_address = get_ip_address_for_rack_controller(
        rack_controller, vlan)
    if is_primary:
        peer_rack = vlan.secondary_rack
    else:
        peer_rack = vlan.primary_rack
    peer_address = get_ip_address_for_rack_controller(peer_rack, vlan)
    name = "failover-vlan-%d" % vlan.id
    return (
        name,
        {
            "name": name,
            "mode": "primary" if is_primary else "secondary",
            "address": str(interface_ip_address.ip),
            "peer_address": str(peer_address.ip),
        },
        peer_rack
    )


def get_ntp_servers(ntp_servers, subnet, peer_rack):
    """Return the list of NTP servers, based on the initial input list of
    servers or dictionary, the subnet the servers will be advertised on,
    and the peer rack controller (if present).
    """
    if isinstance(ntp_servers, dict):
        # If ntp_servers is a dict, that means it maps each
        # (space_id, address_family) to the best NTP server for that space.
        # If it's already a list, that means we're just using the external
        # NTP server(s).
        space_address_family = (subnet.vlan.space_id, subnet.get_ip_version())
        ntp_server = ntp_servers.get(space_address_family)
        if ntp_server is None:
            return []
        else:
            if peer_rack is not None:
                alternates = get_ntp_server_addresses_for_rack(peer_rack)
                alternate_ntp_server = alternates.get(space_address_family)
                if alternate_ntp_server is not None:
                    return [ntp_server, alternate_ntp_server]
            return [ntp_server]
    else:
        # Return the original input; it was already a list.
        return ntp_servers


@typed
def get_dhcp_configure_for(
        ip_version: int, rack_controller, vlan, subnets: list,
        ntp_servers: Union[list, dict], domain, search_list=None,
        dhcp_snippets: Iterable=None):
    """Get the DHCP configuration for `ip_version`."""
    try:
        maas_dns_servers = get_dns_server_addresses(
            rack_controller, ipv4=(ip_version == 4), ipv6=(ip_version == 6),
            include_alternates=True)
    except UnresolvableHost:
        maas_dns_servers = None

    # Select the best interface for this VLAN. This is an interface that
    # at least has an IP address.
    interfaces = get_interfaces_with_ip_on_vlan(
        rack_controller, vlan, ip_version)
    interface = get_best_interface(interfaces)

    has_secondary = vlan.secondary_rack_id is not None

    if has_secondary:
        # Generate the failover peer for this VLAN.
        peer_name, peer_config, peer_rack = make_failover_peer_config(
            vlan, rack_controller)
    else:
        peer_name, peer_config, peer_rack = None, None, None

    if dhcp_snippets is None:
        dhcp_snippets = []

    subnets_dhcp_snippets = [
        dhcp_snippet for dhcp_snippet in dhcp_snippets
        if dhcp_snippet.subnet is not None]
    nodes_dhcp_snippets = [
        dhcp_snippet for dhcp_snippet in dhcp_snippets
        if dhcp_snippet.node is not None]

    # Generate the shared network configurations.
    subnet_configs = []
    for subnet in subnets:
        subnet_configs.append(
            make_subnet_config(
                rack_controller, subnet, maas_dns_servers, ntp_servers,
                domain, search_list, peer_name, subnets_dhcp_snippets,
                peer_rack))

    # Generate the hosts for all subnets.
    hosts = make_hosts_for_subnets(subnets, nodes_dhcp_snippets)
    return (
        peer_config, sorted(subnet_configs, key=itemgetter("subnet")),
        hosts, None if interface is None else interface.name)


@synchronous
@transactional
def get_dhcp_configuration(rack_controller, test_dhcp_snippet=None):
    """Return tuple with IPv4 and IPv6 configurations for the
    rack controller."""
    # Get list of all vlans that are being managed by the rack controller.
    vlans = gen_managed_vlans_for(rack_controller)

    # Group the subnets on each VLAN into IPv4 and IPv6 subnets.
    vlan_subnets = {
        vlan: split_managed_ipv4_ipv6_subnets(vlan.subnet_set.all())
        for vlan in vlans
    }

    # Get the list of all DHCP snippets so we only have to query the database
    # 1 + (the number of DHCP snippets used in this VLAN) instead of
    # 1 + (the number of subnets in this VLAN) +
    #     (the number of nodes in this VLAN)
    dhcp_snippets = DHCPSnippet.objects.filter(enabled=True)
    # If we're testing a DHCP Snippet insert it into our list
    if test_dhcp_snippet is not None:
        dhcp_snippets = list(dhcp_snippets)
        replaced_snippet = False
        # If its an existing DHCPSnippet with its contents being modified
        # replace it with the new values and test
        for i, dhcp_snippet in enumerate(dhcp_snippets):
            if dhcp_snippet.id == test_dhcp_snippet.id:
                dhcp_snippets[i] = test_dhcp_snippet
                replaced_snippet = True
                break
        # If the snippet wasn't updated its either new or testing a currently
        # disabled snippet
        if not replaced_snippet:
            dhcp_snippets.append(test_dhcp_snippet)
    global_dhcp_snippets = [
        make_dhcp_snippet(dhcp_snippet)
        for dhcp_snippet in dhcp_snippets
        if dhcp_snippet.node is None and dhcp_snippet.subnet is None
        ]

    # Configure both DHCPv4 and DHCPv6 on the rack controller.
    failover_peers_v4 = []
    shared_networks_v4 = []
    hosts_v4 = []
    interfaces_v4 = set()
    failover_peers_v6 = []
    shared_networks_v6 = []
    hosts_v6 = []
    interfaces_v6 = set()

    # NTP configuration can get tricky...
    ntp_external_only = Config.objects.get_config("ntp_external_only")
    if ntp_external_only:
        ntp_servers = Config.objects.get_config("ntp_servers")
        ntp_servers = list(split_string_list(ntp_servers))
    else:
        ntp_servers = get_ntp_server_addresses_for_rack(rack_controller)

    default_domain = Domain.objects.get_default_domain()
    search_list = [default_domain.name] + [
        name
        for name in sorted(get_dns_search_paths())
        if name != default_domain.name
    ]
    for vlan, (subnets_v4, subnets_v6) in vlan_subnets.items():
        # IPv4
        if len(subnets_v4) > 0:
            config = get_dhcp_configure_for(
                4, rack_controller, vlan, subnets_v4, ntp_servers,
                default_domain, search_list=search_list,
                dhcp_snippets=dhcp_snippets)
            failover_peer, subnets, hosts, interface = config
            if failover_peer is not None:
                failover_peers_v4.append(failover_peer)
            shared_networks_v4.append({
                "name": "vlan-%d" % vlan.id,
                "mtu": vlan.mtu,
                "subnets": subnets,
            })
            hosts_v4.extend(hosts)
            if interface is not None:
                interfaces_v4.add(interface)
        # IPv6
        if len(subnets_v6) > 0:
            config = get_dhcp_configure_for(
                6, rack_controller, vlan, subnets_v6,
                ntp_servers, default_domain, search_list=search_list,
                dhcp_snippets=dhcp_snippets)
            failover_peer, subnets, hosts, interface = config
            if failover_peer is not None:
                failover_peers_v6.append(failover_peer)
            shared_networks_v6.append({
                "name": "vlan-%d" % vlan.id,
                "mtu": vlan.mtu,
                "subnets": subnets,
            })
            hosts_v6.extend(hosts)
            if interface is not None:
                interfaces_v6.add(interface)
    # When no interfaces exist for each IP version clear the shared networks
    # as DHCP server cannot be started and needs to be stopped.
    if len(interfaces_v4) == 0:
        shared_networks_v4 = {}
    if len(interfaces_v6) == 0:
        shared_networks_v6 = {}
    return DHCPConfigurationForRack(
        failover_peers_v4, shared_networks_v4, hosts_v4, interfaces_v4,
        failover_peers_v6, shared_networks_v6, hosts_v6, interfaces_v6,
        get_omapi_key(), global_dhcp_snippets)


DHCPConfigurationForRack = namedtuple("DHCPConfigurationForRack", (
    "failover_peers_v4", "shared_networks_v4", "hosts_v4", "interfaces_v4",
    "failover_peers_v6", "shared_networks_v6", "hosts_v6", "interfaces_v6",
    "omapi_key", "global_dhcp_snippets"))


@asynchronous
@inlineCallbacks
def configure_dhcp(rack_controller):
    """Write the DHCP configuration files and restart the DHCP servers.

    :raises: :py:class:`~.exceptions.NoConnectionsAvailable` when there
        are no open connections to the specified cluster controller.
    """
    # Let's get this out of the way first up shall we?
    if not settings.DHCP_CONNECT:
        # For the uninitiated, DHCP_CONNECT is set, by default, to False
        # in all tests and True in non-tests.  This avoids unnecessary
        # calls to async tasks.
        return

    # Get the client early; it's a cheap operation that may raise an
    # exception, meaning we can avoid some work if it fails.
    client = yield getClientFor(rack_controller.system_id)

    # Get configuration for both IPv4 and IPv6.
    config = yield deferToDatabase(get_dhcp_configuration, rack_controller)

    # Fix interfaces to go over the wire.
    interfaces_v4 = [
        {"name": name}
        for name in config.interfaces_v4
    ]
    interfaces_v6 = [
        {"name": name}
        for name in config.interfaces_v6
    ]

    # Configure both IPv4 and IPv6.
    ipv4_exc, ipv6_exc = None, None
    ipv4_status, ipv6_status = SERVICE_STATUS.UNKNOWN, SERVICE_STATUS.UNKNOWN

    try:
        yield _perform_dhcp_config(
            client, ConfigureDHCPv4_V2, ConfigureDHCPv4,
            failover_peers=config.failover_peers_v4, interfaces=interfaces_v4,
            shared_networks=config.shared_networks_v4, hosts=config.hosts_v4,
            global_dhcp_snippets=config.global_dhcp_snippets,
            omapi_key=config.omapi_key)
    except Exception as exc:
        ipv4_exc = exc
        ipv4_status = SERVICE_STATUS.DEAD
        log.err(
            "Error configuring DHCPv4 on rack controller '%s': %s" % (
                rack_controller.system_id, exc))
    else:
        if len(config.shared_networks_v4) > 0:
            ipv4_status = SERVICE_STATUS.RUNNING
        else:
            ipv4_status = SERVICE_STATUS.OFF
        log.msg(
            "Successfully configured DHCPv4 on rack controller '%s'." % (
                rack_controller.system_id))

    try:
        yield _perform_dhcp_config(
            client, ConfigureDHCPv6_V2, ConfigureDHCPv6,
            failover_peers=config.failover_peers_v6, interfaces=interfaces_v6,
            shared_networks=config.shared_networks_v6, hosts=config.hosts_v6,
            global_dhcp_snippets=config.global_dhcp_snippets,
            omapi_key=config.omapi_key)
    except Exception as exc:
        ipv6_exc = exc
        ipv6_status = SERVICE_STATUS.DEAD
        log.err(
            "Error configuring DHCPv6 on rack controller '%s': %s" % (
                rack_controller.system_id, exc))
    else:
        if len(config.shared_networks_v6) > 0:
            ipv6_status = SERVICE_STATUS.RUNNING
        else:
            ipv6_status = SERVICE_STATUS.OFF
        log.msg(
            "Successfully configured DHCPv6 on rack controller '%s'." % (
                rack_controller.system_id))

    # Update the status for both services so the user is always seeing the
    # most up to date status.
    @transactional
    def update_services():
        if ipv4_exc is None:
            ipv4_status_info = ""
        else:
            ipv4_status_info = str(ipv4_exc)
        if ipv6_exc is None:
            ipv6_status_info = ""
        else:
            ipv6_status_info = str(ipv6_exc)
        Service.objects.update_service_for(
            rack_controller, "dhcpd", ipv4_status, ipv4_status_info)
        Service.objects.update_service_for(
            rack_controller, "dhcpd6", ipv6_status, ipv6_status_info)
    yield deferToDatabase(update_services)


def validate_dhcp_config(test_dhcp_snippet=None):
    """Validate a DHCPD config with uncommitted values.

    Gathers the DHCPD config from what is committed in the database, as well as
    DHCPD config which needs to be validated, and asks a rack controller to
    validate. Testing is done with dhcpd's builtin validation flag.

    :param test_dhcp_snippet: A DHCPSnippet which has not yet been committed to
        the database and needs to be validated.
    """
    # XXX ltrager 2016-03-28 - This only tests the existing config with new
    # DHCPSnippets but could be expanded to test changes to the config(e.g
    # subnets, omapi_key, interfaces, etc) before they are commited.

    def find_connected_rack(racks):
        connected_racks = [client.ident for client in getAllClients()]
        for rack in racks:
            if rack.system_id in connected_racks:
                return rack
        # The dhcpd.conf config rendered on a rack controller only contains
        # subnets and interfaces which can connect to that rack controller.
        # If no rack controller was found picking a random rack controller
        # which is connected will result in testing a config which does
        # not contain the values we are trying to test.
        raise ValidationError(
            'Unable to validate DHCP config, '
            'no available rack controller connected.')

    rack_controller = None
    # Test on the rack controller where the DHCPSnippet will be used
    if test_dhcp_snippet is not None:
        if test_dhcp_snippet.subnet is not None:
            rack_controller = find_connected_rack(
                RackController.objects.filter_by_subnets(
                    [test_dhcp_snippet.subnet])
            )
        elif test_dhcp_snippet.node is not None:
            rack_controller = find_connected_rack(
                test_dhcp_snippet.node.get_boot_rack_controllers()
            )
    # If no rack controller is linked to the DHCPSnippet its a global DHCP
    # snippet which we can test anywhere.
    if rack_controller is None:
        try:
            client = getRandomClient()
        except NoConnectionsAvailable:
            raise ValidationError(
                'Unable to validate DHCP config, '
                'no available rack controller connected.')
        rack_controller = RackController.objects.get(system_id=client.ident)
    else:
        try:
            client = getClientFor(rack_controller.system_id)
        except NoConnectionsAvailable:
            raise ValidationError(
                'Unable to validate DHCP config, '
                'no available rack controller connected.')
        rack_controller = RackController.objects.get(system_id=client.ident)

    # Get configuration for both IPv4 and IPv6.
    config = get_dhcp_configuration(rack_controller, test_dhcp_snippet)

    # Fix interfaces to go over the wire.
    interfaces_v4 = [
        {"name": name}
        for name in config.interfaces_v4
    ]
    interfaces_v6 = [
        {"name": name}
        for name in config.interfaces_v6
    ]

    # Validate both IPv4 and IPv6.
    v4_args = dict(
        omapi_key=config.omapi_key, failover_peers=config.failover_peers_v4,
        hosts=config.hosts_v4, interfaces=interfaces_v4,
        global_dhcp_snippets=config.global_dhcp_snippets,
        shared_networks=config.shared_networks_v4)
    v6_args = dict(
        omapi_key=config.omapi_key, failover_peers=config.failover_peers_v6,
        hosts=config.hosts_v6, interfaces=interfaces_v6,
        global_dhcp_snippets=config.global_dhcp_snippets,
        shared_networks=config.shared_networks_v6)

    # XXX: These remote calls can hold transactions open for a prolonged
    # period. This is bad for concurrency and scaling.
    v4_response = _validate_dhcp_config_v4(client, **v4_args).wait(30)
    v6_response = _validate_dhcp_config_v6(client, **v6_args).wait(30)

    # Deduplicate errors between IPv4 and IPv6
    known_errors = []
    unique_errors = []
    for errors in (v4_response['errors'], v6_response['errors']):
        if errors is None:
            continue
        for error in errors:
            hash = "%s - %s" % (error['line'], error['error'])
            if hash not in known_errors:
                known_errors.append(hash)
                unique_errors.append(error)
    return unique_errors


def _validate_dhcp_config_v4(client, **args):
    """See `_validate_dhcp_config_vx`."""
    return _perform_dhcp_config(
        client, ValidateDHCPv4Config_V2, ValidateDHCPv4Config, **args)


def _validate_dhcp_config_v6(client, **args):
    """See `_validate_dhcp_config_vx`."""
    return _perform_dhcp_config(
        client, ValidateDHCPv6Config_V2, ValidateDHCPv6Config, **args)


@asynchronous
def _perform_dhcp_config(
        client, v2_command, v1_command, *, shared_networks, **args):
    """Call `v2_command` then `v1_command`...

    ... if the former is not recognised. This allows interoperability between
    a region that's newer than the rack controller.

    :param client: An RPC client.
    :param v2_command: The RPC command to attempt first.
    :param v1_command: The RPC command to attempt second.
    :param shared_networks: The shared networks argument for `v2_command` and
        `v1_command`. If `v2_command` is not handled by the remote side, this
        structure will be downgraded in place.
    :param args: Remaining arguments for `v2_command` and `v1_command`.
    """
    def call(command):
        return client(command, shared_networks=shared_networks, **args)

    def maybeDowngrade(failure):
        if failure.check(amp.UnhandledCommand):
            downgrade_shared_networks(shared_networks)
            return call(v1_command)
        else:
            return failure

    return call(v2_command).addErrback(maybeDowngrade)