-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatic.py
193 lines (161 loc) · 6.77 KB
/
static.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
from typing import Dict, List, Tuple, Any, Optional, Union
from jinja2 import Environment, FileSystemLoader, Template
import os
import subprocess
import logging
# Set up logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
def extract_static_routes(config: Dict[str, Any]) -> List[Tuple[str, str, Optional[str]]]:
"""
Extract static routes from the configuration dictionary.
Args:
config: Configuration dictionary containing protocols and static routes
Returns:
List of tuples containing (prefix, next-hop, distance)
Example:
>>> config = {
... "protocols": {
... "static": {
... "route": {
... "192.168.1.0/24": {
... "next-hop": {
... "10.0.0.1": {"distance": {"1": None}}
... }
... }
... }
... }
... }
... }
>>> extract_static_routes(config)
[('192.168.1.0/24', '10.0.0.1', '1')]
"""
logger.info("Extracting static routes from configuration")
static = config.get("protocols", {}).get("static", {}).get("route", {})
routes: List[Tuple[str, str, Optional[str]]] = []
for prefix, data in static.items():
logger.debug(f"Processing route prefix: {prefix}")
next_hops = data.get("next-hop", {})
for nh, nh_data in next_hops.items():
distance_value = None
if isinstance(nh_data, dict):
distance = nh_data.get("distance")
if isinstance(distance, dict):
# Pick the first (and should be only) distance value
try:
distance_value = next(iter(distance))
except StopIteration:
# Empty distance dictionary, keep distance_value as None
pass
except Exception as e:
logger.warning(f"Error processing distance for route {prefix} - {str(e)}")
routes.append((prefix, nh, distance_value))
logger.info(f"Added route: {prefix} via {nh}" + (f" distance {distance_value}" if distance_value else ""))
logger.info(f"Extracted {len(routes)} static routes")
return routes
def generate_static_routes_config(config_dict: Dict[str, Any]) -> str:
"""
Generate FRR configuration for static routes.
Args:
config_dict: Configuration dictionary containing static routes
Returns:
String containing the rendered FRR configuration
Raises:
FileNotFoundError: If the template file is not found
jinja2.exceptions.TemplateNotFound: If the template cannot be loaded
"""
logger.info("Generating FRR configuration for static routes")
routes = extract_static_routes(config_dict)
template_dir = os.path.dirname(os.path.abspath(__file__))
logger.debug(f"Using template directory: {template_dir}")
env = Environment(
loader=FileSystemLoader(template_dir),
trim_blocks=True,
lstrip_blocks=True
)
try:
template = env.get_template("frr.conf.j2")
config = template.render(static_routes=routes)
logger.info("Successfully generated FRR configuration")
logger.debug(f"Generated configuration:\n{config}")
return config
except Exception as e:
logger.error(f"Error generating FRR configuration: {str(e)}")
return "" # Return empty string on error
def apply_config(config_dict: Dict[str, Any]) -> bool:
"""
Apply static routes configuration to the system.
Args:
config_dict: Configuration dictionary containing static routes
Returns:
bool: True if configuration was applied successfully, False otherwise
"""
logger.info("Applying static routes configuration")
try:
# Generate FRR configuration
frr_config = generate_static_routes_config(config_dict)
if not frr_config:
logger.error("No static routes configuration generated")
return False
# Write configuration to temporary file
temp_file = "/tmp/frr_static_routes.conf"
logger.debug(f"Writing configuration to temporary file: {temp_file}")
with open(temp_file, "w") as f:
f.write(frr_config)
# Apply configuration using vtysh
logger.info("Applying configuration using vtysh")
result = subprocess.run(
["vtysh", "-f", temp_file],
capture_output=True,
text=True,
check=True
)
# Clean up temporary file
os.remove(temp_file)
logger.debug("Removed temporary configuration file")
if result.returncode == 0:
logger.info("Static routes configuration applied successfully")
return True
else:
logger.error(f"Error applying static routes configuration: {result.stderr}")
return False
except subprocess.CalledProcessError as e:
logger.error(f"Error executing vtysh command: {e.stderr}")
return False
except Exception as e:
logger.error(f"Error applying static routes configuration: {str(e)}")
return False
def validate_config(config_dict: Dict[str, Any]) -> bool:
"""
Validate the static routes configuration.
Args:
config_dict: Configuration dictionary containing static routes
Returns:
bool: True if configuration is valid, False otherwise
"""
logger.info("Validating static routes configuration")
try:
routes = extract_static_routes(config_dict)
if not routes:
logger.warning("No static routes found in configuration")
return False
for prefix, next_hop, distance in routes:
# Basic validation of prefix format
if '/' not in prefix:
logger.error(f"Invalid prefix format: {prefix}")
return False
# Basic validation of next-hop format
if not next_hop or next_hop.count('.') != 3:
logger.error(f"Invalid next-hop format: {next_hop}")
return False
# Validate distance if present
if distance and not distance.isdigit():
logger.error(f"Invalid distance value: {distance}")
return False
logger.info("Static routes configuration validation successful")
return True
except Exception as e:
logger.error(f"Error validating static routes configuration: {str(e)}")
return False