Example #1
0
 def test_updates_fabric(self):
     new_name = factory.make_name("fabric")
     new_fabric_description = factory.make_name("description")
     new_class_type = factory.make_name("class_type")
     fabric = factory.make_Fabric()
     form = FabricForm(
         instance=fabric,
         data={
             "name": new_name,
             "description": new_fabric_description,
             "class_type": new_class_type,
         },
     )
     self.assertTrue(form.is_valid(), form.errors)
     form.save()
     self.assertEqual(new_name, reload_object(fabric).name)
     self.assertEqual(
         new_fabric_description, reload_object(fabric).description
     )
     self.assertEqual(new_class_type, reload_object(fabric).class_type)
Example #2
0
    def test_read_with_fabric(self):
        fabric = factory.make_Fabric()
        vlan = factory.make_VLAN(fabric=fabric)
        uri = get_vlan_uri(vlan, fabric)
        response = self.client.get(uri)

        self.assertEqual(http.client.OK, response.status_code,
                         response.content)
        parsed_vlan = json.loads(
            response.content.decode(settings.DEFAULT_CHARSET))
        self.assertThat(
            parsed_vlan,
            ContainsDict({
                "id": Equals(vlan.id),
                "name": Equals(vlan.get_name()),
                "vid": Equals(vlan.vid),
                "fabric": Equals(fabric.get_name()),
                "resource_uri": Equals(get_vlan_uri(vlan)),
            }),
        )
Example #3
0
 def test_create_without_space(self):
     self.become_admin()
     fabric = factory.make_Fabric()
     vlan_name = factory.make_name("fabric")
     vid = random.randint(1, 1000)
     mtu = random.randint(552, 1500)
     uri = get_vlans_uri(fabric)
     response = self.client.post(uri, {
         "name": vlan_name,
         "vid": vid,
         "mtu": mtu,
     })
     self.assertEqual(http.client.OK, response.status_code,
                      response.content)
     response_data = json.loads(
         response.content.decode(settings.DEFAULT_CHARSET))
     self.assertEqual(vlan_name, response_data['name'])
     self.assertEqual(vid, response_data['vid'])
     self.assertEqual(mtu, response_data['mtu'])
     self.assertEqual(Space.UNDEFINED, response_data['space'])
Example #4
0
 def test_cannot_move_vlan_with_overlapping_vid(self):
     fabric0 = Fabric.objects.get_default_fabric()
     fabric1 = factory.make_Fabric()
     fabric1_untagged = fabric1.get_default_vlan()
     form = VLANForm(instance=fabric1_untagged, data={"fabric": fabric0.id})
     is_valid = form.is_valid()
     self.assertThat(is_valid, Equals(False))
     self.assertThat(
         dict(form.errors),
         Equals(
             {
                 "__all__": [
                     "A VLAN with the specified VID already "
                     "exists in the destination fabric."
                 ]
             }
         ),
     )
     with ExpectedException(ValueError):
         form.save()
Example #5
0
 def test__changes_boot_interface_vlan_not_relayed_through_rack(self):
     rack_controller = factory.make_RackController()
     rack_fabric = factory.make_Fabric()
     rack_vlan = rack_fabric.get_default_vlan()
     rack_interface = factory.make_Interface(INTERFACE_TYPE.PHYSICAL,
                                             node=rack_controller,
                                             vlan=rack_vlan)
     rack_subnet = factory.make_Subnet(vlan=rack_vlan)
     rack_ip = factory.make_StaticIPAddress(
         alloc_type=IPADDRESS_TYPE.STICKY,
         subnet=rack_subnet,
         interface=rack_interface)
     other_vlan = factory.make_VLAN()
     relay_vlan = factory.make_VLAN(relay_vlan=other_vlan)
     remote_ip = factory.make_ip_address()
     node = self.make_node(vlan=relay_vlan)
     mac = node.get_boot_interface().mac_address
     get_config(rack_controller.system_id, rack_ip.ip, remote_ip, mac=mac)
     self.assertEqual(rack_vlan,
                      reload_object(node).get_boot_interface().vlan)
Example #6
0
 def test__creates_vlan(self):
     fabric = factory.make_Fabric()
     vlan_name = factory.make_name("vlan")
     vlan_description = factory.make_name("description")
     vid = random.randint(1, 1000)
     mtu = random.randint(552, 4096)
     form = VLANForm(fabric=fabric,
                     data={
                         "name": vlan_name,
                         "description": vlan_description,
                         "vid": vid,
                         "mtu": mtu,
                     })
     self.assertTrue(form.is_valid(), form.errors)
     vlan = form.save()
     self.assertEqual(vlan_name, vlan.name)
     self.assertEqual(vlan_description, vlan.description)
     self.assertEqual(vid, vlan.vid)
     self.assertEqual(fabric, vlan.fabric)
     self.assertEqual(mtu, vlan.mtu)
Example #7
0
    def test_read(self):
        class_type = factory.make_name("class")
        fabric = factory.make_Fabric(class_type=class_type)
        for vid in range(1, 4):
            factory.make_VLAN(fabric=fabric, vid=vid).id
        uri = get_fabric_uri(fabric)
        response = self.client.get(uri)

        self.assertEqual(http.client.OK, response.status_code,
                         response.content)
        parsed_fabric = json_load_bytes(response.content)
        self.assertThat(
            parsed_fabric,
            ContainsDict({
                "id": Equals(fabric.id),
                "name": Equals(fabric.get_name()),
                "class_type": Equals(class_type),
            }))
        self.assertItemsEqual([vlan.id for vlan in fabric.vlan_set.all()],
                              [vlan["id"] for vlan in parsed_fabric["vlans"]])
Example #8
0
 def test__clears_external_dhcp_when_managed_vlan(self):
     rack_controller = factory.make_RackController(interface=False)
     fabric = factory.make_Fabric()
     vlan = fabric.get_default_vlan()
     interface = factory.make_Interface(INTERFACE_TYPE.PHYSICAL,
                                        node=rack_controller,
                                        vlan=vlan)
     subnet = factory.make_Subnet()
     dhcp_ip = factory.pick_ip_in_Subnet(subnet)
     vlan.dhcp_on = True
     vlan.primary_rack = rack_controller
     vlan.external_dhcp = dhcp_ip
     vlan.save()
     factory.make_StaticIPAddress(
         alloc_type=IPADDRESS_TYPE.STICKY,
         ip=dhcp_ip,
         subnet=subnet,
         interface=interface,
     )
     update_foreign_dhcp(rack_controller.system_id, interface.name, dhcp_ip)
     self.assertIsNone(reload_object(interface.vlan).external_dhcp)
Example #9
0
 def test_create_interface_creates_static(self):
     user = factory.make_admin()
     node = factory.make_Node(interface=False, node_type=NODE_TYPE.DEVICE)
     handler = DeviceHandler(user, {})
     name = factory.make_name("eth")
     mac_address = factory.make_mac_address()
     fabric = factory.make_Fabric()
     vlan = fabric.get_default_vlan()
     subnet = factory.make_Subnet(vlan=vlan)
     handler.create_interface({
         "system_id": node.system_id,
         "name": name,
         "mac_address": mac_address,
         "ip_assignment": DEVICE_IP_ASSIGNMENT_TYPE.STATIC,
         "subnet": subnet.id,
         })
     new_interface = node.interface_set.first()
     self.assertIsNotNone(new_interface)
     auto_ip = new_interface.ip_addresses.filter(
         alloc_type=IPADDRESS_TYPE.STICKY, subnet=subnet)
     self.assertIsNotNone(auto_ip)
     self.assertEqual(1, len(auto_ip))
Example #10
0
    def test__sets_boot_interface_vlan_to_match_rack_controller(self):
        rack_controller = factory.make_RackController()
        rack_fabric = factory.make_Fabric()
        rack_vlan = rack_fabric.get_default_vlan()
        rack_interface = factory.make_Interface(INTERFACE_TYPE.PHYSICAL,
                                                node=rack_controller,
                                                vlan=rack_vlan)
        rack_subnet = factory.make_Subnet(vlan=rack_vlan)
        rack_ip = factory.make_StaticIPAddress(
            alloc_type=IPADDRESS_TYPE.STICKY,
            subnet=rack_subnet,
            interface=rack_interface)
        remote_ip = factory.make_ip_address()
        node = self.make_node()
        mac = node.get_boot_interface().mac_address

        get_config(rack_controller.system_id,
                   rack_ip.ip,
                   remote_ip,
                   mac=mac,
                   query_count=27)
        self.assertEqual(rack_vlan,
                         reload_object(node).get_boot_interface().vlan)
Example #11
0
 def test__moves_children_vlans_to_same_fabric(self):
     node = self.maker()
     parent = factory.make_Interface(INTERFACE_TYPE.PHYSICAL, node=node)
     subnet = factory.make_Subnet(vlan=parent.vlan)
     factory.make_StaticIPAddress(subnet=subnet, interface=parent)
     old_vlan = factory.make_VLAN(fabric=parent.vlan.fabric)
     vlan_interface = factory.make_Interface(INTERFACE_TYPE.VLAN,
                                             vlan=old_vlan,
                                             parents=[parent])
     vlan_subnet = factory.make_Subnet(vlan=old_vlan)
     factory.make_StaticIPAddress(subnet=vlan_subnet,
                                  interface=vlan_interface)
     new_fabric = factory.make_Fabric()
     new_vlan = new_fabric.get_default_vlan()
     parent.vlan = new_vlan
     parent.save()
     self.assertEquals(new_vlan, reload_object(subnet).vlan)
     vlan_interface = reload_object(vlan_interface)
     self.assertEquals(
         (new_fabric.id, old_vlan.vid),
         (vlan_interface.vlan.fabric.id, vlan_interface.vlan.vid))
     vlan_subnet = reload_object(vlan_subnet)
     self.assertEquals((new_fabric.id, old_vlan.vid),
                       (vlan_subnet.vlan.fabric.id, vlan_subnet.vlan.vid))
Example #12
0
 def test_rejects_duplicate_names(self):
     fabric1 = factory.make_Fabric()
     self.assertRaises(ValidationError,
                       factory.make_Fabric,
                       name=fabric1.name)
Example #13
0
 def test_handler_path(self):
     fabric = factory.make_Fabric()
     self.assertEqual("/MAAS/api/2.0/fabrics/%s/" % fabric.id,
                      get_fabric_uri(fabric))
Example #14
0
 def test_handler_path(self):
     fabric = factory.make_Fabric()
     self.assertEqual('/api/2.0/fabrics/%s/vlans/' % (fabric.id),
                      get_vlans_uri(fabric))
Example #15
0
 def test_handler_path(self):
     fabric = factory.make_Fabric()
     vlan = factory.make_VLAN(fabric=fabric)
     self.assertEqual('/api/2.0/vlans/%s/' % vlan.id, get_vlan_uri(vlan))
Example #16
0
 def test_get_name_for_set_name(self):
     name = factory.make_name("name")
     fabric = factory.make_Fabric(name=name)
     self.assertEqual(name, fabric.get_name())
Example #17
0
 def test_get_name_for_empty_name(self):
     fabric = factory.make_Fabric()
     self.assertEqual("fabric-%s" % fabric.id, fabric.get_name())
Example #18
0
 def test_manager_get_default_vlan_returns_dflt_vlan_of_dflt_fabric(self):
     factory.make_Fabric()
     vlan = VLAN.objects.get_default_vlan()
     self.assertTrue(vlan.is_fabric_default())
     self.assertTrue(vlan.fabric.is_default())
Example #19
0
 def test_is_fabric_default_detects_default_vlan(self):
     fabric = factory.make_Fabric()
     factory.make_VLAN(fabric=fabric)
     vlan = fabric.vlan_set.all().order_by('id').first()
     self.assertTrue(vlan.is_fabric_default())
Example #20
0
def populate_main():
    """Populate the main data all in one transaction."""
    admin = factory.make_admin(username="******",
                               password="******",
                               completed_intro=False)  # noqa
    user1, _ = factory.make_user_with_keys(username="******",
                                           password="******",
                                           completed_intro=False)
    user2, _ = factory.make_user_with_keys(username="******",
                                           password="******",
                                           completed_intro=False)

    # Physical zones.
    zones = [
        factory.make_Zone(name="zone-north"),
        factory.make_Zone(name="zone-south"),
    ]

    # DNS domains.
    domains = [
        Domain.objects.get_default_domain(),
        factory.make_Domain("sample"),
        factory.make_Domain("ubnt"),
    ]

    # Create the fabrics that will be used by the regions, racks,
    # machines, and devices.
    fabric0 = Fabric.objects.get_default_fabric()
    fabric0_untagged = fabric0.get_default_vlan()
    fabric0_vlan10 = factory.make_VLAN(fabric=fabric0, vid=10)
    fabric1 = factory.make_Fabric()
    fabric1_untagged = fabric1.get_default_vlan()
    fabric1_vlan42 = factory.make_VLAN(fabric=fabric1, vid=42)
    empty_fabric = factory.make_Fabric()  # noqa

    # Create some spaces.
    space_mgmt = factory.make_Space("management")
    space_storage = factory.make_Space("storage")
    space_internal = factory.make_Space("internal")
    space_ipv6_testbed = factory.make_Space("ipv6-testbed")

    # Subnets used by regions, racks, machines, and devices.
    subnet_1 = factory.make_Subnet(
        cidr="172.16.1.0/24",
        gateway_ip="172.16.1.1",
        vlan=fabric0_untagged,
        space=space_mgmt,
    )
    subnet_2 = factory.make_Subnet(
        cidr="172.16.2.0/24",
        gateway_ip="172.16.2.1",
        vlan=fabric1_untagged,
        space=space_mgmt,
    )
    subnet_3 = factory.make_Subnet(
        cidr="172.16.3.0/24",
        gateway_ip="172.16.3.1",
        vlan=fabric0_vlan10,
        space=space_storage,
    )
    subnet_4 = factory.make_Subnet(  # noqa
        cidr="172.16.4.0/24",
        gateway_ip="172.16.4.1",
        vlan=fabric0_vlan10,
        space=space_internal,
    )
    subnet_2001_db8_42 = factory.make_Subnet(  # noqa
        cidr="2001:db8:42::/64",
        gateway_ip="",
        vlan=fabric1_vlan42,
        space=space_ipv6_testbed,
    )
    ipv4_subnets = [subnet_1, subnet_2, subnet_3, subnet_4]

    # Static routes on subnets.
    factory.make_StaticRoute(source=subnet_1, destination=subnet_2)
    factory.make_StaticRoute(source=subnet_1, destination=subnet_3)
    factory.make_StaticRoute(source=subnet_1, destination=subnet_4)
    factory.make_StaticRoute(source=subnet_2, destination=subnet_1)
    factory.make_StaticRoute(source=subnet_2, destination=subnet_3)
    factory.make_StaticRoute(source=subnet_2, destination=subnet_4)
    factory.make_StaticRoute(source=subnet_3, destination=subnet_1)
    factory.make_StaticRoute(source=subnet_3, destination=subnet_2)
    factory.make_StaticRoute(source=subnet_3, destination=subnet_4)
    factory.make_StaticRoute(source=subnet_4, destination=subnet_1)
    factory.make_StaticRoute(source=subnet_4, destination=subnet_2)
    factory.make_StaticRoute(source=subnet_4, destination=subnet_3)

    # Load builtin scripts in the database so we can generate fake results
    # below.
    load_builtin_scripts()

    hostname = gethostname()
    region_rack = get_one(
        Node.objects.filter(node_type=NODE_TYPE.REGION_AND_RACK_CONTROLLER,
                            hostname=hostname))
    # If "make run" executes before "make sampledata", the rack may have
    # already registered.
    if region_rack is None:
        region_rack = factory.make_Node(
            node_type=NODE_TYPE.REGION_AND_RACK_CONTROLLER,
            hostname=hostname,
            interface=False,
        )

        # Get list of mac addresses that should be used for the region
        # rack controller. This will make sure the RegionAdvertisingService
        # picks the correct region on first start-up and doesn't get multiple.
        mac_addresses = get_mac_addresses()

        def get_next_mac():
            try:
                return mac_addresses.pop()
            except IndexError:
                return factory.make_mac_address()

        # Region and rack controller (hostname of dev machine)
        #   eth0     - fabric 0 - untagged
        #   eth1     - fabric 0 - untagged
        #   eth2     - fabric 1 - untagged - 172.16.2.2/24 - static
        #   bond0    - fabric 0 - untagged - 172.16.1.2/24 - static
        #   bond0.10 - fabric 0 - 10       - 172.16.3.2/24 - static
        eth0 = factory.make_Interface(
            INTERFACE_TYPE.PHYSICAL,
            name="eth0",
            node=region_rack,
            vlan=fabric0_untagged,
            mac_address=get_next_mac(),
        )
        eth1 = factory.make_Interface(
            INTERFACE_TYPE.PHYSICAL,
            name="eth1",
            node=region_rack,
            vlan=fabric0_untagged,
            mac_address=get_next_mac(),
        )
        eth2 = factory.make_Interface(
            INTERFACE_TYPE.PHYSICAL,
            name="eth2",
            node=region_rack,
            vlan=fabric1_untagged,
            mac_address=get_next_mac(),
        )
        bond0 = factory.make_Interface(
            INTERFACE_TYPE.BOND,
            name="bond0",
            node=region_rack,
            vlan=fabric0_untagged,
            parents=[eth0, eth1],
            mac_address=eth0.mac_address,
        )
        bond0_10 = factory.make_Interface(
            INTERFACE_TYPE.VLAN,
            node=region_rack,
            vlan=fabric0_vlan10,
            parents=[bond0],
        )
        factory.make_StaticIPAddress(
            alloc_type=IPADDRESS_TYPE.STICKY,
            ip="172.16.1.2",
            subnet=subnet_1,
            interface=bond0,
        )
        factory.make_StaticIPAddress(
            alloc_type=IPADDRESS_TYPE.STICKY,
            ip="172.16.2.2",
            subnet=subnet_2,
            interface=eth2,
        )
        factory.make_StaticIPAddress(
            alloc_type=IPADDRESS_TYPE.STICKY,
            ip="172.16.3.2",
            subnet=subnet_3,
            interface=bond0_10,
        )
        fabric0_untagged.primary_rack = region_rack
        fabric0_untagged.save()
        fabric1_untagged.primary_rack = region_rack
        fabric1_untagged.save()
        fabric0_vlan10.primary_rack = region_rack
        fabric0_vlan10.save()

    # Rack controller (happy-rack)
    #   eth0     - fabric 0 - untagged
    #   eth1     - fabric 0 - untagged
    #   eth2     - fabric 1 - untagged - 172.16.2.3/24 - static
    #   bond0    - fabric 0 - untagged - 172.16.1.3/24 - static
    #   bond0.10 - fabric 0 - 10       - 172.16.3.3/24 - static
    rack = factory.make_Node(
        node_type=NODE_TYPE.RACK_CONTROLLER,
        hostname="happy-rack",
        interface=False,
    )
    eth0 = factory.make_Interface(INTERFACE_TYPE.PHYSICAL,
                                  name="eth0",
                                  node=rack,
                                  vlan=fabric0_untagged)
    eth1 = factory.make_Interface(INTERFACE_TYPE.PHYSICAL,
                                  name="eth1",
                                  node=rack,
                                  vlan=fabric0_untagged)
    eth2 = factory.make_Interface(INTERFACE_TYPE.PHYSICAL,
                                  name="eth2",
                                  node=rack,
                                  vlan=fabric1_untagged)
    bond0 = factory.make_Interface(
        INTERFACE_TYPE.BOND,
        name="bond0",
        node=rack,
        vlan=fabric0_untagged,
        parents=[eth0, eth1],
    )
    bond0_10 = factory.make_Interface(INTERFACE_TYPE.VLAN,
                                      node=rack,
                                      vlan=fabric0_vlan10,
                                      parents=[bond0])
    factory.make_StaticIPAddress(
        alloc_type=IPADDRESS_TYPE.STICKY,
        ip="172.16.1.3",
        subnet=subnet_1,
        interface=bond0,
    )
    factory.make_StaticIPAddress(
        alloc_type=IPADDRESS_TYPE.STICKY,
        ip="172.16.2.3",
        subnet=subnet_2,
        interface=eth2,
    )
    factory.make_StaticIPAddress(
        alloc_type=IPADDRESS_TYPE.STICKY,
        ip="172.16.3.3",
        subnet=subnet_3,
        interface=bond0_10,
    )
    fabric0_untagged.secondary_rack = rack
    fabric0_untagged.save()
    fabric1_untagged.secondary_rack = rack
    fabric1_untagged.save()
    fabric0_vlan10.secondary_rack = rack
    fabric0_vlan10.save()

    # Region controller (happy-region)
    #   eth0     - fabric 0 - untagged
    #   eth1     - fabric 0 - untagged
    #   eth2     - fabric 1 - untagged - 172.16.2.4/24 - static
    #   bond0    - fabric 0 - untagged - 172.16.1.4/24 - static
    #   bond0.10 - fabric 0 - 10       - 172.16.3.4/24 - static
    region = factory.make_Node(
        node_type=NODE_TYPE.REGION_CONTROLLER,
        hostname="happy-region",
        interface=False,
    )
    eth0 = factory.make_Interface(
        INTERFACE_TYPE.PHYSICAL,
        name="eth0",
        node=region,
        vlan=fabric0_untagged,
    )
    eth1 = factory.make_Interface(
        INTERFACE_TYPE.PHYSICAL,
        name="eth1",
        node=region,
        vlan=fabric0_untagged,
    )
    eth2 = factory.make_Interface(
        INTERFACE_TYPE.PHYSICAL,
        name="eth2",
        node=region,
        vlan=fabric1_untagged,
    )
    bond0 = factory.make_Interface(
        INTERFACE_TYPE.BOND,
        name="bond0",
        node=region,
        vlan=fabric0_untagged,
        parents=[eth0, eth1],
    )
    bond0_10 = factory.make_Interface(INTERFACE_TYPE.VLAN,
                                      node=region,
                                      vlan=fabric0_vlan10,
                                      parents=[bond0])
    factory.make_StaticIPAddress(
        alloc_type=IPADDRESS_TYPE.STICKY,
        ip="172.16.1.4",
        subnet=subnet_1,
        interface=bond0,
    )
    factory.make_StaticIPAddress(
        alloc_type=IPADDRESS_TYPE.STICKY,
        ip="172.16.2.4",
        subnet=subnet_2,
        interface=eth2,
    )
    factory.make_StaticIPAddress(
        alloc_type=IPADDRESS_TYPE.STICKY,
        ip="172.16.3.4",
        subnet=subnet_3,
        interface=bond0_10,
    )

    # Create one machine for every status. Each machine has a random interface
    # and storage configration.
    node_statuses = [
        status for status in map_enum(NODE_STATUS).items() if status not in
        [NODE_STATUS.MISSING, NODE_STATUS.RESERVED, NODE_STATUS.RETIRED]
    ]
    machines = []
    test_scripts = [
        script.name
        for script in Script.objects.filter(script_type=SCRIPT_TYPE.TESTING)
    ]
    for _, status in node_statuses:
        owner = None
        if status in ALLOCATED_NODE_STATUSES:
            owner = random.choice([admin, user1, user2])
        elif status in [
                NODE_STATUS.COMMISSIONING,
                NODE_STATUS.FAILED_RELEASING,
        ]:
            owner = admin

        machine = factory.make_Node(
            status=status,
            owner=owner,
            zone=random.choice(zones),
            interface=False,
            with_boot_disk=False,
            power_type="manual",
            domain=random.choice(domains),
            memory=random.choice([1024, 4096, 8192]),
            description=random.choice([
                "",
                "Scheduled for removeal",
                "Firmware old",
                "Earmarked for Project Fuse in April",
            ]),
            cpu_count=random.randint(2, 8),
        )
        machine.set_random_hostname()
        machines.append(machine)

        # Create random network configuration.
        RandomInterfaceFactory.create_random(machine)

        # Add random storage devices and set a random layout.
        for _ in range(random.randint(1, 5)):
            factory.make_PhysicalBlockDevice(
                node=machine,
                size=random.randint(LARGE_BLOCK_DEVICE,
                                    LARGE_BLOCK_DEVICE * 10),
            )
        if status in [
                NODE_STATUS.READY,
                NODE_STATUS.ALLOCATED,
                NODE_STATUS.DEPLOYING,
                NODE_STATUS.DEPLOYED,
                NODE_STATUS.FAILED_DEPLOYMENT,
                NODE_STATUS.RELEASING,
                NODE_STATUS.FAILED_RELEASING,
        ]:
            machine.set_storage_layout(
                random.choice([
                    layout for layout in STORAGE_LAYOUTS.keys()
                    if layout != "vmfs6"
                ]))
            if status != NODE_STATUS.READY:
                machine._create_acquired_filesystems()

        # Add a random amount of events.
        for _ in range(random.randint(25, 100)):
            factory.make_Event(node=machine)

        # Add in commissioning and testing results.
        if status != NODE_STATUS.NEW:
            for _ in range(0, random.randint(1, 10)):
                css = ScriptSet.objects.create_commissioning_script_set(
                    machine)
                scripts = set()
                for __ in range(1, len(test_scripts)):
                    scripts.add(random.choice(test_scripts))
                tss = ScriptSet.objects.create_testing_script_set(
                    machine, list(scripts))
            machine.current_commissioning_script_set = css
            machine.current_testing_script_set = tss
            machine.save()

        # Fill in historic results
        for script_set in machine.scriptset_set.all():
            if script_set in [css, tss]:
                continue
            for script_result in script_set:
                # Can't use script_result.store_result as it will try to
                # process the result and fail on the fake data.
                script_result.exit_status = random.randint(0, 255)
                if script_result.exit_status == 0:
                    script_result.status = SCRIPT_STATUS.PASSED
                else:
                    script_result.status = random.choice(
                        list(SCRIPT_STATUS_FAILED))
                script_result.started = factory.make_date()
                script_result.ended = script_result.started + timedelta(
                    seconds=random.randint(0, 10000))
                script_result.stdout = Bin(
                    factory.make_string().encode("utf-8"))
                script_result.stderr = Bin(
                    factory.make_string().encode("utf-8"))
                script_result.output = Bin(
                    factory.make_string().encode("utf-8"))
                script_result.save()

        # Only add in results in states where commissiong should be completed.
        if status not in [NODE_STATUS.NEW, NODE_STATUS.COMMISSIONING]:
            if status == NODE_STATUS.FAILED_COMMISSIONING:
                exit_status = random.randint(1, 255)
                script_status = random.choice(list(SCRIPT_STATUS_FAILED))
            else:
                exit_status = 0
                script_status = SCRIPT_STATUS.PASSED
            for script_result in css:
                # Can't use script_result.store_result as it will try to
                # process the result and fail on the fake data.
                script_result.status = script_status
                script_result.exit_status = exit_status
                script_result.started = factory.make_date()
                script_result.ended = script_result.started + timedelta(
                    seconds=random.randint(0, 10000))
                script_result.stdout = Bin(
                    factory.make_string().encode("utf-8"))
                script_result.stderr = Bin(
                    factory.make_string().encode("utf-8"))
                script_result.output = Bin(
                    factory.make_string().encode("utf-8"))
                script_result.save()
        elif status == NODE_STATUS.COMMISSIONING:
            for script_result in css:
                script_result.status = random.choice(
                    list(SCRIPT_STATUS_RUNNING_OR_PENDING))
                if script_result.status != SCRIPT_STATUS.PENDING:
                    script_result.started = factory.make_date()
                script_result.save()

        # Only add in results in states where testing should be completed.
        if status not in [NODE_STATUS.NEW, NODE_STATUS.TESTING]:
            if status == NODE_STATUS.FAILED_TESTING:
                exit_status = random.randint(1, 255)
                script_status = random.choice(list(SCRIPT_STATUS_FAILED))
            else:
                exit_status = 0
                script_status = SCRIPT_STATUS.PASSED
            for script_result in tss:
                # Can't use script_result.store_result as it will try to
                # process the result and fail on the fake data.
                script_result.status = script_status
                script_result.exit_status = exit_status
                script_result.started = factory.make_date()
                script_result.ended = script_result.started + timedelta(
                    seconds=random.randint(0, 10000))
                script_result.stdout = Bin(
                    factory.make_string().encode("utf-8"))
                script_result.stderr = Bin(
                    factory.make_string().encode("utf-8"))
                script_result.output = Bin(
                    factory.make_string().encode("utf-8"))
                script_result.save()
        elif status == NODE_STATUS.TESTING:
            for script_result in tss:
                script_result.status = random.choice(
                    list(SCRIPT_STATUS_RUNNING_OR_PENDING))
                if script_result.status != SCRIPT_STATUS.PENDING:
                    script_result.started = factory.make_date()
                script_result.save()

        # Add installation results.
        if status in [
                NODE_STATUS.DEPLOYING,
                NODE_STATUS.DEPLOYED,
                NODE_STATUS.FAILED_DEPLOYMENT,
        ]:
            script_set = ScriptSet.objects.create_installation_script_set(
                machine)
            machine.current_installation_script_set = script_set
            machine.save()

        if status == NODE_STATUS.DEPLOYED:
            for script_result in machine.current_installation_script_set:
                stdout = factory.make_string().encode("utf-8")
                script_result.store_result(0, stdout)
        elif status == NODE_STATUS.FAILED_DEPLOYMENT:
            for script_result in machine.current_installation_script_set:
                exit_status = random.randint(1, 255)
                stdout = factory.make_string().encode("utf-8")
                stderr = factory.make_string().encode("utf-8")
                script_result.store_result(exit_status, stdout, stderr)

        # Add children devices to the deployed machine.
        if status == NODE_STATUS.DEPLOYED:
            boot_interface = machine.get_boot_interface()
            for _ in range(5):
                device = factory.make_Device(
                    interface=True,
                    domain=machine.domain,
                    parent=machine,
                    vlan=boot_interface.vlan,
                )
                device.set_random_hostname()
                RandomInterfaceFactory.assign_ip(
                    device.get_boot_interface(),
                    alloc_type=IPADDRESS_TYPE.STICKY,
                )

    # Create a few pods to and assign a random set of the machines to the pods.
    pods = [None]
    pod_storage_pools = defaultdict(list)
    machines_in_pods = defaultdict(list)
    for _ in range(3):
        subnet = random.choice(ipv4_subnets)
        ip = factory.pick_ip_in_Subnet(subnet)
        ip_address = factory.make_StaticIPAddress(
            alloc_type=IPADDRESS_TYPE.STICKY, ip=ip, subnet=subnet)
        power_address = "qemu+ssh://ubuntu@%s/system" % ip
        pod = factory.make_Pod(
            pod_type="virsh",
            parameters={"power_address": power_address},
            ip_address=ip_address,
            capabilities=[
                Capabilities.DYNAMIC_LOCAL_STORAGE,
                Capabilities.COMPOSABLE,
            ],
        )
        for _ in range(3):
            pool = factory.make_PodStoragePool(pod)
            pod_storage_pools[pod].append(pool)
        pod.default_storage_pool = pool
        pod.save()
        pods.append(pod)
    for _ in range(3):
        subnet = random.choice(ipv4_subnets)
        ip = factory.pick_ip_in_Subnet(subnet)
        ip_address = factory.make_StaticIPAddress(
            alloc_type=IPADDRESS_TYPE.STICKY, ip=ip, subnet=subnet)
        power_address = "%s" % ip
        pod = factory.make_Pod(
            pod_type="rsd",
            parameters={
                "power_address": power_address,
                "power_user": "******",
                "power_pass": "******",
            },
            ip_address=ip_address,
            capabilities=[
                Capabilities.DYNAMIC_LOCAL_STORAGE,
                Capabilities.COMPOSABLE,
            ],
        )
        for _ in range(3):
            pool = factory.make_PodStoragePool(pod)
            pod_storage_pools[pod].append(pool)
        pod.default_storage_pool = pool
        pod.save()
        pods.append(pod)
    for machine in machines:
        # Add the machine to the pod if its lucky day!
        pod = random.choice(pods)
        if pod is not None:
            machine.bmc = pod
            machine.instance_power_parameters = {"power_id": machine.hostname}
            machine.save()
            machines_in_pods[pod].append(machine)

            # Assign the block devices on the machine to a storage pool.
            for block_device in machine.physicalblockdevice_set.all():
                block_device.storage_pool = random.choice(
                    pod_storage_pools[pod])
                block_device.save()

    # Update the pod attributes so that it has more available then used.
    for pod in pods[1:]:
        pod.cores = pod.get_used_cores() + random.randint(4, 8)
        pod.memory = pod.get_used_memory() + random.choice(
            [1024, 2048, 4096, 4096 * 4, 4096 * 8])
        pod.local_storage = sum(pool.storage
                                for pool in pod_storage_pools[pod])
        pod.save()

    # Create a few devices.
    for _ in range(10):
        device = factory.make_Device(interface=True)
        device.set_random_hostname()

    # Add some DHCP snippets.
    # - Global
    factory.make_DHCPSnippet(
        name="foo class",
        description="adds class for vender 'foo'",
        value=VersionedTextFile.objects.create(data=dedent("""\
            class "foo" {
                match if substring (
                    option vendor-class-identifier, 0, 3) = "foo";
            }
        """)),
    )
    factory.make_DHCPSnippet(
        name="bar class",
        description="adds class for vender 'bar'",
        value=VersionedTextFile.objects.create(data=dedent("""\
            class "bar" {
                match if substring (
                    option vendor-class-identifier, 0, 3) = "bar";
            }
        """)),
        enabled=False,
    )
    # - Subnet
    factory.make_DHCPSnippet(
        name="600 lease time",
        description="changes lease time to 600 secs.",
        value=VersionedTextFile.objects.create(data="default-lease-time 600;"),
        subnet=subnet_1,
    )
    factory.make_DHCPSnippet(
        name="7200 max lease time",
        description="changes max lease time to 7200 secs.",
        value=VersionedTextFile.objects.create(data="max-lease-time 7200;"),
        subnet=subnet_2,
        enabled=False,
    )
    # - Node
    factory.make_DHCPSnippet(
        name="boot from other server",
        description="instructs device to boot from other server",
        value=VersionedTextFile.objects.create(data=dedent("""\
            filename "test-boot";
            server-name "boot.from.me";
        """)),
        node=device,
    )

    # Add notifications for admins, users, and each individual user, and for
    # each notification category.
    factory.make_Notification(
        "Attention admins! Core critical! Meltdown imminent! Evacuate "
        "habitat immediately!",
        admins=True,
        category="error",
    )
    factory.make_Notification(
        "Dear users, rumours of a core meltdown are unfounded. Please "
        "return to your home-pods and places of business.",
        users=True,
        category="warning",
    )
    factory.make_Notification(
        "FREE! For the next 2 hours get FREE blueberry and iodine pellets "
        "at the nutri-dispensers.",
        users=True,
        category="success",
    )
    for user in User.objects.all():
        context = {"name": user.username.capitalize()}
        factory.make_Notification(
            "Greetings, {name}! Get away from the habitat for the weekend and "
            "visit the Mare Nubium with MAAS Tours. Use the code METAL to "
            "claim a special gift!",
            user=user,
            context=context,
            category="info",
        )
Example #21
0
 def test_nonreserved_name_does_not_raise_exception(self):
     fabric = factory.make_Fabric(name="myfabric-33")
     self.assertEqual("myfabric-33", fabric.name)
Example #22
0
 def test_create_does_not_override_name(self):
     name = factory.make_name()
     fabric = factory.make_Fabric(name=name)
     self.assertEqual(name, fabric.name)
Example #23
0
 def test_get_name_for_default_vlan_is_untagged(self):
     fabric = factory.make_Fabric()
     self.assertEqual("untagged", fabric.get_default_vlan().get_name())
Example #24
0
 def test_is_default_detects_non_default_fabric(self):
     name = factory.make_name("name")
     fabric = factory.make_Fabric(name=name)
     self.assertFalse(fabric.is_default())
Example #25
0
 def test_cant_delete_default_vlan(self):
     name = factory.make_name('name')
     fabric = factory.make_Fabric(name=name)
     with ExpectedException(ValidationError):
         fabric.get_default_vlan().delete()
Example #26
0
 def test_can_delete_nonconnected_fabric(self):
     fabric = factory.make_Fabric()
     fabric.delete()
     self.assertItemsEqual([], Fabric.objects.filter(id=fabric.id))
Example #27
0
 def test_subnets_are_reconnected_when_vlan_is_deleted(self):
     fabric = factory.make_Fabric()
     vlan = factory.make_VLAN(fabric=fabric)
     subnet = factory.make_Subnet(vlan=vlan)
     vlan.delete()
     self.assertEqual(reload_object(subnet).vlan, fabric.get_default_vlan())
Example #28
0
 def test_can_delete_non_default_fabric(self):
     name = factory.make_name("name")
     fabric = factory.make_Fabric(name=name)
     fabric.vlan_set.all().delete()
     fabric.delete()
     self.assertItemsEqual([], Fabric.objects.filter(id=fabric.id))
Example #29
0
 def create_fabric(self, params=None):
     if params is None:
         params = {}
     return factory.make_Fabric(**params)
Example #30
0
 def test_save_accepts_default_vlan_in_fabric(self):
     fabric = factory.make_Fabric()
     vlan = factory.make_VLAN(fabric=fabric)
     fabric.default_vlan = vlan
     # No exception.
     self.assertIsNone(fabric.save())