blob: 4d529a78f1d2957abc74c869c0cf8c125317c38a [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
9from .utils import logger, netboxapi
10from .device import Device, VirtualMachine
11from .network import Prefix
12
13
14class Tenant:
15 def __init__(self):
16
17 from .utils import netboxapi, netbox_config
18
19 self.nbapi = netboxapi
20 self.name = netbox_config["tenant_name"]
21 self.name_segments = netbox_config.get("prefix_segments", 1)
22
23 self.tenant = self.nbapi.tenancy.tenants.get(name=self.name)
24
25 # Tenant only keep the resources which owns by it
26 self.devices = list()
27 self.vms = list()
28 self.prefixes = dict()
29
30 # Get the Device and Virtual Machines from Netbox API
31 for device_data in self.nbapi.dcim.devices.filter(tenant=self.tenant.slug):
32 device = Device(device_data)
33 device.tenant = self
34 self.devices.append(device)
35
36 for vm_data in self.nbapi.virtualization.virtual_machines.filter(
37 tenant=self.tenant.slug
38 ):
39 vm = VirtualMachine(vm_data)
40 vm.tenant = self
41 self.vms.append(vm)
42
43 vrf = self.nbapi.ipam.vrfs.get(tenant=self.tenant.slug)
44 for prefix_data in self.nbapi.ipam.prefixes.filter(vrf_id=vrf.id):
45 prefix = Prefix(prefix_data, self.name_segments)
46 if prefix_data.description:
47 self.prefixes[prefix_data.prefix] = prefix
48
49 def get_prefixes(self):
50 """Get the IP Prefixes owns by current tenant"""
51
52 return self.prefixes
53
54 def get_device_by_name(self, name):
55 """
56 Find the device or VM which belongs to this Tenant,
57 If the name wasn't specified, return the management server
58 """
59
60 for machine in self.devices + self.vms:
61 if name and machine.name == name:
62 return machine
63 elif machine.data["device_role"]["name"] == "Router":
64 return machine
65
66 ret_msg = (
67 "The name '%s' wasn't found in this tenant, "
68 + "or can't found any Router in this tenant"
69 )
70
71 logger.error(ret_msg, name)
72 sys.exit(1)
73
74 def get_devices(self, device_types=["server", "router"]):
75 """
76 Get all devices (Router + Server) belong to this Tenant
77 """
78
79 if not device_types:
80 return self.devices + self.vms
81
82 ret = []
83
84 for machine in self.devices:
85 if machine.data.device_role.slug in device_types:
86 ret.append(machine)
87
88 for vm in self.vms:
89 if vm.data.role.slug in device_types:
90 ret.append(vm)
91
92 return ret