blob: a4d40485683032b90d98e291dc95dd9d8228dec5 [file] [log] [blame]
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +08001#!/usr/bin/env python3
2
3# SPDX-FileCopyrightText: © 2021 Open Networking Foundation <support@opennetworking.org>
4# SPDX-License-Identifier: Apache-2.0
5
6# tenant.py
7# The tenant abstract object of Netbox Object - Tenant
8
Zack Williamsdac2be42021-08-19 16:14:31 -07009import sys
10
11from .utils import logger
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +080012from .device import Device, VirtualMachine
13from .network import Prefix
14
15
16class Tenant:
17 def __init__(self):
18
19 from .utils import netboxapi, netbox_config
20
21 self.nbapi = netboxapi
22 self.name = netbox_config["tenant_name"]
23 self.name_segments = netbox_config.get("prefix_segments", 1)
24
25 self.tenant = self.nbapi.tenancy.tenants.get(name=self.name)
26
27 # Tenant only keep the resources which owns by it
28 self.devices = list()
29 self.vms = list()
30 self.prefixes = dict()
31
32 # Get the Device and Virtual Machines from Netbox API
33 for device_data in self.nbapi.dcim.devices.filter(tenant=self.tenant.slug):
34 device = Device(device_data)
35 device.tenant = self
36 self.devices.append(device)
37
38 for vm_data in self.nbapi.virtualization.virtual_machines.filter(
39 tenant=self.tenant.slug
40 ):
41 vm = VirtualMachine(vm_data)
42 vm.tenant = self
43 self.vms.append(vm)
44
45 vrf = self.nbapi.ipam.vrfs.get(tenant=self.tenant.slug)
46 for prefix_data in self.nbapi.ipam.prefixes.filter(vrf_id=vrf.id):
47 prefix = Prefix(prefix_data, self.name_segments)
48 if prefix_data.description:
49 self.prefixes[prefix_data.prefix] = prefix
50
51 def get_prefixes(self):
52 """Get the IP Prefixes owns by current tenant"""
53
54 return self.prefixes
55
56 def get_device_by_name(self, name):
57 """
58 Find the device or VM which belongs to this Tenant,
59 If the name wasn't specified, return the management server
60 """
61
62 for machine in self.devices + self.vms:
Zack Williamsdac2be42021-08-19 16:14:31 -070063 if (name and machine.name == name) or machine.data["device_role"][
64 "name"
65 ] == "Router":
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +080066 return machine
67
68 ret_msg = (
69 "The name '%s' wasn't found in this tenant, "
70 + "or can't found any Router in this tenant"
71 )
72
73 logger.error(ret_msg, name)
74 sys.exit(1)
75
Zack Williamsdac2be42021-08-19 16:14:31 -070076 def get_devices(self, device_types=None):
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +080077 """
78 Get all devices (Router + Server) belong to this Tenant
79 """
Zack Williamsdac2be42021-08-19 16:14:31 -070080 if not device_types:
81 device_types = ["server", "router"]
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +080082
83 if not device_types:
84 return self.devices + self.vms
85
86 ret = []
87
88 for machine in self.devices:
89 if machine.data.device_role.slug in device_types:
90 ret.append(machine)
91
92 for vm in self.vms:
93 if vm.data.role.slug in device_types:
94 ret.append(vm)
95
96 return ret