Skip to main content

BgpkitParser

Struct BgpkitParser 

Source
pub struct BgpkitParser<R> { /* private fields */ }

Implementations§

Source§

impl<R> BgpkitParser<R>

Source

pub fn into_record_iter(self) -> RecordIterator<R>

Source

pub fn into_elem_iter(self) -> ElemIterator<R>

Source

pub fn into_raw_record_iter(self) -> RawRecordIterator<R>

Source

pub fn into_update_iter(self) -> UpdateIterator<R>

Creates an iterator over BGP announcements from MRT data.

This iterator yields MrtUpdate items from both UPDATES files (BGP4MP messages) and RIB dump files (TableDump/TableDumpV2 messages). It’s a middle ground between into_record_iter() and into_elem_iter():

  • More focused than into_record_iter() as it only returns BGP announcements
  • More efficient than into_elem_iter() as it doesn’t duplicate attributes per prefix

The iterator returns an MrtUpdate enum with variants:

  • Bgp4MpUpdate: BGP UPDATE messages from UPDATES files
  • TableDumpV2Entry: RIB entries from TableDumpV2 RIB dumps
  • TableDumpMessage: Legacy TableDump v1 messages
§Example
use bgpkit_parser::{BgpkitParser, MrtUpdate};

let parser = BgpkitParser::new("updates.mrt").unwrap();
for update in parser.into_update_iter() {
    match update {
        MrtUpdate::Bgp4MpUpdate(u) => {
            println!("Peer {} announced {} prefixes",
                u.peer_ip,
                u.message.announced_prefixes.len()
            );
        }
        MrtUpdate::TableDumpV2Entry(e) => {
            println!("RIB entry for {} with {} peers",
                e.prefix,
                e.rib_entries.len()
            );
        }
        MrtUpdate::TableDumpMessage(m) => {
            println!("Legacy table dump for {}", m.prefix);
        }
    }
}
Source

pub fn into_fallible_record_iter(self) -> FallibleRecordIterator<R>

Creates a fallible iterator over MRT records that returns parsing errors.

§Example
use bgpkit_parser::BgpkitParser;

let parser = BgpkitParser::new("updates.mrt").unwrap();
for result in parser.into_fallible_record_iter() {
    match result {
        Ok(record) => {
            // Process the record
        }
        Err(e) => {
            // Handle the error
            eprintln!("Error parsing record: {}", e);
        }
    }
}
Source

pub fn into_fallible_elem_iter(self) -> FallibleElemIterator<R>

Creates a fallible iterator over BGP elements that returns parsing errors.

§Example
use bgpkit_parser::BgpkitParser;

let parser = BgpkitParser::new("updates.mrt").unwrap();
for result in parser.into_fallible_elem_iter() {
    match result {
        Ok(elem) => {
            // Process the element
        }
        Err(e) => {
            // Handle the error
            eprintln!("Error parsing element: {}", e);
        }
    }
}
Source

pub fn into_fallible_update_iter(self) -> FallibleUpdateIterator<R>

Creates a fallible iterator over BGP announcements that returns parsing errors.

Unlike the default into_update_iter(), this iterator returns Result<MrtUpdate, ParserErrorWithBytes> allowing users to handle parsing errors explicitly instead of having them logged and skipped.

§Example
use bgpkit_parser::{BgpkitParser, MrtUpdate};

let parser = BgpkitParser::new("updates.mrt").unwrap();
for result in parser.into_fallible_update_iter() {
    match result {
        Ok(MrtUpdate::Bgp4MpUpdate(update)) => {
            println!("Peer {} announced {} prefixes",
                update.peer_ip,
                update.message.announced_prefixes.len()
            );
        }
        Ok(_) => { /* handle other variants */ }
        Err(e) => {
            eprintln!("Error parsing: {}", e);
        }
    }
}
Source

pub fn into_elementor_and_raw_record_iter( self, ) -> (Elementor, impl Iterator<Item = RawMrtRecord>)
where R: Read,

Creates an Elementor pre-initialized with PeerIndexTable and an iterator over raw records.

This is useful for parallel processing where the Elementor needs to be shared across threads. The Elementor is created with the PeerIndexTable from the first record if present, otherwise a new Elementor is created.

§Example

See the parallel_records_to_elem example for full usage.

use bgpkit_parser::BgpkitParser;

let parser = BgpkitParser::new_cached(url, "/tmp")?;
let (elementor, records) = parser.into_elementor_and_raw_record_iter();
Source

pub fn into_elementor_and_record_iter( self, ) -> (Elementor, impl Iterator<Item = MrtRecord>)
where R: Read,

Creates an Elementor pre-initialized with PeerIndexTable and an iterator over parsed records.

This is useful for parallel processing where the Elementor needs to be shared across threads. The Elementor is created with the PeerIndexTable from the first record if present, otherwise a new Elementor is created.

§Example

See the parallel_records_to_elem example for full usage.

Source§

impl BgpkitParser<Box<dyn Read + Send>>

Source

pub fn new(path: &str) -> Result<Self, ParserErrorWithBytes>

Creating a new parser from a object that implements Read trait.

Source

pub fn new_cached( path: &str, cache_dir: &str, ) -> Result<Self, ParserErrorWithBytes>

Creating a new parser that also caches the remote content to a local cache directory.

The cache file name is generated by the following format: cache-<crc32 of file name>-<file name>. For example, the remote file http://archive.routeviews.org/route-views.chile/bgpdata/2023.03/RIBS/rib.20230326.0600.bz2 will be cached as cache-682cb1eb-rib.20230326.0600.bz2 in the cache directory.

Source§

impl<R: Read> BgpkitParser<R>

Source

pub fn from_reader(reader: R) -> Self

Creating a new parser from an object that implements Read trait.

Source

pub fn next_record(&mut self) -> Result<MrtRecord, ParserErrorWithBytes>

This is used in for loop for item in parser{}

Source§

impl<R> BgpkitParser<R>

Source

pub fn enable_core_dump(self) -> Self

Source

pub fn disable_warnings(self) -> Self

Source

pub fn add_filter( self, filter_type: &str, filter_value: &str, ) -> Result<Self, ParserErrorWithBytes>

Add a filter to the parser by specifying filter type and value as strings.

This method parses the filter type and value strings to create a Filter and adds it to the parser’s filter list. For the full list of available filter types and their formats, see the Filter struct documentation.

§Available Filter Types
  • origin_asn - Origin AS number (e.g., “12345”)
  • origin_asns - Multiple origin AS numbers, comma-separated (e.g., “12345,67890”)
  • prefix - Exact prefix match (e.g., “192.168.1.0/24”)
  • prefix_super - Match prefix and super-prefixes
  • prefix_sub - Match prefix and sub-prefixes
  • prefix_super_sub - Match prefix, super-prefixes, and sub-prefixes
  • prefixes - Multiple prefixes (e.g., “1.1.1.0/24,8.8.8.0/24”)
  • peer_ip - Peer IP address (e.g., “192.168.1.1”)
  • peer_ips - Multiple peer IPs (e.g., “192.168.1.1,192.168.1.2”)
  • peer_asn - Peer AS number (e.g., “12345”)
  • peer_asns - Multiple peer AS numbers (e.g., “12345,67890”)
  • type - Message type: “a”/“announce” or “w”/“withdraw”
  • ts_start - Start timestamp (unix timestamp or RFC3339)
  • ts_end - End timestamp (unix timestamp or RFC3339)
  • as_path - AS path regex pattern
  • community - Community regex pattern
  • ip_version - IP version: “4”/“ipv4” or “6”/“ipv6”
§Negative Filters

Most filters support negation by prefixing the value with !. For example:

  • origin_asn=!13335 matches elements where origin AS is NOT 13335
  • prefix=!10.0.0.0/8 matches elements where prefix is NOT 10.0.0.0/8
§Example
use bgpkit_parser::BgpkitParser;

let parser = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
    .unwrap()
    .add_filter("peer_ip", "185.1.8.65")
    .unwrap()
    .add_filter("type", "w")
    .unwrap();

for elem in parser {
    println!("{}", elem);
}
Source

pub fn add_filters(self, filters: &[Filter]) -> Self

Add multiple filters to the parser.

This method extends the existing filters with the provided slice of filters.

§Example
use bgpkit_parser::BgpkitParser;
use bgpkit_parser::parser::Filter;

let filters = vec![
    Filter::new("peer_ip", "185.1.8.65").unwrap(),
    Filter::new("type", "w").unwrap(),
];

let parser = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
    .unwrap()
    .add_filters(&filters);
Source

pub fn with_filters(self, filters: &[Filter]) -> Self

Set filters directly, replacing any existing filters.

This method allows passing a pre-built Vec<Filter> directly to the parser, bypassing the need to parse filter strings. This is useful when you want to build filter specifications independently and reuse them across multiple parsers.

§Example
use bgpkit_parser::BgpkitParser;
use bgpkit_parser::parser::Filter;

// Build filters independently
let filters = vec![
    Filter::new("peer_ip", "185.1.8.65").unwrap(),
    Filter::new("type", "w").unwrap(),
];

// Apply to multiple parsers (no manual clone needed)
let parser1 = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
    .unwrap()
    .with_filters(&filters);

let parser2 = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
    .unwrap()
    .with_filters(&filters);

Trait Implementations§

Source§

impl<R: Read> IntoIterator for BgpkitParser<R>

Use ElemIterator as the default iterator to return BgpElems instead of MrtRecords.

Source§

type Item = BgpElem

The type of the elements being iterated over.
Source§

type IntoIter = ElemIterator<R>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<R> Freeze for BgpkitParser<R>
where R: Freeze,

§

impl<R> RefUnwindSafe for BgpkitParser<R>
where R: RefUnwindSafe,

§

impl<R> Send for BgpkitParser<R>
where R: Send,

§

impl<R> Sync for BgpkitParser<R>
where R: Sync,

§

impl<R> Unpin for BgpkitParser<R>
where R: Unpin,

§

impl<R> UnsafeUnpin for BgpkitParser<R>
where R: UnsafeUnpin,

§

impl<R> UnwindSafe for BgpkitParser<R>
where R: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more