Example #1
0
    def test_GET_rack_controllers_returns_rack_controllers(self):
        self.become_admin()
        tag = factory.make_Tag()
        machine = factory.make_Node()
        device = factory.make_Device()
        rack = factory.make_RackController()
        region = factory.make_RegionController()
        # Create a second node that isn't tagged.
        factory.make_Node()
        machine.tags.add(tag)
        device.tags.add(tag)
        rack.tags.add(tag)
        region.tags.add(tag)
        response = self.client.get(self.get_tag_uri(tag),
                                   {'op': 'rack_controllers'})

        self.assertEqual(http.client.OK, response.status_code)
        parsed_result = json.loads(
            response.content.decode(settings.DEFAULT_CHARSET))
        self.assertItemsEqual([rack.system_id],
                              [r['system_id'] for r in parsed_result])
Example #2
0
 def test_create_interface_creates_with_static_ip_assignment_implicit(self):
     user = factory.make_User()
     handler = DeviceHandler(user, {})
     device = factory.make_Device(owner=user)
     mac = factory.make_mac_address()
     subnet = factory.make_Subnet()
     updated_device = handler.create_interface({
         "system_id": device.system_id,
         "mac_address": mac,
         "ip_assignment": DEVICE_IP_ASSIGNMENT_TYPE.STATIC,
         "subnet": subnet.id,
     })
     self.expectThat(updated_device["primary_mac"], Equals(mac))
     self.expectThat(
         updated_device["ip_assignment"],
         Equals(DEVICE_IP_ASSIGNMENT_TYPE.STATIC))
     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.")
Example #3
0
    def test_yields_rack_addresses(self):
        device = factory.make_Device()
        address = factory.make_StaticIPAddress(
            interface=factory.make_Interface(node=device))

        rack1 = factory.make_RackController()
        rack1_address = factory.make_StaticIPAddress(
            interface=factory.make_Interface(node=rack1),
            subnet=address.subnet)

        rack2 = factory.make_RackController()
        rack2_address = factory.make_StaticIPAddress(
            interface=factory.make_Interface(node=rack2),
            subnet=address.subnet)

        servers = get_servers_for(device)
        self.assertThat(servers,
                        IsSetOfServers({
                            rack1_address.ip,
                            rack2_address.ip,
                        }))
Example #4
0
    def test_GET_query_doesnt_list_devices(self):
        self.become_admin()
        machines = [
            factory.make_Node(
                agent_name=factory.make_name("agent-name"),
                node_type=NODE_TYPE.MACHINE,
            ) for _ in range(3)
        ]
        for machine in machines:
            factory.make_Event(node=machine)

        # Create devices.
        devices = [factory.make_Device() for _ in range(3)]
        for device in devices:
            factory.make_Event(node=device)

        # Create rack controllers.
        rack_controllers = [
            factory.make_Node(
                agent_name=factory.make_name("agent-name"),
                node_type=NODE_TYPE.RACK_CONTROLLER,
            ) for _ in range(3)
        ]
        for rack_controller in rack_controllers:
            factory.make_Event(node=rack_controller)

        response = self.client.get(reverse("events_handler"), {
            "op": "query",
            "level": "DEBUG"
        })

        self.assertEqual(http.client.OK, response.status_code)
        parsed_result = json_load_bytes(response.content)
        system_ids = {event["node"] for event in parsed_result["events"]}
        self.assertThat(
            system_ids.intersection(device.system_id for device in devices),
            HasLength(0),
        )
        self.assertEqual(
            len(machines) + len(rack_controllers), parsed_result["count"])
Example #5
0
 def test_create_interface_creates_static_ip_assignment_explicit(self):
     user = factory.make_User()
     request = HttpRequest()
     request.user = user
     handler = DeviceHandler(user, {}, request)
     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.",
     )
Example #6
0
 def test_create_interface_creates_with_external_ip_assignment(self):
     user = factory.make_User()
     handler = DeviceHandler(user, {})
     device = factory.make_Device(owner=user)
     mac = factory.make_mac_address()
     ip_address = factory.make_ipv4_address()
     updated_device = handler.create_interface({
         "system_id":
         device.system_id,
         "mac_address":
         mac,
         "ip_assignment":
         DEVICE_IP_ASSIGNMENT_TYPE.EXTERNAL,
         "ip_address":
         ip_address,
     })
     self.expectThat(updated_device["primary_mac"], Equals(mac))
     self.expectThat(updated_device["ip_assignment"],
                     Equals(DEVICE_IP_ASSIGNMENT_TYPE.EXTERNAL))
     self.expectThat(
         StaticIPAddress.objects.filter(ip=ip_address).count(), Equals(1),
         "StaticIPAddress was not created.")
Example #7
0
 def test_get_no_numa_nodes_for_device(self):
     user = factory.make_User()
     device = factory.make_Device()
     handler = DeviceHandler(user, {}, None)
     result = handler.get({"system_id": device.system_id})
     self.assertNotIn("numa_nodes", result)
Example #8
0
 def test_doesnt_create_services_for_device(self):
     device = factory.make_Device()
     services = Service.objects.filter(node=device)
     self.assertThat(
         {service.name for service in services},
         HasLength(0))
Example #9
0
    def test_get_maas_stats(self):
        # Make one component of everything
        factory.make_RegionRackController()
        factory.make_RegionController()
        factory.make_RackController()
        factory.make_Machine(cpu_count=2, memory=200, status=NODE_STATUS.READY)
        factory.make_Machine(status=NODE_STATUS.READY)
        factory.make_Machine(status=NODE_STATUS.NEW)
        for _ in range(4):
            factory.make_Machine(status=NODE_STATUS.ALLOCATED)
        factory.make_Machine(cpu_count=3,
                             memory=100,
                             status=NODE_STATUS.FAILED_DEPLOYMENT)
        for _ in range(2):
            factory.make_Machine(status=NODE_STATUS.DEPLOYED)
        factory.make_Device()
        factory.make_Device()

        subnets = Subnet.objects.all()
        v4 = [net for net in subnets if net.get_ip_version() == 4]
        v6 = [net for net in subnets if net.get_ip_version() == 6]

        stats = get_maas_stats()
        machine_stats = get_machine_stats()

        # Due to floating point calculation subtleties, sometimes the value the
        # database returns is off by one compared to the value Python
        # calculates, so just get it directly from the database for the test.
        total_storage = machine_stats["total_storage"]

        expected = {
            "controllers": {
                "regionracks": 1,
                "regions": 1,
                "racks": 1
            },
            "nodes": {
                "machines": 10,
                "devices": 2
            },
            "machine_stats": {
                "total_cpu": 5,
                "total_mem": 300,
                "total_storage": total_storage,
            },
            "machine_status": {
                "new": 1,
                "ready": 2,
                "allocated": 4,
                "deployed": 2,
                "commissioning": 0,
                "testing": 0,
                "deploying": 0,
                "failed_deployment": 1,
                "failed_commissioning": 0,
                "failed_testing": 0,
                "broken": 0,
            },
            "network_stats": {
                "spaces": Space.objects.count(),
                "fabrics": Fabric.objects.count(),
                "vlans": VLAN.objects.count(),
                "subnets_v4": len(v4),
                "subnets_v6": len(v6),
            },
        }
        self.assertEquals(json.loads(stats), expected)
Example #10
0
 def test_get_no_switch(self):
     owner = factory.make_User()
     handler = SwitchHandler(owner, {}, None)
     device = factory.make_Device(owner=owner)
     self.assertRaises(HandlerDoesNotExistError, handler.get,
                       {"system_id": device.system_id})
Example #11
0
 def test_device(self):
     # A Switch object can be based on a device node.
     device = factory.make_Device()
     switch = factory.make_Switch(node=device)
     self.assertEqual(device.as_node(), switch.node)
Example #12
0
 def test_user_cannot_edit_device_rbac(self):
     self.enable_rbac()
     user = factory.make_User()
     node = factory.make_Device()
     backend = MAASAuthorizationBackend()
     self.assertFalse(backend.has_perm(user, NodePermission.edit, node))
Example #13
0
 def test_user_can_view_device_rbac(self):
     self.enable_rbac()
     user = factory.make_User()
     node = factory.make_Device()
     backend = MAASAuthorizationBackend()
     self.assertTrue(backend.has_perm(user, NodePermission.view, node))
Example #14
0
 def test_restore_networking_configuration_requires_admin(self):
     device = factory.make_Device()
     response = self.client.post(get_device_uri(device),
                                 {'op': 'restore_networking_configuration'})
     self.assertEqual(http.client.FORBIDDEN, response.status_code,
                      response.content)
Example #15
0
    def test_get_maas_stats(self):
        # Make one component of everything
        factory.make_RegionRackController()
        factory.make_RegionController()
        factory.make_RackController()
        factory.make_Machine(cpu_count=2, memory=200, status=4)
        factory.make_Machine(cpu_count=3, memory=100, status=11)
        factory.make_Device()

        subnets = Subnet.objects.all()
        v4 = [net for net in subnets if net.get_ip_version() == 4]
        v6 = [net for net in subnets if net.get_ip_version() == 6]

        stats = get_maas_stats()
        machine_stats = get_machine_stats()

        # Due to floating point calculation subtleties, sometimes the value the
        # database returns is off by one compared to the value Python
        # calculates, so just get it directly from the database for the test.
        total_storage = machine_stats['total_storage']

        node_status = Node.objects.values_list('status', flat=True)
        node_status = Counter(node_status)

        compare = {
            "controllers": {
                "regionracks": 1,
                "regions": 1,
                "racks": 1,
            },
            "nodes": {
                "machines": 2,
                "devices": 1,
            },
            "machine_stats": {
                "total_cpu": 5,
                "total_mem": 300,
                "total_storage": total_storage,
            },
            "machine_status": {
                "new":
                node_status.get(NODE_STATUS.NEW, 0),
                "ready":
                node_status.get(NODE_STATUS.READY, 0),
                "allocated":
                node_status.get(NODE_STATUS.ALLOCATED, 0),
                "deployed":
                node_status.get(NODE_STATUS.DEPLOYED, 0),
                "commissioning":
                node_status.get(NODE_STATUS.COMMISSIONING, 0),
                "testing":
                node_status.get(NODE_STATUS.TESTING, 0),
                "deploying":
                node_status.get(NODE_STATUS.DEPLOYING, 0),
                "failed_deployment":
                node_status.get(NODE_STATUS.FAILED_DEPLOYMENT, 0),
                "failed_commissioning":
                node_status.get(NODE_STATUS.COMMISSIONING, 0),
                "failed_testing":
                node_status.get(NODE_STATUS.FAILED_TESTING, 0),
                "broken":
                node_status.get(NODE_STATUS.BROKEN, 0),
            },
            "network_stats": {
                "spaces": Space.objects.count(),
                "fabrics": Fabric.objects.count(),
                "vlans": VLAN.objects.count(),
                "subnets_v4": len(v4),
                "subnets_v6": len(v6),
            },
        }
        self.assertEquals(stats, json.dumps(compare))
Example #16
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 #17
0
 def test_create_services_for_device(self):
     device = factory.make_Device()
     Service.objects.create_services_for(device)
     self.assertThat(Service.objects.filter(node=device), HasLength(0))
Example #18
0
 def test_restore_default_configuration_requires_admin(self):
     device = factory.make_Device()
     response = self.client.post(get_device_uri(device),
                                 {"op": "restore_default_configuration"})
     self.assertEqual(http.client.FORBIDDEN, response.status_code,
                      response.content)
Example #19
0
 def test_not_for_devices(self):
     device = factory.make_Device()
     self.assertEqual(device.numanode_set.count(), 0)
Example #20
0
 def test_list_ignores_nodes_that_arent_switches(self):
     owner = factory.make_User()
     handler = SwitchHandler(owner, {}, None)
     factory.make_Device(owner=owner)
     factory.make_Machine(owner=owner)
     self.assertItemsEqual([], handler.list({}))
Example #21
0
    def test_get_maas_stats(self):
        # Make one component of everything
        factory.make_RegionRackController()
        factory.make_RegionController()
        factory.make_RackController()
        factory.make_Machine(cpu_count=2, memory=200, status=NODE_STATUS.READY)
        factory.make_Machine(status=NODE_STATUS.READY)
        factory.make_Machine(status=NODE_STATUS.NEW)
        for _ in range(4):
            factory.make_Machine(status=NODE_STATUS.ALLOCATED)
        factory.make_Machine(cpu_count=3,
                             memory=100,
                             status=NODE_STATUS.FAILED_DEPLOYMENT)
        factory.make_Machine(status=NODE_STATUS.DEPLOYED)
        deployed_machine = factory.make_Machine(status=NODE_STATUS.DEPLOYED)
        OwnerData.objects.set_owner_data(deployed_machine, {"foo": "bar"})
        factory.make_Device()
        factory.make_Device()
        self.make_pod(cpu=10, mem=100, pod_type="lxd")
        self.make_pod(cpu=20, mem=200, pod_type="virsh")

        subnets = Subnet.objects.all()
        v4 = [net for net in subnets if net.get_ip_version() == 4]
        v6 = [net for net in subnets if net.get_ip_version() == 6]

        stats = get_maas_stats()
        machine_stats = get_machine_stats()

        # Due to floating point calculation subtleties, sometimes the value the
        # database returns is off by one compared to the value Python
        # calculates, so just get it directly from the database for the test.
        total_storage = machine_stats["total_storage"]

        expected = {
            "controllers": {
                "regionracks": 1,
                "regions": 1,
                "racks": 1
            },
            "nodes": {
                "machines": 10,
                "devices": 2
            },
            "machine_stats": {
                "total_cpu": 5,
                "total_mem": 300,
                "total_storage": total_storage,
            },
            "machine_status": {
                "new": 1,
                "ready": 2,
                "allocated": 4,
                "deployed": 2,
                "commissioning": 0,
                "testing": 0,
                "deploying": 0,
                "failed_deployment": 1,
                "failed_commissioning": 0,
                "failed_testing": 0,
                "broken": 0,
            },
            "network_stats": {
                "spaces": Space.objects.count(),
                "fabrics": Fabric.objects.count(),
                "vlans": VLAN.objects.count(),
                "subnets_v4": len(v4),
                "subnets_v6": len(v6),
            },
            "vm_hosts": {
                "lxd": {
                    "vm_hosts": 1,
                    "vms": 0,
                    "available_resources": {
                        "cores": 10,
                        "memory": 100,
                        "over_cores": 10.0,
                        "over_memory": 100.0,
                        "storage": 0,
                    },
                    "utilized_resources": {
                        "cores": 0,
                        "memory": 0,
                        "storage": 0,
                    },
                },
                "virsh": {
                    "vm_hosts": 1,
                    "vms": 0,
                    "available_resources": {
                        "cores": 20,
                        "memory": 200,
                        "over_cores": 20.0,
                        "over_memory": 200.0,
                        "storage": 0,
                    },
                    "utilized_resources": {
                        "cores": 0,
                        "memory": 0,
                        "storage": 0,
                    },
                },
            },
            "workload_annotations": {
                "annotated_machines": 1,
                "total_annotations": 1,
                "unique_keys": 1,
                "unique_values": 1,
            },
        }
        self.assertEqual(stats, expected)