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

202 lines
6.6 KiB
Python
Raw Normal View History

"""Construct SSH command/API parameters from validated query data.
2019-07-07 23:28:23 -07:00
Accepts filtered & validated input from execute.py, constructs SSH
command for Netmiko library or API call parameters for supported
hyperglass API modules.
"""
2020-02-03 02:35:11 -07:00
# Standard Library
import re
2020-04-12 02:17:16 -07:00
import json as _json
2020-05-29 17:47:53 -07:00
from operator import attrgetter
2019-06-10 12:22:38 -07:00
2020-02-03 02:35:11 -07:00
# Project
2020-04-14 10:24:20 -07:00
from hyperglass.log import log
from hyperglass.constants import TRANSPORT_REST, TARGET_FORMAT_SPACE
2020-02-03 02:35:11 -07:00
from hyperglass.configuration import commands
class Construct:
"""Construct SSH commands/REST API parameters from validated query data."""
2020-01-31 02:06:27 -10:00
def __init__(self, device, query_data):
"""Initialize command construction."""
2019-09-25 22:40:02 -07:00
log.debug(
2020-09-28 12:37:44 -07:00
"Constructing {} query for '{}'",
query_data.query_type,
str(query_data.query_target),
)
2020-01-31 02:06:27 -10:00
self.device = device
self.query_data = query_data
2020-03-24 18:36:04 -07:00
self.target = self.query_data.query_target
2019-09-09 00:18:01 -07:00
2020-01-31 02:06:27 -10:00
# Set transport method based on NOS type
self.transport = "scrape"
if self.device.nos in TRANSPORT_REST:
self.transport = "rest"
2019-12-31 13:30:55 -07:00
2020-01-31 02:06:27 -10:00
# Remove slashes from target for required platforms
if self.device.nos in TARGET_FORMAT_SPACE:
2020-03-24 18:36:04 -07:00
self.target = re.sub(r"\/", r" ", str(self.query_data.query_target))
2019-09-09 00:18:01 -07:00
2020-01-31 02:06:27 -10:00
# Set AFIs for based on query type
if self.query_data.query_type in ("bgp_route", "ping", "traceroute"):
2020-03-24 18:36:04 -07:00
# For IP queries, AFIs are enabled (not null/None) VRF -> AFI definitions
# where the IP version matches the IP version of the target.
2020-01-31 02:06:27 -10:00
self.afis = [
v
for v in (
self.query_data.query_vrf.ipv4,
self.query_data.query_vrf.ipv6,
2019-09-30 07:51:17 -07:00
)
2020-01-31 02:06:27 -10:00
if v is not None and self.query_data.query_target.version == v.version
]
elif self.query_data.query_type in ("bgp_aspath", "bgp_community"):
2020-03-24 18:36:04 -07:00
# For AS Path/Community queries, AFIs are just enabled VRF -> AFI
# definitions, no IP version checking is performed (since there is no IP).
2020-01-31 02:06:27 -10:00
self.afis = [
v
for v in (
self.query_data.query_vrf.ipv4,
self.query_data.query_vrf.ipv6,
2019-09-30 07:51:17 -07:00
)
2020-01-31 02:06:27 -10:00
if v is not None
]
with Formatter(self.device.nos, self.query_data.query_type) as formatter:
self.target = formatter(self.query_data.query_target)
2020-04-12 02:17:16 -07:00
2020-01-31 02:06:27 -10:00
def json(self, afi):
"""Return JSON version of validated query for REST devices."""
2020-01-31 02:06:27 -10:00
log.debug("Building JSON query for {q}", q=repr(self.query_data))
2020-04-12 02:17:16 -07:00
return _json.dumps(
2020-01-31 02:06:27 -10:00
{
"query_type": self.query_data.query_type,
"vrf": self.query_data.query_vrf.name,
"afi": afi.protocol,
"source": str(afi.source_address),
2020-03-24 18:36:04 -07:00
"target": str(self.target),
2020-01-31 02:06:27 -10:00
}
)
2019-09-09 00:18:01 -07:00
2020-01-31 02:06:27 -10:00
def scrape(self, afi):
"""Return formatted command for 'Scrape' endpoints (SSH)."""
2020-05-29 17:47:53 -07:00
if self.device.structured_output:
cmd_paths = (
self.device.nos,
"structured",
afi.protocol,
self.query_data.query_type,
)
else:
cmd_paths = (self.device.commands, afi.protocol, self.query_data.query_type)
2020-05-29 17:47:53 -07:00
command = attrgetter(".".join(cmd_paths))(commands)
2020-01-31 02:06:27 -10:00
return command.format(
2020-03-24 18:36:04 -07:00
target=self.target,
2020-01-31 02:06:27 -10:00
source=str(afi.source_address),
vrf=self.query_data.query_vrf.name,
)
2019-09-09 00:18:01 -07:00
2020-01-31 02:06:27 -10:00
def queries(self):
"""Return queries for each enabled AFI."""
query = []
2020-01-31 02:06:27 -10:00
for afi in self.afis:
if self.transport == "rest":
2020-01-31 02:06:27 -10:00
query.append(self.json(afi=afi))
else:
query.append(self.scrape(afi=afi))
2019-09-09 00:18:01 -07:00
2020-09-28 12:37:44 -07:00
log.debug("Constructed query: {}", query)
return query
class Formatter:
"""Modify query target based on the device's NOS requirements and the query type."""
def __init__(self, nos: str, query_type: str) -> None:
"""Initialize target formatting."""
self.nos = nos
self.query_type = query_type
def __enter__(self):
"""Get the relevant formatter."""
return self._get_formatter()
def __exit__(self, exc_type, exc_value, exc_traceback):
"""Handle context exit."""
if exc_type is not None:
log.error(exc_traceback)
pass
def _get_formatter(self):
if self.nos in ("juniper", "juniper_junos"):
if self.query_type == "bgp_aspath":
return self._juniper_bgp_aspath
if self.nos in ("bird", "bird_ssh"):
if self.query_type == "bgp_aspath":
return self._bird_bgp_aspath
elif self.query_type == "bgp_community":
return self._bird_bgp_community
return self._default
def _default(self, target: str) -> str:
"""Don't format targets by default."""
return target
def _juniper_bgp_aspath(self, target: str) -> str:
"""Convert from Cisco AS_PATH format to Juniper format."""
query = str(target)
asns = re.findall(r"\d+", query)
was_modified = False
if bool(re.match(r"^\_", query)):
# Replace `_65000` with `.* 65000`
asns.insert(0, r".*")
was_modified = True
if bool(re.match(r".*(\_)$", query)):
# Replace `65000_` with `65000 .*`
asns.append(r".*")
was_modified = True
if was_modified:
modified = " ".join(asns)
log.debug("Modified target '{}' to '{}'", target, modified)
return modified
return query
def _bird_bgp_aspath(self, target: str) -> str:
"""Convert from Cisco AS_PATH format to BIRD format."""
# Extract ASNs from query target string
asns = re.findall(r"\d+", target)
was_modified = False
if bool(re.match(r"^\_", target)):
# Replace `_65000` with `.* 65000`
asns.insert(0, "*")
was_modified = True
if bool(re.match(r".*(\_)$", target)):
# Replace `65000_` with `65000 .*`
asns.append("*")
was_modified = True
asns.insert(0, "[=")
asns.append("=]")
result = " ".join(asns)
if was_modified:
log.debug("Modified target '{}' to '{}'", target, result)
return result
def _bird_bgp_community(self, target: str) -> str:
"""Convert from standard community format to BIRD format."""
parts = target.split(":")
return f'({",".join(parts)})'