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
// Copyright 2017, CZ.NIC z.s.p.o. (http://www.nic.cz/)
//
// This file is part of the pakon system.
//
// Pakon is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
// Pakon is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Pakon.  If not, see <http://www.gnu.org/licenses/>.

//! Some helpers for tests and creation of flows-related data.

#![deny(missing_docs)]

extern crate libdata;
extern crate libflow;
extern crate libquery;
extern crate libutils;

use std::iter;
use std::net::IpAddr;
use std::time::{Duration, UNIX_EPOCH};

use libdata::column::{FlowTags, Local, Remote, Tags};
use libdata::flow::{Bytes, Count, Direction, IpProto, IpProtoRaw, Port, Speed};
use libdata::stats::{Stat, Stats};
use libflow::slice::{Flow, Time};
use libquery::InTimeInterval;
use libutils::tunable::SLICE_LENGTH_SECONDS;

/// Builds a dummy test flow.
///
/// It is mostly empty, with 1 packet in the local→remote direction and set addresses. It is a
/// TCP flow, with ports set to 1 and 2.
///
/// # Parameters
///
/// * id: Id of the new flow.
/// * local: Local endpoint IP address for the new flow.
/// * remote: Remote endpoint IP address for the new flow.
pub fn dummy_flow(local: IpAddr, remote: IpAddr) -> Flow {
    let mut tags = Tags::new();
    tags.insert(Direction::In);
    tags.insert(Local(local));
    tags.insert(Local(Port(1)));
    tags.insert(Remote(remote));
    tags.insert(Remote(Port(2)));
    tags.insert(IpProto::Tcp);
    tags.insert(IpProtoRaw(16));

    let stats = Stats {
        dir_in: Stat {
            speed_duration: Duration::from_secs(5),
            flows: Count(1),
            flows_started: Count(0),
            size: Bytes(120),
            packets: Count(1),
            max_speed: Speed(24),
            start: Some(UNIX_EPOCH),
            end: Some(UNIX_EPOCH + Duration::from_secs(5)),
        },
        dir_out: Stat {
            flows: Count(1),
            start: Some(UNIX_EPOCH),
            end: Some(UNIX_EPOCH + Duration::from_secs(5)),
            ..Stat::default()
        },
    };

    Flow::new(FlowTags::new(tags), stats)
}

/// Creates a dummy time slice for testing purposes.
///
/// # Parameters
///
/// * `start`: The start time field in number of milliseconds since 1.1. 1970. This is expected
///    to be used as kind of identifier during the tests, so the units are not important.
pub fn dummy_time(start: u64) -> Time {
    let start = ::libdata::flow::system_time_from_ms(start);
    let end = start + Duration::from_secs(SLICE_LENGTH_SECONDS);
    Time::new(start, end, Vec::new())
}

/// Adds another flow slice into the time slice.
///
/// This is for testing purposes, to augment a dummy time slice with some data.
///
/// Note that this creates a new time slice.
///
/// # Parameters
///
/// * `time`: The time slice to augment.
/// * `flow`: The flow to insert. If there's any of the same ID, it is overwritten.
pub fn flow_append(time: &Time, flow: Flow) -> Time {
    let (start, end) = time.interval();
    let flows = time
        .into_iter()
        .cloned()
        .chain(iter::once(flow))
        .collect();
    Time::new(start, end, flows)
}

#[cfg(test)]
mod tests {
    use super::*;

    use libdata::column::{Ident, Value};
    use libquery::ValueSrc;

    /// Tests computations of the flow statistics.
    #[test]
    fn flow_stat() {
        let flow = dummy_flow("192.0.2.1".parse().unwrap(), "192.0.2.2".parse().unwrap());
        let expected = Stats {
            dir_in: Stat {
                packets: Count(1),
                size: Bytes(120),
                speed_duration: Duration::from_secs(SLICE_LENGTH_SECONDS),
                max_speed: Speed(24),
                flows: Count(1),
                flows_started: Count(0),
                start: Some(UNIX_EPOCH),
                end: Some(UNIX_EPOCH + Duration::from_secs(5)),
            },
            dir_out: Stat {
                flows: Count(1),
                start: Some(UNIX_EPOCH),
                end: Some(UNIX_EPOCH + Duration::from_secs(5)),
                ..Stat::default()
            },
        };
        assert_eq!(&expected, (&flow).stats());
    }

    /// Test getting values out of a time flow slice.
    #[test]
    fn flow_value() {
        let mut time = dummy_time(0);
        let flow = dummy_flow("192.0.2.1".parse().unwrap(), "192.0.2.2".parse().unwrap());
        time = flow_append(&time, flow);
        // Just a smoke test… everything is inside that interval
        assert!(time.in_time_interval(None, None));
        // Iterate through the container
        assert_eq!(1, time.into_iter().count());
        let remote = Remote("192.0.2.2".parse::<IpAddr>().unwrap()).into();
        for flow in &time {
            // Pick few values at random, testing all would be really tedious
            assert_eq!(flow.value(&Ident::of::<IpProto>()).unwrap(), Value::from(IpProto::Tcp));
            assert_eq!(flow.value(&Ident::of::<Remote<IpAddr>>()).unwrap(), remote);
        }
    }
}