|
| 1 | +""" |
| 2 | +An API to obtain data from Nautobot, and format it for use in various external |
| 3 | +systems |
| 4 | +""" |
| 5 | + |
| 6 | +# Standard Library |
| 7 | + |
| 8 | +# Third Party |
| 9 | +from fastapi import FastAPI |
| 10 | +from fastapi import Request |
| 11 | +from fastapi.responses import JSONResponse |
| 12 | + |
| 13 | +# First Party |
| 14 | +from helpers.graphql import query_nautobot_graphql |
| 15 | +from helpers.queries import OOB_TARGET_QUERY |
| 16 | +from helpers.schemas import TargetResponse |
| 17 | + |
| 18 | +app = FastAPI() |
| 19 | + |
| 20 | + |
| 21 | +@app.exception_handler(Exception) |
| 22 | +async def validation_exception_handler(request: Request, exc: Exception): |
| 23 | + """ |
| 24 | + Generic catchall for exception handling |
| 25 | + """ |
| 26 | + return JSONResponse( |
| 27 | + status_code=500, |
| 28 | + content={ |
| 29 | + "error": True, |
| 30 | + "path": str(request.url), |
| 31 | + "detail": f"Exception message is {exc!r}.", |
| 32 | + }, |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +@app.get("/targets/oob") |
| 37 | +def get_oob_targets() -> list[TargetResponse]: |
| 38 | + """ |
| 39 | + Obtains a list of targets to monitor from Nautobot, and returns them in a |
| 40 | + format that can be read by the Prometheus `http_sd_config` method. |
| 41 | + """ |
| 42 | + response = query_nautobot_graphql(OOB_TARGET_QUERY).json() |
| 43 | + res = [] |
| 44 | + for interface in response["data"]["interfaces"]: |
| 45 | + for device in interface["ip_addresses"]: |
| 46 | + urn = interface["device"].get("cpf_urn") |
| 47 | + # Only return devices which contain a urn. |
| 48 | + if not urn: |
| 49 | + continue |
| 50 | + device_name = interface["device"]["name"] |
| 51 | + device_uuid = interface["device"]["id"] |
| 52 | + location = interface["device"]["location"]["name"] |
| 53 | + rack = interface["device"]["rack"]["name"] |
| 54 | + res.append( |
| 55 | + { |
| 56 | + "targets": [device["host"]], |
| 57 | + "labels": { |
| 58 | + "device_name": device_name, |
| 59 | + "uuid": device_uuid, |
| 60 | + "location": location, |
| 61 | + "rack": rack, |
| 62 | + "urn": urn, |
| 63 | + }, |
| 64 | + } |
| 65 | + ) |
| 66 | + return res |
0 commit comments