Skip to content

Handle netbox api cache more gracefully #1111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 21 additions & 21 deletions plugins/inventory/nb_inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -1491,33 +1491,33 @@ def wrapper():

def fetch_api_docs(self):
try:
status = self._fetch_information(self.api_endpoint + "/api/status")
netbox_api_version = ".".join(status["netbox-version"].split(".")[:2])
except Exception:
netbox_api_version = 0

tmp_dir = os.path.split(DEFAULT_LOCAL_TMP)[0]
tmp_file = os.path.join(tmp_dir, "netbox_api_dump.json")

try:
tmp_dir = os.path.split(DEFAULT_LOCAL_TMP)[0]
tmp_file = os.path.join(tmp_dir, "netbox_api_dump.json")
with open(tmp_file) as file:
openapi = json.load(file)
cache = json.load(file)
cached_api_version = ".".join(cache["info"]["version"].split(".")[:2])
except Exception:
openapi = {}
cached_api_version = None
cache = None

cached_api_version = openapi.get("info", {}).get("version")
if cached_api_version:
cached_api_version = ".".join(cached_api_version.split(".")[:2])
status = self._fetch_information(self.api_endpoint + "/api/status")
netbox_api_version = ".".join(status["netbox-version"].split(".")[:2])

if netbox_api_version != cached_api_version:
if version.parse(netbox_api_version) >= version.parse("3.5.0"):
endpoint_url = self.api_endpoint + "/api/schema/?format=json"
else:
endpoint_url = self.api_endpoint + "/api/docs/?format=openapi"
if version.parse(netbox_api_version) >= version.parse("3.5.0"):
endpoint_url = self.api_endpoint + "/api/schema/?format=json"
else:
endpoint_url = self.api_endpoint + "/api/docs/?format=openapi"

if cache and cached_api_version == netbox_api_version:
openapi = cache
else:
openapi = self._fetch_information(endpoint_url)
with open(tmp_file, "w") as file:
json.dump(openapi, file)

try:
with open(tmp_file, "w") as file:
json.dump(openapi, file)
except Exception:
pass

self.api_version = version.parse(netbox_api_version)

Expand Down