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
//! Retina runtime.
//!
//! The runtime initializes the DPDK environment abstraction layer, creates memory pools, launches
//! the packet processing cores, and manages logging and display output.

mod offline;
mod online;
use self::offline::*;
use self::online::*;

use crate::config::*;
use crate::dpdk;
use crate::filter::FilterFactory;
use crate::lcore::SocketId;
use crate::memory::mempool::Mempool;
use crate::subscription::*;

use std::collections::BTreeMap;
use std::ffi::CString;
use std::sync::Arc;

use anyhow::{bail, Result};

/// The Retina runtime.
///
/// The runtime initializes the DPDK environment abstraction layer, creates memory pools, launches
/// the packet processing cores, and manages logging and display output.
pub struct Runtime<S>
where
    S: Subscribable,
{
    #[allow(dead_code)]
    mempools: BTreeMap<SocketId, Mempool>,
    online: Option<OnlineRuntime<S>>,
    offline: Option<OfflineRuntime<S>>,
    #[cfg(feature = "timing")]
    subscription: Arc<Subscription<S>>,
}

impl<S> Runtime<S>
where
    S: Subscribable,
{
    /// Creates a new runtime from the `config` settings, filter, and callback.
    ///
    /// # Remarks
    ///
    /// The `factory` parameter is a macro-generated function pointer based on the user-defined
    /// filter string, and must take the value "`filter`". `cb` is the name of the user-defined
    /// callback function.
    ///
    /// # Example
    ///
    /// let mut runtime = Runtime::new(config, filter, callback)?;
    pub fn new(config: RuntimeConfig, factory: fn() -> FilterFactory<S::Tracked>) -> Result<Self> {
        let factory = factory();
        let filter_str = factory.filter_str.clone();
        let subscription = Arc::new(Subscription::new(factory));

        println!("Initializing Retina runtime...");
        log::info!("Initializing EAL...");
        dpdk::load_drivers();
        {
            let eal_params = config.get_eal_params();
            let eal_params_len = eal_params.len() as i32;

            let mut args = vec![];
            let mut ptrs = vec![];
            for arg in eal_params.into_iter() {
                let s = CString::new(arg).unwrap();
                ptrs.push(s.as_ptr() as *mut u8);
                args.push(s);
            }

            let ret = unsafe { dpdk::rte_eal_init(eal_params_len, ptrs.as_ptr() as *mut _) };
            if ret < 0 {
                bail!("Failure initializing EAL");
            }
        }

        log::info!("Initializing Mempools...");
        let mut mempools = BTreeMap::new();
        let socket_ids = config.get_all_socket_ids();
        let mtu = if let Some(online) = &config.online {
            online.mtu
        } else if let Some(offline) = &config.offline {
            offline.mtu
        } else {
            Mempool::default_mtu()
        };
        for socket_id in socket_ids {
            log::debug!("Socket ID: {}", socket_id);
            let mempool = Mempool::new(&config.mempool, socket_id, mtu)?;
            mempools.insert(socket_id, mempool);
        }

        let online = config.online.as_ref().map(|cfg| {
            log::info!("Initializing Online Runtime...");
            let online_opts = OnlineOptions {
                online: cfg.clone(),
                conntrack: config.conntrack.clone(),
            };
            OnlineRuntime::new(
                &config,
                online_opts,
                &mut mempools,
                filter_str.clone(),
                Arc::clone(&subscription),
            )
        });

        let offline = config.offline.as_ref().map(|cfg| {
            log::info!("Initializing Offline Analysis...");
            let offline_opts = OfflineOptions {
                offline: cfg.clone(),
                conntrack: config.conntrack.clone(),
            };
            OfflineRuntime::new(offline_opts, &mempools, Arc::clone(&subscription))
        });

        log::info!("Runtime ready.");
        Ok(Runtime {
            mempools,
            online,
            offline,
            #[cfg(feature = "timing")]
            subscription,
        })
    }

    /// Run Retina for the duration specified in the configuration or until `ctrl-c` to terminate.
    ///
    /// # Example
    ///
    /// runtime.run();
    pub fn run(&mut self) {
        if let Some(online) = &mut self.online {
            online.run();
        } else if let Some(offline) = &self.offline {
            offline.run();
        } else {
            log::error!("No runtime");
        }
        #[cfg(feature = "timing")]
        {
            self.subscription.timers.display_stats();
            self.subscription.timers.dump_stats();
        }
        log::info!("Done.");
    }
}