import pybgpstream
import collections
import time # To potentially show progress or time execution
def get_origin_as(as_path_str: str) -> int | None:
"""
Extracts the origin AS (the rightmost AS) from an AS path string.
Handles basic cases and ignores paths ending in AS sets or invalid segments.
"""
if not as_path_str:
return None
segments = as_path_str.strip().split()
if not segments:
return None
# Iterate backwards to find the first valid AS number (handles prepending)
for i in range(len(segments) - 1, -1, -1):
segment = segments[i]
# Basic check to skip AS sets like {123,456} or lists
if '{' in segment or ',' in segment or '[' in segment:
continue # Move to the next segment to the left
try:
origin_as = int(segment)
# Check for valid ASNs (e.g., non-zero, potentially within range)
if origin_as > 0:
return origin_as
else:
# Found a zero or negative number, might indicate an issue
# Continue searching left in case of prepended 0s etc.
continue
except ValueError:
# Segment is not a simple integer (could be confederation, etc.)
# Continue searching left
continue
return None # No valid origin AS found in the path segments
def top_10_ases_by_prefix_growth(rib_files: list[str]) -> list[tuple[int, float]]:
"""
Calculates the percentage growth in advertised prefixes for each AS over
the timespan represented by the chronologically sorted list of RIB files.
Args:
rib_files: A chronologically sorted list of absolute path names to RIB dump files.
Returns:
A list of tuples, where each tuple contains (AS number, percentage growth),
sorted in descending order of growth percentage, limited to the top 10.
Returns an empty list if no valid data is processed or no growth is found.
"""
if not rib_files:
print("Warning: No RIB files provided.")
return []
print(f"Processing {len(rib_files)} RIB files...")
# Dictionary to store the first and last observed prefix counts for each AS
# format: {asn: {'first_count': count, 'first_time': timestamp,
# 'last_count': count, 'last_time': timestamp}}
as_prefix_data = collections.defaultdict(lambda: {'first_count': -1, 'first_time': -1,
'last_count': -1, 'last_time': -1})
# Dictionary to store unique prefixes per AS for the *current* snapshot being processed
# format: {asn: set(prefixes)}
current_snapshot_prefixes = collections.defaultdict(set)
current_snapshot_time = -1
processed_snapshots = 0
start_time = time.time()
# --- PyBGPStream Setup ---
stream = pybgpstream.BGPStream()
# Set the data interface to 'rib-file'
# The option key is 'rib-file' and the value is the path
for rib_file in rib_files:
stream.add_data_interface_option("rib-file", rib_file)
#print(f"Added RIB file: {rib_file}") # Optional: for debugging
# Filter for RIB entries only
stream.add_filter('record-type', 'ribs')
# We want data from all peers in the RIBs
# stream.add_filter('peer-asn', str(peer_asn), 'filter') # Not needed here
# No time interval filter needed, process all records in the files
# stream.add_interval_filter(start_ts, end_ts)
# --- Processing Loop ---
try:
print("Starting BGPStream processing...")
rec_count = 0
elem_count = 0
for rec in stream.records():
rec_count += 1
# Process RIB entries within the record
# Note: A single record often corresponds to a single RIB dump file
# but we should handle based on element time for robustness.
current_rec_time = rec.time # Use record time as snapshot time
# Clear previous snapshot data before processing elements of the new record
# We assume each file/record represents a distinct snapshot time point.
# If a single file could contain multiple timestamps, logic needs adjustment.
# Process the *previous* snapshot's data if the time has changed
if current_snapshot_time != -1 and current_rec_time != current_snapshot_time:
print(f"Processing snapshot from time {current_snapshot_time}...")
for asn, prefixes in current_snapshot_prefixes.items():
count = len(prefixes)
if asn not in as_prefix_data:
# First time seeing this AS
as_prefix_data[asn]['first_count'] = count
as_prefix_data[asn]['first_time'] = current_snapshot_time
as_prefix_data[asn]['last_count'] = count
as_prefix_data[asn]['last_time'] = current_snapshot_time
else:
# Update last seen count and time for this AS
as_prefix_data[asn]['last_count'] = count
as_prefix_data[asn]['last_time'] = current_snapshot_time
# Reset for the new snapshot time
current_snapshot_prefixes = collections.defaultdict(set)
processed_snapshots += 1
current_snapshot_time = current_rec_time # Update current time
# Process elements within the current record/snapshot
for elem in rec:
elem_count += 1
if elem.type == "R": # RIB Entry
prefix = elem.fields.get("prefix")
as_path_str = elem.fields.get("as-path")
if prefix and as_path_str:
origin_as = get_origin_as(as_path_str)
if origin_as:
# Add prefix to the set for this origin AS in the current snapshot
current_snapshot_prefixes[origin_as].add(prefix)
if rec_count % 10 == 0: # Print progress occasionally
print(f" Processed {rec_count} records ({elem_count} elements)...")
except Exception as e:
print(f"An error occurred during BGPStream processing: {e}")
# Decide how to handle partial results if needed
# return [] # Or potentially process what we have
# --- Process the *last* snapshot's data ---
# After the loop finishes, the data for the very last snapshot time needs processing.
if current_snapshot_time != -1 and current_snapshot_prefixes:
print(f"Processing final snapshot from time {current_snapshot_time}...")
for asn, prefixes in current_snapshot_prefixes.items():
count = len(prefixes)
if asn not in as_prefix_data:
# First and only time seeing this AS
as_prefix_data[asn]['first_count'] = count
as_prefix_data[asn]['first_time'] = current_snapshot_time
as_prefix_data[asn]['last_count'] = count
as_prefix_data[asn]['last_time'] = current_snapshot_time
else:
# Update last seen count and time
as_prefix_data[asn]['last_count'] = count
as_prefix_data[asn]['last_time'] = current_snapshot_time
processed_snapshots += 1
end_time = time.time()
print(f"BGPStream processing finished in {end_time - start_time:.2f} seconds.")
print(f"Processed {processed_snapshots} distinct snapshot times.")
print(f"Found data for {len(as_prefix_data)} unique ASes.")
# --- Calculate Growth ---
growth_results = []
for asn, data in as_prefix_data.items():
first_count = data['first_count']
last_count = data['last_count']
# Ensure the AS appeared at least once with a valid count
if first_count == -1 or last_count == -1:
# Should not happen with defaultdict logic, but good safety check
continue
# Handle cases where an AS appeared only once (no growth)
# or where the initial count was zero.
if first_count > 0:
growth_percentage = ((last_count - first_count) / first_count) * 100.0
growth_results.append((asn, growth_percentage))
elif first_count == 0 and last_count > 0:
# Growth from 0 to N is arguably infinite. Assign a large value or skip.
# Let's skip for this calculation as percentage isn't well-defined.
# Alternatively: growth_results.append((asn, float('inf')))
pass
else: # first_count == 0 and last_count == 0, or other edge cases
# No growth or undefined growth
growth_results.append((asn, 0.0))
# --- Sort and Return Top 10 ---
# Sort by growth percentage in descending order
growth_results.sort(key=lambda x: x[1], reverse=True)
return growth_results[:10]
# --- Example Usage ---
if __name__ == '__main__':
# IMPORTANT: Replace these with ACTUAL, VALID, ABSOLUTE paths to your RIB files
# Ensure the files exist and are accessible by the script.
# These files MUST be sorted chronologically for the logic to be correct.
# Example using hypothetical RouteViews files (you'll need real ones)
# Create dummy files for demonstration if you don't have real ones
# NOTE: This requires write permissions in the current directory
import os
import gzip
dummy_dir = "dummy_rib_files"
if not os.path.exists(dummy_dir):
os.makedirs(dummy_dir)
# VERY basic dummy RIB content - not realistic BGP data! Just for structure.
rib_content_1 = """TYPE: TABLE_DUMP_V2
TIME: 1678886400
PREFIX: 192.0.2.0/24
AS_PATH: 64500 64501
NEXT_HOP: 10.0.0.1
PREFIX: 203.0.113.0/24
AS_PATH: 64500 64502
NEXT_HOP: 10.0.0.1
PREFIX: 198.51.100.0/24
AS_PATH: 65000
NEXT_HOP: 10.0.0.2
"""
rib_content_2 = """TYPE: TABLE_DUMP_V2
TIME: 1678890000
PREFIX: 192.0.2.0/24
AS_PATH: 64500 64501
NEXT_HOP: 10.0.0.1
PREFIX: 203.0.113.0/24
AS_PATH: 64500 64502
NEXT_HOP: 10.0.0.1
PREFIX: 198.51.100.0/24
AS_PATH: 65000
NEXT_HOP: 10.0.0.2
PREFIX: 198.51.101.0/24
AS_PATH: 65000
NEXT_HOP: 10.0.0.2
PREFIX: 10.10.0.0/16
AS_PATH: 64502
NEXT_HOP: 10.0.0.3
"""
file1_path = os.path.abspath(os.path.join(dummy_dir, "rib.20230315.1200.gz"))
file2_path = os.path.abspath(os.path.join(dummy_dir, "rib.20230315.1300.gz"))
try:
with gzip.open(file1_path, "wt", encoding="utf-8") as f:
f.write(rib_content_1)
with gzip.open(file2_path, "wt", encoding="utf-8") as f:
f.write(rib_content_2)
print(f"Created dummy RIB files: {file1_path}, {file2_path}")
# Ensure files are sorted chronologically if providing manually
rib_files_list = sorted([file1_path, file2_path])
top_10_growth = top_10_ases_by_prefix_growth(rib_files_list)
print("\n--- Top 10 ASes by Prefix Growth Percentage ---")
if top_10_growth:
for i, (asn, growth) in enumerate(top_10_growth):
print(f"{i+1}. AS{asn}: {growth:.2f}% growth")
else:
print("No growth data calculated or found.")
except Exception as e:
print(f"An error occurred during example execution: {e}")
finally:
# Clean up dummy files
# import shutil
# if os.path.exists(dummy_dir):
# shutil.rmtree(dummy_dir)
# print(f"Cleaned up dummy directory: {dummy_dir}")
# Comment out cleanup if you want to inspect the files
pass
Explanation:
get_origin_as(as_path_str): A helper function to robustly extract the origin AS (the rightmost number) from the AS path string. It handles empty paths, splits the path, iterates backward to skip potential prepended junk or AS_SETs (in a basic way), and converts the segment to an integer. Returns None if no valid origin AS is found.
top_10_ases_by_prefix_growth(rib_files) Function:
- Takes the sorted list of absolute RIB file paths.
- Initializes
as_prefix_data: A dictionary to store the first and last seen prefix counts and timestamps for each AS. defaultdict simplifies adding new ASes.
- Initializes
current_snapshot_prefixes: A dictionary mapping ASNs to a set of prefixes seen within the current snapshot being processed. Using a set automatically handles duplicate prefix announcements for the same AS within a single snapshot.
- Initializes
current_snapshot_time: Tracks the timestamp of the snapshot currently being built in current_snapshot_prefixes.
- PyBGPStream Setup:
- Creates a
BGPStream instance.
- Iterates through
rib_files and adds each file using stream.add_data_interface_option("rib-file", file_path).
- Filters for
record-type 'ribs'.
- Processing Loop:
- Iterates through
stream.records(). Each record typically corresponds to one RIB file dump.
- Snapshot Logic: It checks if the
rec.time (timestamp of the current record) is different from current_snapshot_time.
- If the time has changed (meaning we finished processing the previous snapshot time), it iterates through the
current_snapshot_prefixes dictionary (which holds the aggregated data for the previous snapshot).
- For each AS in the completed snapshot, it updates
as_prefix_data with either the initial counts/time (if seen for the first time) or just the last_count and last_time.
- It then resets
current_snapshot_prefixes for the new snapshot time and updates current_snapshot_time.
- It then iterates through elements (
elem) within the current record.
- If
elem.type == "R" (RIB entry):
To Use:
- Install PyBGPStream:
pip install pybgpstream
- Get RIB Files: Obtain the RIB dump files (e.g., from RouteViews or RIPE RIS) covering the desired timespan.
- Ensure Order: Make sure the list of file paths you provide is sorted chronologically (usually by the timestamp in the filename).
- Update Paths: Modify the
rib_files_list in the if __name__ == '__main__': block to contain the correct, absolute paths to your files.
- Run: Execute the Python script (
python your_script_name.py).