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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.

use std::cmp;
use std::path::Path;

use crate::properties::{RangeProperties, UserCollectedPropertiesDecoder};
use crate::raw::EventListener;
use collections::hash_set_with_capacity;
use engine_traits::CompactedEvent;
use engine_traits::CompactionJobInfo;
use rocksdb::{
    CompactionJobInfo as RawCompactionJobInfo, CompactionReason, TablePropertiesCollectionView,
};
use std::collections::BTreeMap;
use std::collections::Bound::{Excluded, Included, Unbounded};
use tikv_util::warn;

pub struct RocksCompactionJobInfo<'a>(&'a RawCompactionJobInfo);

impl<'a> RocksCompactionJobInfo<'a> {
    pub fn from_raw(raw: &'a RawCompactionJobInfo) -> Self {
        RocksCompactionJobInfo(raw)
    }

    pub fn into_raw(self) -> &'a RawCompactionJobInfo {
        self.0
    }
}

impl CompactionJobInfo for RocksCompactionJobInfo<'_> {
    type TablePropertiesCollectionView = TablePropertiesCollectionView;
    type CompactionReason = CompactionReason;

    fn status(&self) -> Result<(), String> {
        self.0.status()
    }

    fn cf_name(&self) -> &str {
        self.0.cf_name()
    }

    fn input_file_count(&self) -> usize {
        self.0.input_file_count()
    }

    fn input_file_at(&self, pos: usize) -> &Path {
        self.0.input_file_at(pos)
    }

    fn output_file_count(&self) -> usize {
        self.0.output_file_count()
    }

    fn output_file_at(&self, pos: usize) -> &Path {
        self.0.output_file_at(pos)
    }

    fn table_properties(&self) -> &Self::TablePropertiesCollectionView {
        self.0.table_properties()
    }

    fn elapsed_micros(&self) -> u64 {
        self.0.elapsed_micros()
    }

    fn num_corrupt_keys(&self) -> u64 {
        self.0.num_corrupt_keys()
    }

    fn output_level(&self) -> i32 {
        self.0.output_level()
    }

    fn input_records(&self) -> u64 {
        self.0.input_records()
    }

    fn output_records(&self) -> u64 {
        self.0.output_records()
    }

    fn total_input_bytes(&self) -> u64 {
        self.0.total_input_bytes()
    }

    fn total_output_bytes(&self) -> u64 {
        self.0.total_output_bytes()
    }

    fn compaction_reason(&self) -> Self::CompactionReason {
        self.0.compaction_reason()
    }
}

pub struct RocksCompactedEvent {
    pub cf: String,
    pub output_level: i32,
    pub total_input_bytes: u64,
    pub total_output_bytes: u64,
    pub start_key: Vec<u8>,
    pub end_key: Vec<u8>,
    pub input_props: Vec<RangeProperties>,
    pub output_props: Vec<RangeProperties>,
}

impl RocksCompactedEvent {
    pub fn new(
        info: &RocksCompactionJobInfo,
        start_key: Vec<u8>,
        end_key: Vec<u8>,
        input_props: Vec<RangeProperties>,
        output_props: Vec<RangeProperties>,
    ) -> RocksCompactedEvent {
        RocksCompactedEvent {
            cf: info.cf_name().to_owned(),
            output_level: info.output_level(),
            total_input_bytes: info.total_input_bytes(),
            total_output_bytes: info.total_output_bytes(),
            start_key,
            end_key,
            input_props,
            output_props,
        }
    }
}

impl CompactedEvent for RocksCompactedEvent {
    fn total_bytes_declined(&self) -> u64 {
        if self.total_input_bytes > self.total_output_bytes {
            self.total_input_bytes - self.total_output_bytes
        } else {
            0
        }
    }

    fn is_size_declining_trivial(&self, split_check_diff: u64) -> bool {
        let total_bytes_declined = self.total_bytes_declined();
        total_bytes_declined < split_check_diff
            || total_bytes_declined * 10 < self.total_input_bytes
    }

    fn output_level_label(&self) -> String {
        self.output_level.to_string()
    }

    fn calc_ranges_declined_bytes(
        self,
        ranges: &BTreeMap<Vec<u8>, u64>,
        bytes_threshold: u64,
    ) -> Vec<(u64, u64)> {
        // Calculate influenced regions.
        let mut influenced_regions = vec![];
        for (end_key, region_id) in
            ranges.range((Excluded(self.start_key), Included(self.end_key.clone())))
        {
            influenced_regions.push((region_id, end_key.clone()));
        }
        if let Some((end_key, region_id)) = ranges.range((Included(self.end_key), Unbounded)).next()
        {
            influenced_regions.push((region_id, end_key.clone()));
        }

        // Calculate declined bytes for each region.
        // `end_key` in influenced_regions are in incremental order.
        let mut region_declined_bytes = vec![];
        let mut last_end_key: Vec<u8> = vec![];
        for (region_id, end_key) in influenced_regions {
            let mut old_size = 0;
            for prop in &self.input_props {
                old_size += prop.get_approximate_size_in_range(&last_end_key, &end_key);
            }
            let mut new_size = 0;
            for prop in &self.output_props {
                new_size += prop.get_approximate_size_in_range(&last_end_key, &end_key);
            }
            last_end_key = end_key;

            // Filter some trivial declines for better performance.
            if old_size > new_size && old_size - new_size > bytes_threshold {
                region_declined_bytes.push((*region_id, old_size - new_size));
            }
        }

        region_declined_bytes
    }

    fn cf(&self) -> &str {
        &*self.cf
    }
}

pub type Filter = fn(&RocksCompactionJobInfo) -> bool;

pub struct CompactionListener {
    ch: Box<dyn Fn(RocksCompactedEvent) + Send + Sync>,
    filter: Option<Filter>,
}

impl CompactionListener {
    pub fn new(
        ch: Box<dyn Fn(RocksCompactedEvent) + Send + Sync>,
        filter: Option<Filter>,
    ) -> CompactionListener {
        CompactionListener { ch, filter }
    }
}

impl EventListener for CompactionListener {
    fn on_compaction_completed(&self, info: &RawCompactionJobInfo) {
        let info = &RocksCompactionJobInfo::from_raw(info);
        if info.status().is_err() {
            return;
        }

        if let Some(ref f) = self.filter {
            if !f(info) {
                return;
            }
        }

        let mut input_files = hash_set_with_capacity(info.input_file_count());
        let mut output_files = hash_set_with_capacity(info.output_file_count());
        for i in 0..info.input_file_count() {
            info.input_file_at(i)
                .to_str()
                .map(|x| input_files.insert(x.to_owned()));
        }
        for i in 0..info.output_file_count() {
            info.output_file_at(i)
                .to_str()
                .map(|x| output_files.insert(x.to_owned()));
        }
        let mut input_props = Vec::with_capacity(info.input_file_count());
        let mut output_props = Vec::with_capacity(info.output_file_count());
        let iter = info.table_properties().into_iter();
        for (file, properties) in iter {
            let ucp = UserCollectedPropertiesDecoder(properties.user_collected_properties());
            if let Ok(prop) = RangeProperties::decode(&ucp) {
                if input_files.contains(file) {
                    input_props.push(prop);
                } else if output_files.contains(file) {
                    output_props.push(prop);
                }
            } else {
                warn!("Decode size properties from sst file failed");
                return;
            }
        }

        if input_props.is_empty() && output_props.is_empty() {
            return;
        }

        let mut smallest_key = None;
        let mut largest_key = None;
        for prop in &input_props {
            if let Some(smallest) = prop.smallest_key() {
                if let Some(s) = smallest_key {
                    smallest_key = Some(cmp::min(s, smallest));
                } else {
                    smallest_key = Some(smallest);
                }
            }
            if let Some(largest) = prop.largest_key() {
                if let Some(l) = largest_key {
                    largest_key = Some(cmp::max(l, largest));
                } else {
                    largest_key = Some(largest);
                }
            }
        }

        if smallest_key.is_none() || largest_key.is_none() {
            return;
        }

        (self.ch)(RocksCompactedEvent::new(
            info,
            smallest_key.unwrap(),
            largest_key.unwrap(),
            input_props,
            output_props,
        ));
    }
}