Coverage for birdplan/bird_config/util.py: 100%
23 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-23 03:27 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-23 03:27 +0000
1#
2# SPDX-License-Identifier: GPL-3.0-or-later
3#
4# Copyright (c) 2019-2024, AllWorldIT
5#
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program. If not, see <http://www.gnu.org/licenses/>.
19"""Bird configuration utility functions."""
21import ipaddress
22from typing import List
24__all__ = ["sanitize_community", "sanitize_community_list", "network_count"]
27def sanitize_community(community: str) -> str:
28 """Sanitize a string representation of a large community."""
29 # Split on :
30 community_components = community.split(":")
31 # Re-join using , and add brackets
32 community_str = f'({",".join(community_components)})'
33 return community_str
36def sanitize_community_list(communities: List[str]) -> List[str]:
37 """Sanitize a list of communities."""
39 result = []
40 for community in sorted(communities):
41 result.append(sanitize_community(community))
43 return result
46def network_count(ip_networks: List[str]) -> int:
47 """Get the number of ISP networks within a list of IP networks."""
49 # Loop with the networks we got
50 count = 0
51 for prefix_raw in ip_networks:
52 # Split off possible network size constraints
53 prefix = prefix_raw.split("{", 1)[0]
54 # Grab network object
55 ipnetwork = ipaddress.ip_network(prefix)
56 # Check which IP version this is
57 if ipnetwork.version == 4:
58 # Count how many /24's there are in the ipnetwork
59 prefix_count = ipnetwork.num_addresses >> 8
60 else:
61 # Count approximate number of /48's there are in the ipnetwork
62 prefix_count = ipnetwork.num_addresses >> 80
63 # Add to counter
64 count += prefix_count
66 return count