aboutsummaryrefslogtreecommitdiff
path: root/ops/src/lib.rs
blob: a929816c99230838164b0dade98bbdd0b6b8e5b7 (plain)
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#[macro_use]
extern crate log;
extern crate blist;
extern crate bit_set;
extern crate serde;
extern crate chrono;
extern crate ilc_base;
extern crate regex;

mod ageset;
pub mod stats;
pub mod convert;

/// No-op log parsing
pub mod parse {
    use ilc_base::{self, Context, Decode};
    use std::io::BufRead;

    /// Simply parse the input, without further validation or conversion. No information is stored.
    /// This will return `Err` if the decoder yields `Err`.
    pub fn parse(ctx: &Context, input: &mut BufRead, decoder: &mut Decode) -> ilc_base::Result<()> {
        for e in decoder.decode(&ctx, input) {
            match e {
                Ok(e) => debug!("{:?}", e),
                Err(e) => error!("{:?}", e),
            }
        }
        Ok(())
    }
}

/// Internal (as opposed to external, not to be confused with private) log sorting
pub mod sort {
    use ilc_base::{self, Context, Decode, Encode, Event};
    use std::io::{BufRead, Write};

    /// **Memory-intensive**
    /// Sort the input, discarding faulty events. This will
    /// read *all events* into memory, then sort them by time and write them back.
    /// Behaviour is undefined if events lack full date information.
    ///
    /// *This should be an external merge-sort, but is a placeholder until implementation*
    pub fn sort(ctx: &Context,
                input: &mut BufRead,
                decoder: &mut Decode,
                output: &mut Write,
                encoder: &Encode)
                -> ilc_base::Result<()> {
        let mut events: Vec<Event> = decoder.decode(&ctx, input)
                                            .flat_map(Result::ok)
                                            .collect();

        events.sort_by(|a, b| a.time.cmp(&b.time));
        for e in events {
            try!(encoder.encode(&ctx, output, &e));
        }
        Ok(())
    }
}

/// Event deduplication
pub mod dedup {
    use std::io::{BufRead, Write};
    use std::hash::{Hash, Hasher};
    use ageset::AgeSet;
    use ilc_base::{self, Context, Decode, Encode, Event};

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct NoTimeHash<'a>(pub Event<'a>);

    impl<'a> Hash for NoTimeHash<'a> {
        fn hash<H>(&self, state: &mut H)
            where H: Hasher
        {
            self.0.ty.hash(state);
            self.0.channel.hash(state);
        }
    }

    /// Deduplicate subsequent identical elements, e.g. after a sorting
    /// operation. This will **not** read all events into memory, and only
    /// operate on a short window of events. Therefore, it'll only work correctly
    /// on sorted or very short logs.
    pub fn dedup(ctx: &Context,
                 input: &mut BufRead,
                 decoder: &mut Decode,
                 output: &mut Write,
                 encoder: &Encode)
                 -> ilc_base::Result<()> {
        let mut backlog = AgeSet::new();

        for e in decoder.decode(&ctx, input) {
            if let Ok(e) = e {
                let newest_event = e.clone();
                backlog.prune(move |a: &NoTimeHash| {
                    let age = newest_event.time.as_timestamp() - a.0.time.as_timestamp();
                    age > 5000
                });
                // write `e` if it's a new event
                let n = NoTimeHash(e);
                if !backlog.contains(&n) {
                    try!(encoder.encode(&ctx, output, &n.0));
                    backlog.push(n);
                }
            }
        }
        Ok(())
    }
}

/// "Efficient" n-way merging
pub mod merge {
    use std::io::{BufRead, Write};
    use bit_set::BitSet;
    use ilc_base::{self, Context, Decode, Encode, Event};

    /// Merge several individually sorted logs, *without* reading everything
    /// into memory.
    ///
    /// The `input` and `decode` parameter will be zipped, so make sure they match up.
    ///
    /// Output will be inconsistent if every input isn't sorted by itself.
    /// Logs with incomplete dates are free to do to weird stuff.
    pub fn merge<'a>(ctx: &Context,
                     input: Vec<&'a mut BufRead>,
                     decode: &mut Decode,
                     output: &mut Write,
                     encode: &Encode)
                     -> ilc_base::Result<()> {
        let mut events = input.into_iter()
                              .map(|i| decode.decode(&ctx, i).peekable())
                              .collect::<Vec<_>>();
        let mut empty = BitSet::with_capacity(events.len());

        loop {
            if events.is_empty() {
                return Ok(());
            }

            let earliest_idx = {
                // Lifetimes can be a lot easier if you don't nest closures.
                // Uglier too, yes. But hey, at least it compiles.
                // Currently earliest event
                let mut current = None;
                // Index of stream that has "current" as head
                let mut stream_idx = None;

                for (idx, stream) in events.iter_mut().enumerate() {
                    let peek = stream.peek();
                    if let Some(ev) = peek {
                        // Ignore errors in stream
                        if let &Ok(ref ev) = ev {
                            if current.map(|c: &Event| ev.time < c.time).unwrap_or(true) {
                                current = Some(ev);
                                stream_idx = Some(idx);
                            }
                        }
                    } else {
                        empty.insert(idx);
                    }
                }
                stream_idx
            };

            // Safe because of matching against Some(&Ok(ref ev)) earlier
            let earliest = earliest_idx.map(|idx| events[idx].next().unwrap().unwrap());

            if let Some(event) = earliest {
                try!(encode.encode(&ctx, output, &event));
            }

            // Keep non-empty streams
            for (offset, idx) in empty.iter().enumerate() {
                // `remove` returns an iterator. It's empty, but Rust doesn't know that,
                // so suppress the warning like this.
                let _ = events.remove(offset + idx);
            }
            empty.clear();
        }
    }
}