def test_prefers_static_ip_over_dhcp(self): rack = factory.make_RackController() factory.make_RegionRackRPCConnection(rack) nic = rack.get_boot_interface() network = factory.make_ipv4_network() subnet = factory.make_Subnet(cidr=str(network.cidr)) static_ip = factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.AUTO, ip=factory.pick_ip_in_Subnet(subnet), subnet=subnet, interface=nic, ) factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.DHCP, ip=factory.pick_ip_in_Subnet(subnet), subnet=subnet, interface=nic, ) domain = get_internal_domain() self.assertThat(domain.resources, HasLength(1)) self.assertEqual(get_resource_name_for_subnet(subnet), domain.resources[0].name) self.assertEqual( InternalDomainResourseRecord(rrtype="A", rrdata=static_ip.ip), domain.resources[0].records[0], )
def test_adds_connected_multiple_racks_ipv6(self): rack1 = factory.make_RackController() factory.make_RegionRackRPCConnection(rack1) rack2 = factory.make_RackController() factory.make_RegionRackRPCConnection(rack2) network = factory.make_ipv6_network() subnet = factory.make_Subnet(cidr=str(network.cidr)) static_ip1 = factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.AUTO, ip=factory.pick_ip_in_Subnet(subnet), subnet=subnet, interface=rack1.get_boot_interface(), ) static_ip2 = factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.AUTO, ip=factory.pick_ip_in_Subnet(subnet), subnet=subnet, interface=rack2.get_boot_interface(), ) domain = get_internal_domain() self.assertEqual(get_resource_name_for_subnet(subnet), domain.resources[0].name) self.assertThat( domain.resources[0].records, MatchesSetwise( Equals( InternalDomainResourseRecord(rrtype="AAAA", rrdata=static_ip1.ip)), Equals( InternalDomainResourseRecord(rrtype="AAAA", rrdata=static_ip2.ip)), ), )
def test_create_creates_device_with_static_ip_assignment_explicit(self): user = factory.make_User() request = HttpRequest() request.user = user handler = DeviceHandler(user, {}, request) mac = factory.make_mac_address() hostname = factory.make_name("hostname") subnet = factory.make_Subnet() ip_address = factory.pick_ip_in_Subnet(subnet) created_device = handler.create({ "hostname": hostname, "primary_mac": mac, "interfaces": [{ "mac": mac, "ip_assignment": DEVICE_IP_ASSIGNMENT_TYPE.STATIC, "subnet": subnet.id, "ip_address": ip_address, }], }) self.expectThat(created_device["ip_assignment"], Equals(DEVICE_IP_ASSIGNMENT_TYPE.STATIC)) self.expectThat(created_device["ip_address"], Equals(ip_address)) static_interface = Interface.objects.get(mac_address=MAC(mac)) observed_subnet = static_interface.ip_addresses.first().subnet self.expectThat(observed_subnet, Equals(subnet), "Static assignment to the subnet was not created.") self.expectThat( StaticIPAddress.objects.filter(ip=ip_address).count(), Equals(1), "StaticIPAddress was not created.")
def test_yields_internal_forward_zones(self): default_domain = Domain.objects.get_default_domain() subnet = factory.make_Subnet(cidr=str(IPNetwork("10/29").cidr)) domains = [] for _ in range(3): record = InternalDomainResourseRecord( rrtype='A', rrdata=factory.pick_ip_in_Subnet(subnet)) resource = InternalDomainResourse( name=factory.make_name('resource'), records=[record]) domain = InternalDomain(name=factory.make_name('domain'), ttl=random.randint(15, 300), resources=[resource]) domains.append(domain) zones = ZoneGenerator([], [subnet], serial=random.randint(0, 65535), internal_domains=domains).as_list() self.assertThat( zones, MatchesSetwise(*[ MatchesAll( forward_zone(domain.name), MatchesStructure(_other_mapping=MatchesDict({ domain.resources[0].name: MatchesStructure(rrset=MatchesSetwise( Equals((domain.ttl, domain.resources[0].records[0].rrtype, domain.resources[0].records[0].rrdata)))) }))) for domain in domains ] + [ reverse_zone(default_domain.name, "10/29"), reverse_zone(default_domain.name, "10/24") ]))
def test_logs_migration(self): logger = self.useFixture(FakeLogger("maas")) rack = factory.make_RackController() vlan = factory.make_VLAN() subnet = factory.make_Subnet(vlan=vlan) ip = factory.pick_ip_in_Subnet(subnet) interfaces = { factory.make_name("eth0"): { "type": "physical", "mac_address": factory.make_mac_address(), "parents": [], "links": [{ "mode": "static", "address": "%s/%d" % (str(ip), subnet.get_ipnetwork().prefixlen), }], "enabled": True, } } rack.update_interfaces(interfaces) ng_uuid = factory.make_UUID() NodeGroupToRackController.objects.create(uuid=ng_uuid, subnet=subnet) handle_upgrade(rack, ng_uuid) vlan = reload_object(vlan) self.assertEqual( "DHCP setting from NodeGroup(%s) have been migrated to %s." % (ng_uuid, vlan), logger.output.strip(), )
def test_get_hostname_ip_mapping_containts_both_static_and_dynamic(self): node1 = factory.make_Node(interface=True) node1_interface = node1.get_boot_interface() subnet = factory.make_Subnet() static_ip = factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.AUTO, ip=factory.pick_ip_in_Subnet(subnet), subnet=subnet, interface=node1_interface, ) node2 = factory.make_Node(interface=True) node2_interface = node2.get_boot_interface() subnet = factory.make_ipv4_Subnet_with_IPRanges() dynamic_ip = factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.DISCOVERED, ip=factory.pick_ip_in_IPRange(subnet.get_dynamic_ranges()[0]), subnet=subnet, interface=node2_interface, ) ttl = random.randint(10, 300) Config.objects.set_config("default_dns_ttl", ttl) expected_mapping = { "%s.maas" % node1.hostname: HostnameIPMapping( node1.system_id, ttl, {static_ip.ip}, node1.node_type ), "%s.maas" % node2.hostname: HostnameIPMapping( node2.system_id, ttl, {dynamic_ip.ip}, node2.node_type ), } actual = get_hostname_ip_mapping(Domain.objects.get_default_domain()) self.assertItemsEqual(expected_mapping.items(), actual.items())
def test_returns_None_when_subnet_is_not_managed(self): subnet = factory.make_Subnet() self.assertIsNone( find_rack_controller( make_request(factory.pick_ip_in_Subnet(subnet)) ) )
def test__returns_correct_url(self): import maasserver.compose_preseed as cp_module # Disable boot source cache signals. self.addCleanup(bootsources.signals.enable) bootsources.signals.disable() # Force the server host to be our test data. self.patch(cp_module, 'get_maas_facing_server_host').return_value = ( self.rack if self.rack else self.default_region_ip) # Now setup the configuration and arguments, and see what we get back. node = factory.make_Node(interface=True, status=NODE_STATUS.COMMISSIONING) Config.objects.set_config("enable_http_proxy", self.enable) Config.objects.set_config("http_proxy", self.http_proxy) Config.objects.set_config("use_peer_proxy", self.use_peer_proxy) Config.objects.set_config("use_rack_proxy", self.use_rack_proxy) if self.maas_proxy_port: Config.objects.set_config("maas_proxy_port", self.maas_proxy_port) request = make_HttpRequest(http_host=self.default_region_ip) if self.use_rack_proxy: subnet = None if self.cidr: subnet = factory.make_Subnet(cidr=self.cidr) if self.subnet_dns: subnet.dns_servers = [self.subnet_dns] else: subnet.dns_servers = [] subnet.save() request.META['REMOTE_ADDR'] = factory.pick_ip_in_Subnet(subnet) else: request.META['REMOTE_ADDR'] = factory.make_ipv4_address() actual = get_apt_proxy(request, node.get_boot_rack_controller()) self.assertEqual(self.result, actual)
def make_device_with_ip_address( self, ip_assignment=None, owner=None): """The `DEVICE_IP_ASSIGNMENT` is based on what data exists in the model for a device. This will setup the model to make sure the device will match `ip_assignment`.""" if ip_assignment is None: ip_assignment = factory.pick_enum(DEVICE_IP_ASSIGNMENT_TYPE) if owner is None: owner = factory.make_User() device = factory.make_Node( node_type=NODE_TYPE.DEVICE, interface=True, owner=owner) interface = device.get_boot_interface() if ip_assignment == DEVICE_IP_ASSIGNMENT_TYPE.EXTERNAL: subnet = factory.make_Subnet() factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.USER_RESERVED, ip=factory.pick_ip_in_network(subnet.get_ipnetwork()), subnet=subnet, user=owner) elif ip_assignment == DEVICE_IP_ASSIGNMENT_TYPE.DYNAMIC: factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.DHCP, ip="", interface=interface) else: subnet = factory.make_Subnet(vlan=interface.vlan) factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.STICKY, ip=factory.pick_ip_in_Subnet(subnet), interface=interface, subnet=subnet) return device
def test_migrates_nodegroup_subnet(self): rack = factory.make_RackController() vlan = factory.make_VLAN() subnet = factory.make_Subnet(vlan=vlan) ip = factory.pick_ip_in_Subnet(subnet) interfaces = { factory.make_name("eth0"): { "type": "physical", "mac_address": factory.make_mac_address(), "parents": [], "links": [{ "mode": "static", "address": "%s/%d" % (str(ip), subnet.get_ipnetwork().prefixlen), }], "enabled": True, } } rack.update_interfaces(interfaces) ng_uuid = factory.make_UUID() NodeGroupToRackController.objects.create(uuid=ng_uuid, subnet=subnet) handle_upgrade(rack, ng_uuid) vlan = reload_object(vlan) self.assertEqual(rack.system_id, vlan.primary_rack.system_id) self.assertTrue(vlan.dhcp_on) self.assertItemsEqual([], NodeGroupToRackController.objects.all())
def assign_ip(cls, interface, alloc_type=None): """Assign an IP address to the interface.""" subnets = list(interface.vlan.subnet_set.all()) if len(subnets) > 0: subnet = random.choice(subnets) if alloc_type is None: alloc_type = random.choice( [IPADDRESS_TYPE.STICKY, IPADDRESS_TYPE.AUTO]) if (alloc_type == IPADDRESS_TYPE.AUTO and interface.node.status not in [ NODE_STATUS.DEPLOYING, NODE_STATUS.DEPLOYED, NODE_STATUS.FAILED_DEPLOYMENT, NODE_STATUS.RELEASING, ]): assign_ip = "" else: # IPv6 use pick_ip_in_network as pick_ip_in_Subnet takes # forever with the IPv6 network. network = subnet.get_ipnetwork() if network.version == 6: assign_ip = factory.pick_ip_in_network(network) else: assign_ip = factory.pick_ip_in_Subnet(subnet) factory.make_StaticIPAddress( alloc_type=alloc_type, subnet=subnet, ip=assign_ip, interface=interface, )
def test_linking_when_no_bond_not_allowed(self): node = factory.make_Node() eth0 = factory.make_Interface(INTERFACE_TYPE.PHYSICAL, node=node) eth1 = factory.make_Interface(INTERFACE_TYPE.PHYSICAL, node=node) bond0 = factory.make_Interface( INTERFACE_TYPE.BOND, parents=[eth0, eth1], node=node ) subnet = factory.make_Subnet(vlan=eth0.vlan) ip_in_static = factory.pick_ip_in_Subnet(subnet) form = InterfaceLinkForm( instance=eth0, data={ "mode": INTERFACE_LINK_TYPE.STATIC, "subnet": subnet.id, "ip_address": "%s" % ip_in_static, }, ) self.assertFalse(form.is_valid()) self.assertEqual( { "bond": [ ( "Cannot link interface(%s) when interface is in a " "bond(%s)." % (eth0.name, bond0.name) ) ] }, form.errors, )
def test__returns_at_most_60kiB_of_JSON(self): # Configure the rack controller subnet to be very large so it # can hold that many BMC connected to the interface for the rack # controller. rack = factory.make_RackController(power_type='') rack_interface = rack.get_boot_interface() subnet = factory.make_Subnet( cidr=str(factory.make_ipv6_network(slash=8))) factory.make_StaticIPAddress(ip=factory.pick_ip_in_Subnet(subnet), subnet=subnet, interface=rack_interface) # Ensure that there are at least 64kiB of power parameters (when # converted to JSON) in the database. example_parameters = {"key%d" % i: "value%d" % i for i in range(250)} remaining = 2**16 while remaining > 0: node = self.make_Node(bmc_connected_to=rack, power_parameters=example_parameters) remaining -= len(json.dumps(node.get_effective_power_parameters())) nodes = list_cluster_nodes_power_parameters( rack.system_id, limit=None) # Remove numeric limit. # The total size of the JSON is less than 60kiB, but only a bit. nodes_json = map(json.dumps, nodes) nodes_json_lengths = map(len, nodes_json) nodes_json_length = sum(nodes_json_lengths) expected_maximum = 60 * (2**10) # 60kiB self.expectThat(nodes_json_length, LessThan(expected_maximum + 1)) expected_minimum = 50 * (2**10) # 50kiB self.expectThat(nodes_json_length, GreaterThan(expected_minimum - 1))
def test_create_interface_creates_static_ip_assignment_explicit(self): user = factory.make_User() handler = DeviceHandler(user, {}) device = factory.make_Device(owner=user) mac = factory.make_mac_address() subnet = factory.make_Subnet() ip_address = factory.pick_ip_in_Subnet(subnet) updated_device = handler.create_interface({ "system_id": device.system_id, "mac_address": mac, "ip_assignment": DEVICE_IP_ASSIGNMENT_TYPE.STATIC, "subnet": subnet.id, "ip_address": ip_address, }) self.expectThat(updated_device["primary_mac"], Equals(mac)) self.expectThat( updated_device["ip_assignment"], Equals(DEVICE_IP_ASSIGNMENT_TYPE.STATIC)) self.expectThat(updated_device["ip_address"], Equals(ip_address)) static_interface = Interface.objects.get(mac_address=MAC(mac)) observed_subnet = static_interface.ip_addresses.first().subnet self.expectThat( observed_subnet, Equals(subnet), "Static assignment to the subnet was not created.") self.expectThat( StaticIPAddress.objects.filter(ip=ip_address).count(), Equals(1), "StaticIPAddress was not created.")
def test_POST_reserve_with_fqdn_and_ip_creates_ip_with_hostname(self): subnet = factory.make_Subnet() hostname = factory.make_hostname() domainname = factory.make_Domain().name fqdn = "%s.%s" % (hostname, domainname) ip_in_network = factory.pick_ip_in_Subnet(subnet) response = self.post_reservation_request( subnet=subnet, ip_address=ip_in_network, hostname="%s.%s" % (hostname, domainname), ) self.assertEqual( http.client.OK, response.status_code, response.content ) returned_address = json_load_bytes(response.content) [staticipaddress] = StaticIPAddress.objects.all() self.expectThat( returned_address["alloc_type"], Equals(IPADDRESS_TYPE.USER_RESERVED), ) self.expectThat(returned_address["ip"], Equals(ip_in_network)) self.expectThat(staticipaddress.ip, Equals(ip_in_network)) self.expectThat( staticipaddress.dnsresource_set.first().fqdn, Equals(fqdn) )
def make_discovery(): """Make a discovery in its own transaction so each last_seen time is different.""" random_rack = random.choice(RackController.objects.all()) random_interface = random.choice(random_rack.interface_set.all()) random_subnet = random.choice(random_interface.vlan.subnet_set.all()) factory.make_Discovery(interface=random_interface, ip=factory.pick_ip_in_Subnet(random_subnet))
def test_create_creates_device_with_static_and_external_ip(self): user = factory.make_User() request = HttpRequest() request.user = user handler = DeviceHandler(user, {}, request) hostname = factory.make_name("hostname") subnet = factory.make_Subnet() mac_static = factory.make_mac_address() static_ip_address = factory.pick_ip_in_Subnet(subnet) mac_external = factory.make_mac_address() external_ip_address = factory.make_ipv4_address() created_device = handler.create( { "hostname": hostname, "primary_mac": mac_static, "extra_macs": [mac_external], "interfaces": [ { "mac": mac_static, "ip_assignment": DEVICE_IP_ASSIGNMENT_TYPE.STATIC, "subnet": subnet.id, "ip_address": static_ip_address, }, { "mac": mac_external, "ip_assignment": DEVICE_IP_ASSIGNMENT_TYPE.EXTERNAL, "ip_address": external_ip_address, }, ], } ) self.expectThat(created_device["primary_mac"], Equals(mac_static)) self.expectThat(created_device["extra_macs"], Equals([mac_external])) self.expectThat( created_device["ip_assignment"], Equals(DEVICE_IP_ASSIGNMENT_TYPE.STATIC), ) self.expectThat( created_device["ip_address"], Equals(static_ip_address) ) static_interface = Interface.objects.get(mac_address=MAC(mac_static)) observed_subnet = static_interface.ip_addresses.first().subnet self.expectThat( observed_subnet, Equals(subnet), "Static assignment to the subnet was not created.", ) self.expectThat( StaticIPAddress.objects.filter(ip=static_ip_address).count(), Equals(1), "Static StaticIPAddress was not created.", ) self.expectThat( StaticIPAddress.objects.filter(ip=external_ip_address).count(), Equals(1), "External StaticIPAddress was not created.", )
def test_returns_primary_rack_when_subnet_is_managed(self): subnet = factory.make_Subnet() rack_controller = factory.make_RackController() subnet.vlan.dhcp_on = True subnet.vlan.primary_rack = rack_controller subnet.vlan.save() self.assertEquals( rack_controller.system_id, find_rack_controller( make_request(factory.pick_ip_in_Subnet(subnet))).system_id)
def test_source_cannot_be_destination(self): subnet = factory.make_Subnet() gateway_ip = factory.pick_ip_in_Subnet(subnet) error = self.assertRaises( ValidationError, factory.make_StaticRoute, source=subnet, destination=subnet, gateway_ip=gateway_ip) self.assertEqual( str( {'__all__': [ "source and destination cannot be the same subnet."]}), str(error))
def create_rack_with_static_ip(self, subnet=None): if subnet is None: network = factory.make_ipv4_network() subnet = factory.make_Subnet(cidr=str(network.cidr)) rack = factory.make_RackController(interface=True) nic = rack.get_boot_interface() static_ip = factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.AUTO, ip=factory.pick_ip_in_Subnet(subnet), subnet=subnet, interface=nic) return rack, static_ip
def test_gateway_ip_must_be_in_source(self): source = factory.make_Subnet(version=4) dest = factory.make_Subnet(version=4) gateway_ip = factory.pick_ip_in_Subnet(dest) error = self.assertRaises( ValidationError, factory.make_StaticRoute, source=source, destination=dest, gateway_ip=gateway_ip) self.assertEqual( str( {'__all__': [ "gateway_ip must be with in the source subnet."]}), str(error))
def test__has_enlistment_preseed_url_with_local_ip_subnet_with_dns(self): rack_controller = factory.make_RackController() subnet = factory.make_Subnet() local_ip = factory.pick_ip_in_Subnet(subnet) remote_ip = factory.make_ip_address() factory.make_default_ubuntu_release_bootable() observed_config = get_config( rack_controller.system_id, local_ip, remote_ip) self.assertEqual( compose_enlistment_preseed_url( base_url='http://%s:5248/' % local_ip), observed_config["preseed_url"])
def test_source_must_be_same_version_of_destination(self): source = factory.make_Subnet(version=4) dest = factory.make_Subnet(version=6) gateway_ip = factory.pick_ip_in_Subnet(source) error = self.assertRaises( ValidationError, factory.make_StaticRoute, source=source, destination=dest, gateway_ip=gateway_ip) self.assertEqual( str( {'__all__': [ "source and destination must be the same IP version."]}), str(error))
def test__sets_boot_interface_when_given_hardware_uuid(self): node = self.make_node() nic = node.get_boot_interface() node.boot_interface = None node.save() rack_controller = nic.vlan.primary_rack subnet = nic.vlan.subnet_set.first() local_ip = factory.pick_ip_in_Subnet(subnet) get_config( rack_controller.system_id, local_ip, factory.make_ip_address(), hardware_uuid=node.hardware_uuid, query_count=24) self.assertEqual(nic, reload_object(node).boot_interface)
def make_discovery(racks=None): """Make a discovery in its own transaction so each last_seen time is different. """ if racks is None: racks = _prefetch_racks() rack = random.choice(racks) interface = random.choice(rack.interface_set.all()) subnet = random.choice(interface.vlan.subnet_set.all()) factory.make_Discovery(interface=interface, ip=factory.pick_ip_in_Subnet(subnet))
def test_POST_reserve_creates_ip_address(self): subnet = factory.make_Subnet() ip_in_network = factory.pick_ip_in_Subnet(subnet) response = self.post_reservation_request(ip_address=ip_in_network) self.assertEqual(http.client.OK, response.status_code, response.content) returned_address = json_load_bytes(response.content) [staticipaddress] = StaticIPAddress.objects.all() self.expectThat(returned_address["alloc_type"], Equals(IPADDRESS_TYPE.USER_RESERVED)) self.expectThat(returned_address["ip"], Equals(ip_in_network)) self.expectThat(staticipaddress.ip, Equals(ip_in_network))
def test__doesnt_add_disconnected_rack(self): rack = factory.make_RackController() # No `RegionRackRPCConnection` is being created so the rack is # disconnected. nic = rack.get_boot_interface() network = factory.make_ipv4_network() subnet = factory.make_Subnet(cidr=str(network.cidr)) factory.make_StaticIPAddress( alloc_type=IPADDRESS_TYPE.AUTO, ip=factory.pick_ip_in_Subnet(subnet), subnet=subnet, interface=nic) domain = get_internal_domain() self.assertEqual(0, len(domain.resources))
def test_POST_reserve_ip_address_detects_in_use_address(self): subnet = factory.make_Subnet() ip_in_network = factory.pick_ip_in_Subnet(subnet) response = self.post_reservation_request(subnet, ip_in_network) self.assertEqual(http.client.OK, response.status_code, response.content) # Do same request again and check it is rejected. response = self.post_reservation_request(subnet, ip_in_network) self.expectThat(response.status_code, Equals(http.client.NOT_FOUND)) self.expectThat( response.content, Equals(("The IP address %s is already in use." % ip_in_network).encode(settings.DEFAULT_CHARSET)))
def test_create_admin_only(self): source = factory.make_Subnet() destination = factory.make_Subnet( version=source.get_ipnetwork().version) gateway_ip = factory.pick_ip_in_Subnet(source) uri = get_staticroutes_uri() response = self.client.post( uri, { "source": source.id, "destination": destination.id, "gateway_ip": gateway_ip, }) self.assertEqual(http.client.FORBIDDEN, response.status_code, response.content)
def test_preseed_url_for_known_node_local_ip_subnet_with_dns(self): rack_url = 'http://%s' % factory.make_name('host') subnet = factory.make_Subnet() local_ip = factory.pick_ip_in_Subnet(subnet) remote_ip = factory.make_ip_address() self.patch( server_address, 'resolve_hostname').return_value = {local_ip} rack_controller = factory.make_RackController(url=rack_url) node = self.make_node(primary_rack=rack_controller) mac = node.get_boot_interface().mac_address observed_config = get_config( rack_controller.system_id, local_ip, remote_ip, mac=mac) self.assertThat( observed_config["preseed_url"], StartsWith('http://%s:5248' % local_ip))