From f5cb3ddab20949658905504b2ba177343ac05ad4 Mon Sep 17 00:00:00 2001 From: Neda Moeini <neda.moeini@ga0479-nmoeini.home> Date: Mon, 25 Sep 2023 13:11:13 +0200 Subject: [PATCH] Added exception handling for netbox api and improved codebase. --- gso/cli/netbox.py | 6 +----- gso/services/netbox_client.py | 17 ++++++++++++----- gso/utils/device_info.py | 3 +-- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/gso/cli/netbox.py b/gso/cli/netbox.py index ddaa94ff7..97acdcf84 100644 --- a/gso/cli/netbox.py +++ b/gso/cli/netbox.py @@ -17,11 +17,7 @@ def netbox_initial_setup() -> None: typer.echo("Initial setup of NetBox ...") typer.echo("Connecting to NetBox ...") - try: - nbclient = NetBoxClient() - except RequestError as e: - typer.echo(f"Error connecting to NetBox: {e}") - return + nbclient = NetBoxClient() typer.echo("Creating GEANT site ...") try: diff --git a/gso/services/netbox_client.py b/gso/services/netbox_client.py index 964fb6c2b..f22bd4319 100644 --- a/gso/services/netbox_client.py +++ b/gso/services/netbox_client.py @@ -3,11 +3,12 @@ from uuid import UUID import pydantic import pynetbox +from pynetbox import RequestError from pynetbox.models.dcim import Devices, DeviceTypes, Interfaces from gso.products import Router from gso.settings import load_oss_params -from gso.utils.device_info import FEASIBLE_LAG_RANGE, TierInfo +from gso.utils.device_info import FEASIBLE_IP_TRUNK_LAG_RANGE, TierInfo from gso.utils.exceptions import NotFoundError, WorkflowStateError @@ -49,9 +50,15 @@ class NetBoxClient: """Implement all methods to communicate with the NetBox API.""" def __init__(self) -> None: - netbox_params = load_oss_params().NETBOX - self.netbox = pynetbox.api(netbox_params.api, netbox_params.token) - + self.netbox_params = load_oss_params().NETBOX + self.netbox = self._connect() + + def _connect(self): + try: + return pynetbox.api(self.netbox_params.api, self.netbox_params.token) + except RequestError as e: + raise Exception('NetBox API Error', e) + def get_all_devices(self) -> list[Devices]: return list(self.netbox.dcim.devices.all()) @@ -207,7 +214,7 @@ class NetBoxClient: ] # Generate all feasible lags - all_feasible_lags = [f"LAG-{i}" for i in FEASIBLE_LAG_RANGE] + all_feasible_lags = [f"LAG-{i}" for i in FEASIBLE_IP_TRUNK_LAG_RANGE] # Return available lags not assigned to the device return [lag for lag in all_feasible_lags if lag not in lag_interface_names] diff --git a/gso/utils/device_info.py b/gso/utils/device_info.py index c4d09ccb8..1c193557f 100644 --- a/gso/utils/device_info.py +++ b/gso/utils/device_info.py @@ -30,5 +30,4 @@ class TierInfo: return getattr(self, name) -# Ranges of LAGs that are feasible for a given device type. -FEASIBLE_LAG_RANGE = range(1, 11) +FEASIBLE_IP_TRUNK_LAG_RANGE = range(1, 10) -- GitLab