-
Notifications
You must be signed in to change notification settings - Fork 18
/
yanet-announcer.py
executable file
·546 lines (436 loc) · 17.3 KB
/
yanet-announcer.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import functools
import json
import logging
import signal
import subprocess
import ipaddress
import textwrap
import time
import typing
from collections import abc
CONFIGURATION_PATH: str = "/etc/yanet/announcer.conf"
MACHINE_TARGET_PATH: str = "/etc/yanet/target"
ANNOUNCER_CONFIG: typing.Any = None
LOGGER: typing.Optional[logging.Logger] = None
OPTIONS: typing.Optional[argparse.Namespace] = None
SIGNAL_RECV: bool = False
SKIP_CHECKS_ALL_KEYWORD: str = "all"
SKIP_CHECKS_CONFIG_PARAM: str = "skip_checks"
class Decorator:
"""Class with static decorators."""
@staticmethod
def skip_function(return_value: typing.Any = None):
"""Decorator skips func execution for passed names in args."""
def decorator(func: typing.Callable):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if func.__name__ in OPTIONS.skip or SKIP_CHECKS_ALL_KEYWORD in OPTIONS.skip:
LOGGER.debug("skip func execution: %s", func.__name__)
return return_value
return func(*args, **kwargs)
return wrapper
return decorator
@staticmethod
def logger_function(func: typing.Callable):
"""Decorator logs func args."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
if OPTIONS.dry_run:
LOGGER.debug("func call %s(%s, %s)", func.__name__, args, kwargs)
return func(*args, **kwargs)
return wrapper
class Executer:
"""Class that allow to execute commands."""
@staticmethod
@functools.lru_cache(maxsize=128)
def get(command: str) -> typing.List[typing.Dict[str, str]]:
"""Execute and parse output."""
# don't use generator output, because LRU cache return wrong response
parsed_output: typing.List[typing.Dict[str, str]] = []
out = subprocess.check_output(command, shell=True, stderr=subprocess.DEVNULL).decode("ascii").splitlines()
if len(out) <= 1:
return parsed_output
column_lengths: typing.List[int] = [len(column) for column in out[1].split(" ")]
offset = 0
headers = []
for i in range(0, len(column_lengths)):
headers.append(out[0][offset : offset + column_lengths[i]].strip())
offset += column_lengths[i] + 2
for row_i in range(2, len(out)):
offset = 0
columns: typing.Dict[str, str] = {}
for i in range(0, len(column_lengths)):
columns[headers[i]] = out[row_i][offset : offset + column_lengths[i]].strip()
offset += column_lengths[i] + 2
parsed_output.append(columns)
return parsed_output
@staticmethod
def flush_cache() -> None:
Executer.get.cache_clear()
@staticmethod
def run(command: str) -> int:
"""Execute and return exit code."""
proc = subprocess.run(command, shell=True)
return proc.returncode
def bgp_update_ipv4(prefix):
LOGGER.info("bgp_update_ipv4: %s", prefix)
if prefix not in ANNOUNCER_CONFIG:
return
for command in ANNOUNCER_CONFIG[prefix]["update"]:
LOGGER.info(command)
if not OPTIONS.dry_run:
Executer.run(command)
def bgp_remove_ipv4(prefix):
LOGGER.info("bgp_remove_ipv4: %s", prefix)
if prefix not in ANNOUNCER_CONFIG:
return
for command in ANNOUNCER_CONFIG[prefix]["remove"]:
LOGGER.info(command)
if not OPTIONS.dry_run:
Executer.run(command)
def bgp_update_ipv6(prefix):
LOGGER.info("bgp_update_ipv6: %s", prefix)
if prefix not in ANNOUNCER_CONFIG:
return
for command in ANNOUNCER_CONFIG[prefix]["update"]:
LOGGER.info(command)
if not OPTIONS.dry_run:
Executer.run(command)
def bgp_remove_ipv6(prefix):
LOGGER.info("bgp_remove_ipv6: %s", prefix)
if prefix not in ANNOUNCER_CONFIG:
return
for command in ANNOUNCER_CONFIG[prefix]["remove"]:
LOGGER.info(command)
if not OPTIONS.dry_run:
Executer.run(command)
def bgp_update(prefix_list):
for prefix in prefix_list:
try:
parsed = ipaddress.ip_network(prefix)
if parsed.version == 6:
bgp_update_ipv6(prefix)
else:
bgp_update_ipv4(prefix)
except Exception as error:
if "firewall" in prefix:
bgp_update_ipv6(prefix)
LOGGER.info("Update bgp with custom prefix: %s", prefix)
else:
LOGGER.error("Can not update bgp prefix: %s with error: %s", prefix, error)
def bgp_remove(prefix_list):
for prefix in prefix_list:
try:
parsed = ipaddress.ip_network(prefix)
if parsed.version == 6:
bgp_remove_ipv6(prefix)
else:
bgp_remove_ipv4(prefix)
except Exception as error:
if "firewall" in prefix:
bgp_remove_ipv6(prefix)
LOGGER.info("Remove bgp with custom prefix: %s", prefix)
else:
LOGGER.error("Can not remove bgp prefix: %s with error: %s", prefix, error)
def get_announces(types):
for type in types:
table_decap = Executer.get(f"yanet-cli {type}")
table_decap_announce = Executer.get(f"yanet-cli {type} announce")
for table_decap_row in table_decap:
module = table_decap_row["module"]
next_module = table_decap_row["next_module"]
announces = []
for table_decap_announce_row in table_decap_announce:
if table_decap_announce_row["module"] != module:
continue
if table_decap_announce_row["announces"] == "n/s":
continue
announces.extend(table_decap_announce_row["announces"].split(","))
yield {"module": module, "type": type, "announces": announces, "next_module": next_module}
@Decorator.logger_function
@Decorator.skip_function()
def check_services():
# Example
"""
~ yanet-cli version
application version revision hash custom
------------ ------- -------- -------- --------------
dataplane 0.0 0 00000000 develop
controlplane 0.0 0 00000000 develop
cli 0.0 0 00000000 develop
"""
LOGGER.info("Checking dataplane/contorlplane...")
try:
lines = Executer.get("/usr/bin/yanet-cli version")
application = set()
for line in lines:
application.add(line.get("application"))
if application != {"cli", "controlplane", "dataplane"}:
raise Exception("main services(dataplane, controlplane) not running")
LOGGER.info("Dataplane/controlplane is in running state!")
except:
raise Exception("Can not get version from yanet-cli.")
@Decorator.logger_function
@Decorator.skip_function()
def check_rib(rib_table: str) -> None:
runtime_rib_table = Executer.get("yanet-cli rib")
if len(runtime_rib_table) < 1:
raise Exception(f"check_rib('{rib_table}')")
for row in runtime_rib_table:
if row["table_name"] == rib_table:
return
raise Exception(f"check_rib('{rib_table}')")
@Decorator.logger_function
@Decorator.skip_function()
def check_default_v4(route):
interfaces = Executer.get("yanet-cli route interface")
routes = Executer.get(f"yanet-cli route get {route} 0.0.0.0/0")
for route_row in routes:
for interface_row in interfaces:
if interface_row["module"] != route:
continue
if route_row["egress_interface"] == interface_row["interface"]:
return
raise Exception(f"check_default_v4('{route}')")
@Decorator.logger_function
@Decorator.skip_function()
def check_default_v6(route):
interfaces = Executer.get("yanet-cli route interface")
routes = Executer.get(f"yanet-cli route get {route} ::/0")
for route_row in routes:
for interface_row in interfaces:
if interface_row["module"] != route:
continue
if route_row["egress_interface"] == interface_row["interface"]:
return
raise Exception(f"check_default_v6('{route}')")
@Decorator.logger_function
@Decorator.skip_function()
def check_neighbor_v4(address_row, neighbors):
for neighbor_row in neighbors:
if (
address_row["module"] == neighbor_row["route_name"]
and address_row["interface"] == neighbor_row["interface_name"]
and address_row["neighbor_v4"] == neighbor_row["ip_address"]
):
return True
return False
@Decorator.logger_function
@Decorator.skip_function()
def check_neighbor_v6(address_row, neighbors):
for neighbor_row in neighbors:
if (
address_row["module"] == neighbor_row["route_name"]
and address_row["interface"] == neighbor_row["interface_name"]
and address_row["neighbor_v6"] == neighbor_row["ip_address"]
):
return True
return False
@Decorator.logger_function
@Decorator.skip_function()
def check_interfaces_neighbor_v4():
interfaces = Executer.get("yanet-cli route interface")
neighbors = Executer.get("yanet-cli neighbor show")
for row in interfaces:
if row["neighbor_v4"] != "n/s":
if not check_neighbor_v4(row, neighbors):
raise Exception(f"check_interfaces_neighbor_v4(): {row}")
return
@Decorator.logger_function
@Decorator.skip_function()
def check_interfaces_neighbor_v6():
interfaces = Executer.get("yanet-cli route interface")
neighbors = Executer.get("yanet-cli neighbor show")
for row in interfaces:
if row["neighbor_v6"] != "n/s":
if not check_neighbor_v6(row, neighbors):
raise Exception(f"check_interfaces_neighbor_v6(): {row}")
return
@Decorator.logger_function
@Decorator.skip_function(return_value=True)
def check_module(module):
try:
check_services()
if module["type"] == "tun64":
check_rib("ipv4 unicast")
check_rib("ipv6 unicast")
if module["next_module"].endswith(":tunnel"):
check_default_v4(module["next_module"][:-7])
check_default_v6(module["next_module"][:-7])
else:
check_default_v4(module["next_module"])
check_default_v6(module["next_module"])
check_interfaces_neighbor_v4()
check_interfaces_neighbor_v6()
elif module["type"] == "nat64stateful":
check_rib("ipv4 unicast")
check_rib("ipv6 unicast")
if module["next_module"].endswith(":tunnel"):
check_default_v4(module["next_module"][:-7])
check_default_v6(module["next_module"][:-7])
else:
check_default_v4(module["next_module"])
check_default_v6(module["next_module"])
check_interfaces_neighbor_v4()
check_interfaces_neighbor_v6()
elif module["type"] == "decap":
if module["next_module"].endswith(":tunnel"):
check_rib("ipv4 unicast")
check_rib("ipv6 unicast")
check_default_v4(module["next_module"][:-7])
check_default_v6(module["next_module"][:-7])
check_interfaces_neighbor_v4()
check_interfaces_neighbor_v6()
else:
check_rib("ipv4 unicast")
check_default_v4(module["next_module"])
check_interfaces_neighbor_v4()
elif module["type"] == "nat64stateless":
check_rib("ipv4 unicast")
check_rib("ipv6 unicast")
if module["next_module"].endswith(":tunnel"):
check_default_v4(module["next_module"][:-7])
check_default_v6(module["next_module"][:-7])
else:
check_default_v4(module["next_module"])
check_default_v6(module["next_module"])
check_interfaces_neighbor_v4()
check_interfaces_neighbor_v6()
elif module["type"] == "dregress":
check_rib("ipv4 unicast")
check_rib("ipv6 unicast")
check_default_v4(module["next_module"])
check_default_v6(module["next_module"])
check_interfaces_neighbor_v4()
check_interfaces_neighbor_v6()
elif module["type"] == "balancer":
check_rib("ipv6 unicast")
check_default_v6(module["next_module"])
check_interfaces_neighbor_v6()
elif module["type"] == "firewall":
check_rib("ipv6 unicast")
check_default_v6(module["next_module"])
check_interfaces_neighbor_v6()
except Exception as error:
if OPTIONS.dry_run:
LOGGER.error("Fail: %s", error)
return False
return True
@Decorator.logger_function
@Decorator.skip_function(return_value=True)
def check_firewall_module():
"""Wrapper for firewall check module: allow to skip only firewall check."""
firewall_module_definition: typing.Dict[str, str] = {
"module": "firewall",
"type": "firewall",
"next_module": "route0",
}
return check_module(firewall_module_definition)
def signal_handler(signum, frame):
global SIGNAL_RECV
SIGNAL_RECV = True
def init_logger():
global LOGGER
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.INFO)
formatter = logging.Formatter("%(filename)s:%(lineno)s - %(levelname)s - %(message)s")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
LOGGER.addHandler(handler)
def parse_args():
global OPTIONS
parser = argparse.ArgumentParser(description="YANET announcer", formatter_class=argparse.RawTextHelpFormatter)
run_mode_group = parser.add_mutually_exclusive_group(required=True)
run_mode_group.add_argument(
"-r", "--run", action="store_true", default=False, dest="daemon", help="run as a daemon"
)
run_mode_group.add_argument(
"-t", "--test", action="store_true", default=False, dest="dry_run", help="dry-run one time execution"
)
parser.add_argument(
"-s",
"--skip",
type=str,
nargs="*",
default=[],
dest="skip",
help=textwrap.dedent(
f"skipped checks names (keyword '{SKIP_CHECKS_ALL_KEYWORD}' disables all checks).\n"
f"Option may be overridden with configuration '{SKIP_CHECKS_CONFIG_PARAM}' param."
),
)
OPTIONS = parser.parse_args()
def update_config():
global ANNOUNCER_CONFIG
global OPTIONS
with open(CONFIGURATION_PATH) as f:
ANNOUNCER_CONFIG = json.load(f)
# Use skip checks for skip flag rewrite opts.
# "pop" using for back compatibility with previous format,
# where ANNOUNCER_CONFIG contains only prefixes
config_skip_checks: typing.Iterable[str] = ANNOUNCER_CONFIG.pop(SKIP_CHECKS_CONFIG_PARAM, [])
if config_skip_checks and isinstance(config_skip_checks, abc.Iterable):
OPTIONS.skip = config_skip_checks
def main():
init_logger()
parse_args()
if OPTIONS.daemon:
signal.signal(signal.SIGTERM, signal_handler)
current_prefixes = []
report_config_counter: int = 0
report_getannounces_counter: int = 0
is_firewall_machine: bool = False
try:
with open(MACHINE_TARGET_PATH, "r", encoding="UTF-8") as file:
line = file.readline().rstrip()
if "firewall" in line:
is_firewall_machine = True
except Exception as error:
LOGGER.error("Failed to read target file: %s", error)
while True:
Executer.flush_cache()
prefixes: typing.List[str] = []
try:
update_config()
report_config_counter = 0
except Exception as error:
if report_config_counter == 0:
LOGGER.error("Fail: %s", error)
report_config_counter = 1
time.sleep(1)
continue
try:
for module in get_announces(["decap", "nat64stateless", "dregress", "balancer", "tun64", "nat64stateful"]):
if OPTIONS.dry_run:
LOGGER.info(module)
if check_module(module):
prefixes.extend(module["announces"])
report_getannounces_counter = 0
except Exception as error:
if report_getannounces_counter == 0:
LOGGER.error("Can not get announces with error: %s", error)
report_getannounces_counter = 1
if len(current_prefixes) > 0:
LOGGER.warning(
"Problem with get_announce(dp/cp in down state?), remove current announces: %s", current_prefixes
)
bgp_remove(current_prefixes)
current_prefixes = []
continue
if is_firewall_machine and check_firewall_module():
prefixes.extend(["firewall::/128"])
bgp_update(list(set(prefixes) - set(current_prefixes)))
bgp_remove(list(set(current_prefixes) - set(prefixes)))
if not OPTIONS.daemon:
return
current_prefixes = prefixes
if SIGNAL_RECV:
LOGGER.warning("Detect SIGNAL_RECV, remove announces and exit...")
bgp_remove(current_prefixes)
return
time.sleep(1)
if __name__ == "__main__":
main()