1
0
mirror of https://github.com/checktheroads/hyperglass synced 2024-05-11 05:55:08 +00:00

253 lines
7.9 KiB
Python
Raw Normal View History

2020-01-21 17:27:57 -07:00
"""API Routes."""
2020-02-03 02:34:50 -07:00
# Standard Library
import os
2020-05-29 17:47:53 -07:00
import json
import time
2020-06-26 12:23:11 -07:00
from datetime import datetime
2020-02-03 02:34:50 -07:00
# Third Party
from fastapi import HTTPException, BackgroundTasks
2020-01-21 17:27:57 -07:00
from starlette.requests import Request
2020-02-03 02:34:50 -07:00
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
2020-02-03 02:34:50 -07:00
# Project
2020-04-18 23:18:50 -07:00
from hyperglass.log import log
2020-07-13 01:54:38 -07:00
from hyperglass.cache import AsyncCache
from hyperglass.encode import jwt_decode
from hyperglass.external import Webhook, bgptools
from hyperglass.api.tasks import process_headers, import_public_key
2020-07-17 01:06:19 -07:00
from hyperglass.constants import __version__
from hyperglass.exceptions import HyperglassError
2020-02-03 02:34:50 -07:00
from hyperglass.configuration import REDIS_CONFIG, params, devices
from hyperglass.execution.main import execute
2020-02-03 02:34:50 -07:00
from hyperglass.api.models.query import Query
from hyperglass.api.models.cert_import import EncodedRequest
APP_PATH = os.environ["hyperglass_directory"]
async def send_webhook(query_data: Query, request: Request, timestamp: datetime):
"""If webhooks are enabled, get request info and send a webhook.
2020-04-18 23:18:50 -07:00
Args:
query_data (Query): Valid query
request (Request): Starlette/FastAPI request
2020-04-18 23:18:50 -07:00
Returns:
int: Returns 1 regardless of result
"""
try:
if params.logging.http is not None:
headers = await process_headers(headers=request.headers)
if headers.get("x-real-ip") is not None:
host = headers["x-real-ip"]
elif headers.get("x-forwarded-for") is not None:
host = headers["x-forwarded-for"]
else:
host = request.client.host
network_info = await bgptools.network_info(host)
async with Webhook(params.logging.http) as hook:
await hook.send(
query={
**query_data.export_dict(pretty=True),
"headers": headers,
"source": host,
2020-07-13 01:54:38 -07:00
"network": network_info.get(host, {}),
"timestamp": timestamp,
}
)
except Exception as err:
log.error(
"Error sending webhook to {}: {}", params.logging.http.provider, str(err)
)
2020-04-15 02:12:01 -07:00
async def query(query_data: Query, request: Request, background_tasks: BackgroundTasks):
"""Ingest request data pass it to the backend application to perform the query."""
2020-06-26 12:23:11 -07:00
timestamp = datetime.utcnow()
background_tasks.add_task(send_webhook, query_data, request, timestamp)
2020-04-13 01:05:24 -07:00
# Initialize cache
2020-07-13 01:54:38 -07:00
cache = AsyncCache(db=params.cache.database, **REDIS_CONFIG)
2020-04-13 01:05:24 -07:00
log.debug("Initialized cache {}", repr(cache))
# Use hashed query_data string as key for for k/v cache store so
# each command output value is unique.
2020-01-26 02:15:19 -07:00
cache_key = query_data.digest()
# Define cache entry expiry time
2020-01-28 09:52:54 -07:00
cache_timeout = params.cache.timeout
2020-05-29 17:47:53 -07:00
log.debug(f"Cache Timeout: {cache_timeout}")
2020-04-13 01:05:24 -07:00
log.info(f"Starting query execution for query {query_data.summary}")
2020-04-16 09:30:20 -07:00
2020-04-18 07:58:46 -07:00
cache_response = await cache.get_dict(cache_key, "output")
2020-04-16 23:43:02 -07:00
2020-07-17 01:43:17 -07:00
json_output = False
if query_data.device.structured_output and query_data.query_type in (
"bgp_route",
"bgp_community",
"bgp_aspath",
):
json_output = True
2020-04-16 23:43:02 -07:00
cached = False
if cache_response:
2020-04-19 09:50:52 -07:00
log.debug("Query {q} exists in cache", q=cache_key)
2020-04-16 23:43:02 -07:00
# If a cached response exists, reset the expiration time.
await cache.expire(cache_key, seconds=cache_timeout)
cached = True
runtime = 0
2020-04-18 07:58:46 -07:00
timestamp = await cache.get_dict(cache_key, "timestamp")
2020-04-16 23:43:02 -07:00
elif not cache_response:
2020-04-13 01:05:24 -07:00
log.debug(f"No existing cache entry for query {cache_key}")
log.debug(
f"Created new cache key {cache_key} entry for query {query_data.summary}"
)
2020-04-18 07:58:46 -07:00
timestamp = query_data.timestamp
# Pass request to execution module
starttime = time.time()
cache_output = await execute(query_data)
endtime = time.time()
elapsedtime = round(endtime - starttime, 4)
log.debug(f"Query {cache_key} took {elapsedtime} seconds to run.")
2020-04-18 07:58:46 -07:00
if cache_output is None:
raise HyperglassError(message=params.messages.general, alert="danger")
# Create a cache entry
2020-07-17 01:43:17 -07:00
if json_output:
2020-05-29 17:47:53 -07:00
raw_output = json.dumps(cache_output)
else:
raw_output = str(cache_output)
await cache.set_dict(cache_key, "output", raw_output)
2020-04-18 07:58:46 -07:00
await cache.set_dict(cache_key, "timestamp", timestamp)
2020-04-13 01:05:24 -07:00
await cache.expire(cache_key, seconds=cache_timeout)
log.debug(f"Added cache entry for query: {cache_key}")
2020-04-16 23:43:02 -07:00
runtime = int(round(elapsedtime, 0))
# If it does, return the cached entry
2020-04-18 07:58:46 -07:00
cache_response = await cache.get_dict(cache_key, "output")
2020-07-13 01:54:38 -07:00
response_format = "text/plain"
2020-07-17 01:43:17 -07:00
if json_output:
2020-05-29 17:47:53 -07:00
response_format = "application/json"
2020-04-13 01:05:24 -07:00
log.debug(f"Cache match for {cache_key}:\n {cache_response}")
log.success(f"Completed query execution for {query_data.summary}")
2020-04-16 23:43:02 -07:00
return {
"output": cache_response,
"id": cache_key,
"cached": cached,
"runtime": runtime,
2020-04-18 07:58:46 -07:00
"timestamp": timestamp,
2020-05-29 17:47:53 -07:00
"format": response_format,
2020-04-18 07:58:46 -07:00
"random": query_data.random(),
2020-04-16 23:43:02 -07:00
"level": "success",
"keywords": [],
}
2020-01-21 17:27:57 -07:00
async def import_certificate(encoded_request: EncodedRequest):
"""Import a certificate from hyperglass-agent."""
# Try to match the requested device name with configured devices
2020-07-30 01:30:01 -07:00
try:
matched_device = devices[encoded_request.device]
except AttributeError:
raise HTTPException(
detail=f"Device {str(encoded_request.device)} not found", status_code=404
)
try:
# Decode JSON Web Token
decoded_request = await jwt_decode(
payload=encoded_request.encoded,
secret=matched_device.credential.password.get_secret_value(),
)
except HyperglassError as decode_error:
raise HTTPException(detail=str(decode_error), status_code=401)
try:
# Write certificate to file
import_public_key(
2020-07-30 01:30:01 -07:00
app_path=APP_PATH,
device_name=matched_device.name,
keystring=decoded_request,
)
2020-07-30 01:30:01 -07:00
except RuntimeError as err:
raise HyperglassError(str(err), level="danger")
return {
"output": f"Added public key for {encoded_request.device}",
"level": "success",
"keywords": [encoded_request.device],
}
2020-01-21 17:27:57 -07:00
async def docs():
"""Serve custom docs."""
2020-01-28 08:59:27 -07:00
if params.docs.enable:
2020-01-21 17:27:57 -07:00
docs_func_map = {"swagger": get_swagger_ui_html, "redoc": get_redoc_html}
2020-01-28 08:59:27 -07:00
docs_func = docs_func_map[params.docs.mode]
2020-01-21 17:27:57 -07:00
return docs_func(
2020-01-28 08:59:27 -07:00
openapi_url=params.docs.openapi_url, title=params.site_title + " - API Docs"
2020-01-21 17:27:57 -07:00
)
else:
raise HTTPException(detail="Not found", status_code=404)
2020-02-01 02:24:52 -10:00
async def routers():
"""Serve list of configured routers and attributes."""
return [
d.dict(
include={
"name": ...,
"network": ...,
"display_name": ...,
"vrfs": {-1: {"name", "display_name"}},
}
)
2020-07-30 01:30:01 -07:00
for d in devices.objects
2020-02-01 02:24:52 -10:00
]
2020-04-18 11:34:23 -07:00
async def communities():
"""Serve list of configured communities if mode is select."""
if params.queries.bgp_community.mode != "select":
raise HTTPException(detail="BGP community mode is not select", status_code=404)
return [c.export_dict() for c in params.queries.bgp_community.communities]
2020-02-01 02:24:52 -10:00
async def queries():
"""Serve list of enabled query types."""
return params.queries.list
2020-07-17 01:06:19 -07:00
async def info():
"""Serve general information about this instance of hyperglass."""
return {
"name": params.site_title,
"organization": params.org_name,
"primary_asn": int(params.primary_asn),
"version": f"hyperglass {__version__}",
}
endpoints = [query, docs, routers, info]