-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathapp.rs
1509 lines (1345 loc) · 53.6 KB
/
app.rs
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// std imports
use std::{
cmp::{Reverse, max},
collections::BTreeMap,
convert::{TryFrom, TryInto},
fs,
io::{BufWriter, Write},
iter::repeat,
num::NonZeroUsize,
ops::Range,
path::PathBuf,
rc::Rc,
sync::Arc,
time::{Duration, Instant},
};
// unix-only std imports
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
// third-party imports
use closure::closure;
use crossbeam_channel::{self as channel, Receiver, RecvError, RecvTimeoutError, Sender};
use crossbeam_utils::thread;
use enumset::{EnumSet, enum_set};
use enumset_ext::EnumSetExt;
use itertools::{Itertools, izip};
use serde::{Deserialize, Serialize};
// local imports
use crate::{
IncludeExcludeKeyFilter,
appdirs::AppDirs,
datefmt::{DateTimeFormat, DateTimeFormatter},
error::*,
fmtx::aligned_left,
formatting::{RawRecordFormatter, RecordFormatter, RecordWithSourceFormatter},
fsmon::{self, EventKind},
index::{Indexer, IndexerSettings, Timestamp},
input::{BlockLine, Input, InputHolder, InputReference},
model::{Filter, Parser, ParserSettings, RawRecord, Record, RecordFilter, RecordWithSourceConstructor},
query::Query,
scanning::{BufFactory, Delimit, Delimiter, Scanner, SearchExt, Segment, SegmentBuf, SegmentBufFactory},
settings::{FieldShowOption, Fields, Formatting, InputInfo},
theme::{Element, StylingPush, Theme},
timezone::Tz,
vfs::LocalFileSystem,
};
// TODO: merge Options to Settings and replace Options with Settings.
// ---
pub struct Options {
pub theme: Arc<Theme>,
pub time_format: DateTimeFormat,
pub raw: bool,
pub raw_fields: bool,
pub allow_prefix: bool,
pub buffer_size: NonZeroUsize,
pub max_message_size: NonZeroUsize,
pub concurrency: usize,
pub filter: Arc<AdvancedFilter>,
pub fields: FieldOptions,
pub formatting: Formatting,
pub time_zone: Tz,
pub hide_empty_fields: bool,
pub sort: bool,
pub follow: bool,
pub sync_interval: Duration,
pub input_info: InputInfoSet,
pub input_format: Option<InputFormat>,
pub dump_index: bool,
pub app_dirs: Option<AppDirs>,
pub tail: u64,
pub delimiter: Delimiter,
pub unix_ts_unit: Option<UnixTimestampUnit>,
pub flatten: bool,
}
impl Options {
#[cfg(test)]
fn with_theme(self, theme: Arc<Theme>) -> Self {
Self { theme, ..self }
}
#[cfg(test)]
fn with_fields(self, fields: FieldOptions) -> Self {
Self { fields, ..self }
}
#[cfg(test)]
fn with_raw_fields(self, raw_fields: bool) -> Self {
Self { raw_fields, ..self }
}
#[cfg(test)]
fn with_raw(self, raw: bool) -> Self {
Self { raw, ..self }
}
#[cfg(test)]
fn with_sort(self, sort: bool) -> Self {
Self { sort, ..self }
}
#[cfg(test)]
fn with_filter(self, filter: Arc<AdvancedFilter>) -> Self {
Self { filter, ..self }
}
#[cfg(test)]
fn with_input_info(self, input_info: InputInfoSet) -> Self {
Self { input_info, ..self }
}
}
pub type InputInfoSet = EnumSet<InputInfo>;
#[derive(Default)]
pub struct AdvancedFilter {
pub basic: Filter,
pub query: Option<Query>,
}
impl AdvancedFilter {
pub fn new(basic: Filter, query: Option<Query>) -> Self {
Self { basic, query }
}
pub fn is_empty(&self) -> bool {
self.basic.is_empty() && self.query.is_none()
}
}
impl RecordFilter for AdvancedFilter {
#[inline]
fn apply<'a>(&self, record: &'a Record) -> bool {
self.basic.apply(record) && self.query.apply(record)
}
}
impl From<&Arc<AdvancedFilter>> for Query {
fn from(options: &Arc<AdvancedFilter>) -> Self {
if options.is_empty() {
Query::default()
} else {
Query::new(options.clone())
}
}
}
impl From<Filter> for AdvancedFilter {
fn from(filter: Filter) -> Self {
Self::new(filter, None)
}
}
impl From<Filter> for Arc<AdvancedFilter> {
fn from(filter: Filter) -> Self {
Self::new(filter.into())
}
}
#[derive(Default)]
pub struct FieldOptions {
pub filter: Arc<IncludeExcludeKeyFilter>,
pub settings: Fields,
}
#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum InputFormat {
Json,
Logfmt,
}
// ---
#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum UnixTimestampUnit {
Seconds,
Milliseconds,
Microseconds,
Nanoseconds,
}
impl UnixTimestampUnit {
pub fn guess(ts: i64) -> Self {
match ts {
Self::TS_UNIX_AUTO_S_MIN..=Self::TS_UNIX_AUTO_S_MAX => Self::Seconds,
Self::TS_UNIX_AUTO_MS_MIN..=Self::TS_UNIX_AUTO_MS_MAX => Self::Milliseconds,
Self::TS_UNIX_AUTO_US_MIN..=Self::TS_UNIX_AUTO_US_MAX => Self::Microseconds,
_ => Self::Nanoseconds,
}
}
const TS_UNIX_AUTO_S_MIN: i64 = -62135596800;
const TS_UNIX_AUTO_S_MAX: i64 = 253402300799;
const TS_UNIX_AUTO_MS_MIN: i64 = Self::TS_UNIX_AUTO_S_MIN * 1000;
const TS_UNIX_AUTO_MS_MAX: i64 = Self::TS_UNIX_AUTO_S_MAX * 1000;
const TS_UNIX_AUTO_US_MIN: i64 = Self::TS_UNIX_AUTO_MS_MIN * 1000;
const TS_UNIX_AUTO_US_MAX: i64 = Self::TS_UNIX_AUTO_MS_MAX * 1000;
}
// ---
pub struct App {
options: Options,
}
pub type Output = dyn Write + Send + Sync;
impl App {
pub fn new(mut options: Options) -> Self {
if options.raw && options.input_info.intersects(InputInfo::None | InputInfo::Auto) {
options.input_info = InputInfo::None.into()
}
options.input_info = InputInfo::resolve(options.input_info.into());
Self { options }
}
pub fn run(&self, inputs: Vec<InputHolder>, output: &mut Output) -> Result<()> {
if self.options.follow {
self.follow(inputs.into_iter().map(|x| x.reference).collect(), output)
} else if self.options.sort {
self.sort(inputs, output)
} else {
self.cat(inputs, output)
}
}
fn cat(&self, inputs: Vec<InputHolder>, output: &mut Output) -> Result<()> {
let input_badges = self.input_badges(inputs.iter().map(|x| &x.reference));
let inputs = inputs
.into_iter()
.map(|x| x.open())
.collect::<std::io::Result<Vec<_>>>()?;
let n = self.options.concurrency;
let sfi = Arc::new(SegmentBufFactory::new(self.options.buffer_size.try_into()?));
let bfo = BufFactory::new(self.options.buffer_size.try_into()?);
let parser = self.parser();
thread::scope(|scope| -> Result<()> {
// prepare receive/transmit channels for input data
let (txi, rxi): (Vec<_>, Vec<_>) = (0..n).map(|_| channel::bounded(1)).unzip();
// prepare receive/transmit channels for output data
let (txo, rxo): (Vec<_>, Vec<_>) = (0..n).into_iter().map(|_| channel::bounded::<(usize, SegmentBuf)>(1)).unzip();
// spawn reader thread
let reader = scope.spawn(closure!(clone sfi, |_| -> Result<()> {
let mut tx = StripedSender::new(txi);
let scanner = Scanner::new(sfi, &self.options.delimiter);
for (i, mut input) in inputs.into_iter().enumerate() {
for item in scanner.items(&mut input.stream.as_sequential()).with_max_segment_size(self.options.max_message_size.into()) {
if tx.send((i, item?)).is_none() {
break;
}
}
}
Ok(())
}));
// spawn processing threads
for (rxi, txo) in izip!(rxi, txo) {
scope.spawn(closure!(ref bfo, ref parser, ref sfi, ref input_badges, |_| {
let mut processor = self.new_segment_processor(&parser);
for (i, segment) in rxi.iter() {
let prefix = input_badges.as_ref().map(|b|b[i].as_str()).unwrap_or("");
match segment {
Segment::Complete(segment) => {
let mut buf = bfo.new_buf();
processor.process(segment.data(), &mut buf, prefix, None, &mut RecordIgnorer{});
sfi.recycle(segment);
if let Err(_) = txo.send((i, buf.into())) {
break;
};
}
Segment::Incomplete(segment, _) => {
if let Err(_) = txo.send((i, segment)) {
break;
}
}
}
}
}));
}
// spawn writer thread
let writer = scope.spawn(closure!(ref bfo, |_| -> Result<()> {
for (_, buf) in StripedReceiver::new(rxo) {
output.write_all(buf.data())?;
bfo.recycle(buf.into_inner());
}
Ok(())
}));
// collect errors from reader and writer threads
reader.join().unwrap()?;
writer.join().unwrap()?;
Ok(())
})
.unwrap()?;
Ok(())
}
fn sort(&self, inputs: Vec<InputHolder>, output: &mut Output) -> Result<()> {
let mut output = BufWriter::new(output);
let indexer_settings = IndexerSettings::new(
LocalFileSystem,
self.options.buffer_size.try_into()?,
self.options.max_message_size.try_into()?,
&self.options.fields.settings.predefined,
self.options.delimiter.clone(),
self.options.allow_prefix,
self.options.unix_ts_unit,
self.options.input_format,
);
let param_hash = hex::encode(indexer_settings.hash()?);
let cache_dir = self
.options
.app_dirs
.as_ref()
.map(|dirs| dirs.cache_dir.clone())
.unwrap_or_else(|| PathBuf::from(".cache"))
.join(param_hash);
fs::create_dir_all(&cache_dir)?;
let indexer = Indexer::new(self.options.concurrency, cache_dir, indexer_settings);
let input_badges = self.input_badges(inputs.iter().map(|x| &x.reference));
let inputs = inputs
.into_iter()
.map(|x| x.index(&indexer))
.collect::<Result<Vec<_>>>()?;
if self.options.dump_index {
for input in inputs {
for block in input.into_blocks().sorted() {
writeln!(output, "block at {} with size {}", block.offset(), block.size())?;
writeln!(output, "{:#?}", block.source_block())?;
let block_offset = block.offset();
for line in block.into_lines()? {
writeln!(
output,
"{} bytes at {} (absolute {})",
line.len(),
line.offset(),
block_offset + line.offset() as u64
)?;
}
}
}
return Ok(());
}
let n = self.options.concurrency;
let parser = self.parser();
thread::scope(|scope| -> Result<()> {
// prepare transmit/receive channels for data produced by pusher thread
let (txp, rxp): (Vec<_>, Vec<_>) = (0..n).map(|_| channel::bounded(1)).unzip();
// prepare transmit/receive channels for data produced by worker threads
let (txw, rxw): (Vec<_>, Vec<_>) = (0..n)
.map(|_| channel::bounded::<(OutputBlock, usize, usize)>(1))
.unzip();
// spawn pusher thread
let pusher = scope.spawn(closure!(|_| -> Result<()> {
let mut blocks: Vec<_> = inputs
.into_iter()
.enumerate()
.map(|(i, input)| input.into_blocks().map(move |block| (block, i)))
.flatten()
.filter_map(|(block, i)| {
let src = block.source_block();
if src.stat.lines_valid == 0 {
return None;
}
if let Some((ts_min, ts_max)) = src.stat.ts_min_max {
if let Some(until) = self.options.filter.basic.until {
if ts_min > until.into() {
return None;
}
}
if let Some(since) = self.options.filter.basic.since {
if ts_max < since.into() {
return None;
}
}
if let Some(level) = self.options.filter.basic.level {
if !src.match_level(level) {
return None;
}
}
let offset = block.offset();
Some((block, ts_min, ts_max, i, offset))
} else {
None
}
})
.collect();
blocks.sort_by(|a, b| (a.1, a.2, a.3, a.4).partial_cmp(&(b.1, b.2, b.3, b.4)).unwrap());
let mut output = StripedSender::new(txp);
for (j, (block, ts_min, _, i, _)) in blocks.into_iter().enumerate() {
if output.send((block, ts_min, i, j)).is_none() {
break;
}
}
Ok(())
}));
// spawn worker threads
let mut workers = Vec::with_capacity(n);
for (rxp, txw) in izip!(rxp, txw) {
workers.push(scope.spawn(closure!(ref parser, |_| -> Result<()> {
let mut processor = self.new_segment_processor(&parser);
for (block, ts_min, i, j) in rxp.iter() {
let mut buf = Vec::with_capacity(2 * usize::try_from(block.size())?);
let mut items = Vec::with_capacity(2 * usize::try_from(block.lines_valid())?);
for line in block.into_lines()? {
if line.len() == 0 {
continue;
}
processor.process(
line.bytes(),
&mut buf,
"",
Some(1),
&mut |record: &Record, location: Range<usize>| {
if let Some(ts) = &record.ts {
if let Some(unix_ts) = ts.unix_utc() {
items.push((unix_ts.into(), location));
} else {
log::warn!(
"skipped a message because its timestamp could not be parsed: {:#?}",
ts.raw()
)
}
}
},
);
}
let buf = Arc::new(buf);
if txw.send((OutputBlock { ts_min, buf, items }, i, j)).is_err() {
break;
}
}
Ok(())
})));
}
// spawn merger thread
let merger = scope.spawn(|_| -> Result<()> {
let mut input = StripedReceiver::new(rxw);
let (mut tsi, mut tso) = (None, None);
let mut workspace = Vec::new();
let mut done = false;
// Workspace rules
// 1. Can process messages up to max `ts_min` of the blocks in workspace
// 2. Can process any messages if workspace is complete (has all remaining blocks)
// 3. Should be sorted by (head (next line timestamp), input, block number, offset)
loop {
while tso >= tsi || workspace.len() == 0 {
if let Some((block, i, j)) = input.next() {
tsi = Some(block.ts_min.clone());
tso = tso.or(tsi);
let mut tail = block.into_lines();
let head = tail.next();
if let Some(head) = head {
workspace.push((head, tail, i, j));
}
} else {
done = true;
break;
}
}
if done && workspace.len() == 0 {
break;
}
workspace.sort_by_key(|v| Reverse(((v.0).0, v.2, v.3, (v.0).1.offset())));
let k = workspace.len() - 1;
let item = &mut workspace[k];
let ts = (item.0).0;
tso = Some(ts);
if tso >= tsi && !done {
continue;
}
if let Some(badges) = &input_badges {
output.write_all(&badges[item.2].as_bytes())?;
}
output.write_all((item.0).1.bytes())?;
output.write_all(&[b'\n'])?;
match item.1.next() {
Some(head) => item.0 = head,
None => drop(workspace.swap_remove(k)),
}
}
Ok(())
});
pusher.join().unwrap()?;
for worker in workers {
worker.join().unwrap()?;
}
merger.join().unwrap()?;
Ok(())
})
.unwrap()?;
Ok(())
}
fn follow(&self, inputs: Vec<InputReference>, output: &mut Output) -> Result<()> {
let input_badges = self.input_badges(inputs.iter());
let m = inputs.len();
let n = self.options.concurrency;
let parser = self.parser();
let sfi = Arc::new(SegmentBufFactory::new(self.options.buffer_size.try_into()?));
let bfo = BufFactory::new(self.options.buffer_size.try_into()?);
thread::scope(|scope| -> Result<()> {
// prepare receive/transmit channels for input data
let (txi, rxi) = channel::bounded(1);
// prepare receive/transmit channels for output data
let (txo, rxo) = channel::bounded(1);
// spawn reader threads
let mut readers = Vec::with_capacity(m);
for (i, input_ref) in inputs.into_iter().enumerate() {
let reader = scope.spawn(closure!(clone sfi, clone txi, |_| -> Result<()> {
let scanner = Scanner::new(sfi.clone(), &self.options.delimiter);
let mut meta = None;
if let InputReference::File(path) = &input_ref {
meta = Some(fs::metadata(&path.canonical)?);
}
let mut input = Some(input_ref.open()?.tail(self.options.tail)?);
let is_file = |meta: &Option<fs::Metadata>| meta.as_ref().map(|m|m.is_file()).unwrap_or(false);
let process = |input: &mut Option<Input>, is_file: bool| {
if let Some(input) = input {
for (j, item) in scanner.items(&mut input.stream.as_sequential()).with_max_segment_size(self.options.max_message_size.into()).enumerate() {
if txi.send((i, j, item?)).is_err() {
break;
}
}
Ok(!is_file)
} else {
Ok(false)
}
};
if let InputReference::File(path) = &input_ref {
if process(&mut input, is_file(&meta))? {
return Ok(())
}
fsmon::run(vec![path.canonical.clone()], |event| {
match event.kind {
EventKind::Modify(_) | EventKind::Create(_) | EventKind::Any | EventKind::Other => {
if let (Some(old_meta), Ok(new_meta)) = (&meta, fs::metadata(&path.canonical)) {
if old_meta.len() > new_meta.len() {
input = None;
}
#[cfg(unix)]
if old_meta.ino() != new_meta.ino() || old_meta.dev() != new_meta.dev() {
input = None;
}
meta = Some(new_meta);
}
if input.is_none() {
input = input_ref.open().ok();
}
if process(&mut input, is_file(&meta))? {
return Ok(())
}
Ok(())
}
EventKind::Remove(_) => {
input = None;
Ok(())
},
EventKind::Access(_) => Ok(()),
}
})
} else {
process(&mut input, is_file(&meta)).map(|_|())
}
}));
readers.push(reader);
}
drop(txi);
// spawn processing threads
let mut workers = Vec::with_capacity(n);
for _ in 0..n {
let worker = scope.spawn(closure!(ref bfo, ref parser, ref sfi, ref input_badges, clone rxi, clone txo, |_| {
let mut processor = self.new_segment_processor(&parser);
for (i, j, segment) in rxi.iter() {
let prefix = input_badges.as_ref().map(|b|b[i].as_str()).unwrap_or("");
match segment {
Segment::Complete(segment) => {
let mut buf = bfo.new_buf();
let mut index_builder = TimestampIndexBuilder{result: TimestampIndex::new(j)};
processor.process(segment.data(), &mut buf, prefix, None, &mut index_builder);
sfi.recycle(segment);
if txo.send((i, buf, index_builder.result)).is_err() {
return;
};
}
Segment::Incomplete(_, _) => {}
}
}
}));
workers.push(worker);
}
drop(txo);
// spawn merger thread
let merger = scope.spawn(move |_| -> Result<()> {
type Key = (Timestamp, usize, usize, usize); // (ts, input, block, offset)
type Line = (Rc<Vec<u8>>, Range<usize>, Instant); // (buf, location, instant)
let mut window = BTreeMap::<Key,Line>::new();
let mut last_ts: Option<Timestamp> = None;
let mut prev_ts: Option<Timestamp> = None;
let mut mem_usage = 0;
let mem_limit = n * usize::from(self.options.buffer_size);
loop {
let deadline = Instant::now().checked_sub(self.options.sync_interval);
while let Some(first) = window.first_key_value() {
if deadline.map(|deadline| first.1.2 > deadline).unwrap_or(true) && mem_usage < mem_limit {
break;
}
if let Some(entry) = window.pop_first() {
let sync_indicator = if prev_ts.map(|ts| ts <= entry.0.0).unwrap_or(true) {
&self.options.theme.indicators.sync.synced
} else {
&self.options.theme.indicators.sync.failed
};
prev_ts = Some(entry.0.0);
mem_usage -= entry.1.1.end - entry.1.1.start;
output.write_all(sync_indicator.value.as_bytes())?;
output.write_all(&entry.1.0[entry.1.1.clone()])?;
output.write_all(&[b'\n'])?;
}
}
let next_ts = window.first_entry().map(|e|e.get().2);
let timeout = if let (Some(next_ts), Some(deadline)) = (next_ts, deadline) {
Some(max(deadline, next_ts) - next_ts)
} else {
None
};
match rxo.recv_timeout(timeout.unwrap_or(std::time::Duration::MAX)) {
Ok((i, buf, index)) => {
let buf = Rc::new(buf);
for line in index.lines {
last_ts = Some(last_ts.map(|last_ts| std::cmp::max(last_ts, line.ts)).unwrap_or(line.ts));
mem_usage += line.location.end - line.location.start;
let key = (line.ts, i, index.block, line.location.start);
let value = (buf.clone(), line.location, Instant::now());
window.insert(key, value);
}
}
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => {
if timeout.is_none() {
break
}
}
}
}
Ok(())
});
for reader in readers {
reader.join().unwrap()?;
}
for worker in workers {
worker.join().unwrap();
}
merger.join().unwrap()?;
Ok(())
})
.unwrap()?;
Ok(())
}
fn parser(&self) -> Parser {
Parser::new(ParserSettings::new(
&self.options.fields.settings.predefined,
&self.options.fields.settings.ignore,
self.options.unix_ts_unit,
))
}
fn formatter(&self) -> Box<dyn RecordWithSourceFormatter> {
if self.options.raw {
Box::new(RawRecordFormatter {})
} else {
Box::new(
RecordFormatter::new(
self.options.theme.clone(),
DateTimeFormatter::new(self.options.time_format.clone(), self.options.time_zone),
self.options.hide_empty_fields,
self.options.fields.filter.clone(),
self.options.formatting.clone(),
)
.with_field_unescaping(!self.options.raw_fields)
.with_flatten(self.options.flatten)
.with_always_show_time(self.options.fields.settings.predefined.time.show == FieldShowOption::Always)
.with_always_show_level(self.options.fields.settings.predefined.level.show == FieldShowOption::Always),
)
}
}
fn input_badges<'a, I: IntoIterator<Item = &'a InputReference>>(&self, inputs: I) -> Option<Vec<String>> {
let name = |input: &InputReference| match input {
InputReference::Stdin => "<stdin>".to_owned(),
InputReference::File(path) => path.original.to_string_lossy().to_string(),
};
let mut badges = inputs.into_iter().map(|x| name(x).chars().collect_vec()).collect_vec();
let ii = self.options.input_info;
const II: InputInfoSet = enum_set!(InputInfo::Minimal | InputInfo::Compact | InputInfo::Full);
if ii.intersection(II).is_empty() {
return None;
}
if ii.contains(InputInfo::None) && badges.len() < 2 {
return None;
}
let num_width = format!("{}", badges.len()).len();
let opt = &self.options.formatting.punctuation;
if ii.contains(InputInfo::Compact) {
let pl = common_prefix_len(&badges);
for badge in badges.iter_mut() {
let cl = opt.input_name_clipping.chars().count();
if badge.len() > 24 + cl + pl {
if pl > 7 {
*badge = opt
.input_name_common_part
.chars()
.chain(badge[pl - 4..pl + 8].iter().cloned())
.chain(opt.input_name_clipping.chars())
.chain(badge[badge.len() - 16..].iter().cloned())
.collect();
} else {
*badge = badge[0..pl + 12]
.iter()
.cloned()
.chain(opt.input_name_clipping.chars())
.chain(badge[badge.len() - 12..].iter().cloned())
.collect();
}
} else if pl > 7 {
*badge = opt
.input_name_common_part
.chars()
.chain(badge[pl - 4..].iter().cloned())
.collect();
}
}
}
if let Some(max_len) = badges.iter().map(|badge| badge.len()).max() {
for badge in badges.iter_mut() {
badge.extend(repeat(' ').take(max_len - badge.len()));
}
}
let mut result = Vec::with_capacity(badges.len());
for (i, badge) in badges.iter_mut().enumerate() {
let mut buf = Vec::with_capacity(badge.len() * 2);
self.options.theme.apply(&mut buf, &None, |s| {
s.element(Element::Input, |s| {
s.element(Element::InputNumber, |s| {
s.batch(|buf| buf.extend(opt.input_number_left_separator.as_bytes()));
s.element(Element::InputNumberInner, |s| {
s.batch(|buf| {
aligned_left(buf, num_width + 1, b' ', |mut buf| {
buf.extend_from_slice(opt.input_number_prefix.as_bytes());
buf.extend_from_slice(format!("{}", i).as_bytes());
});
buf.extend(opt.input_name_left_separator.as_bytes());
});
});
s.batch(|buf| buf.extend(opt.input_number_right_separator.as_bytes()));
});
if ii.intersects(InputInfo::Compact | InputInfo::Full) {
s.element(Element::InputName, |s| {
s.batch(|buf| buf.extend(opt.input_name_left_separator.as_bytes()));
s.element(Element::InputNameInner, |s| {
s.batch(|buf| {
buf.extend_from_slice(badge.iter().collect::<String>().as_bytes());
})
});
s.batch(|buf| buf.extend(opt.input_name_right_separator.as_bytes()));
});
}
});
});
result.push(String::from_utf8(buf).unwrap());
}
Some(result)
}
fn new_segment_processor<'a>(&'a self, parser: &'a Parser) -> impl SegmentProcess + 'a {
let options = SegmentProcessorOptions {
allow_prefix: self.options.allow_prefix,
allow_unparsed_data: self.options.filter.is_empty(),
delimiter: self.options.delimiter.clone(),
input_format: self.options.input_format,
};
SegmentProcessor::new(parser, self.formatter(), Query::from(&self.options.filter), options)
}
}
// ---
pub trait SegmentProcess {
fn process<O: RecordObserver>(
&mut self,
data: &[u8],
buf: &mut Vec<u8>,
prefix: &str,
limit: Option<usize>,
observer: &mut O,
);
}
// ---
#[derive(Default)]
pub struct SegmentProcessorOptions {
pub allow_prefix: bool,
pub allow_unparsed_data: bool,
pub delimiter: Delimiter,
pub input_format: Option<InputFormat>,
}
// ---
pub struct SegmentProcessor<'a, Formatter, Filter> {
parser: &'a Parser,
formatter: Formatter,
filter: Filter,
options: SegmentProcessorOptions,
delim: <Delimiter as Delimit>::Searcher,
}
impl<'a, Formatter: RecordWithSourceFormatter, Filter: RecordFilter> SegmentProcessor<'a, Formatter, Filter> {
pub fn new(parser: &'a Parser, formatter: Formatter, filter: Filter, options: SegmentProcessorOptions) -> Self {
let delim = options.delimiter.clone().into_searcher();
Self {
parser,
formatter,
filter,
options,
delim,
}
}
#[inline(always)]
fn show_unparsed(&self) -> bool {
self.options.allow_unparsed_data
}
}
impl<'a, Formatter: RecordWithSourceFormatter, Filter: RecordFilter> SegmentProcess
for SegmentProcessor<'a, Formatter, Filter>
{
fn process<O>(&mut self, data: &[u8], buf: &mut Vec<u8>, prefix: &str, limit: Option<usize>, observer: &mut O)
where
O: RecordObserver,
{
let mut i = 0;
let limit = limit.unwrap_or(usize::MAX);
for line in self.delim.split(data) {
if line.len() == 0 {
if self.show_unparsed() {
buf.push(b'\n');
}
continue;
}
let mut stream = RawRecord::parser()
.allow_prefix(self.options.allow_prefix)
.format(self.options.input_format)
.parse(line);
let mut parsed_some = false;
let mut produced_some = false;
let mut last_offset = 0;
while let Some(Ok(ar)) = stream.next() {
i += 1;
last_offset = ar.offsets.end;
if parsed_some {
buf.push(b'\n');
}
parsed_some = true;
let record = self.parser.parse(&ar.record);
if record.matches(&self.filter) {
let begin = buf.len();
buf.extend(prefix.as_bytes());
buf.extend(ar.prefix);
if ar.prefix.last().map(|&x| x == b' ') == Some(false) {
buf.push(b' ');
}
self.formatter.format_record(buf, record.with_source(&line[ar.offsets]));
let end = buf.len();
observer.observe_record(&record, begin..end);
produced_some = true;
}
if i >= limit {
break;
}
}
let remainder = if parsed_some { &line[last_offset..] } else { line };
if remainder.len() != 0 && self.show_unparsed() {
if !parsed_some {
buf.extend(prefix.as_bytes());
}
if !parsed_some || produced_some {
buf.extend_from_slice(remainder);
buf.push(b'\n');
}
} else if produced_some {
buf.push(b'\n');
}
}
}
}
// ---
pub trait RecordObserver {
fn observe_record<'a>(&mut self, record: &Record<'a>, location: Range<usize>);
}
// ---
pub struct RecordIgnorer {}
impl RecordObserver for RecordIgnorer {
#[inline]
fn observe_record<'a>(&mut self, _: &Record<'a>, _: Range<usize>) {}
}
// ---
struct TimestampIndexBuilder {
result: TimestampIndex,
}
impl RecordObserver for TimestampIndexBuilder {
#[inline]
fn observe_record<'a>(&mut self, record: &Record<'a>, location: Range<usize>) {
if let Some(ts) = record.ts.as_ref().and_then(|ts| ts.unix_utc()).map(|ts| ts.into()) {
self.result.lines.push(TimestampIndexLine { location, ts });
}
}
}
// ---
impl<T: FnMut(&Record, Range<usize>)> RecordObserver for T {
#[inline]
fn observe_record<'a>(&mut self, record: &Record<'a>, location: Range<usize>) {
self(record, location)
}
}
// ---
struct TimestampIndex {
block: usize,
lines: Vec<TimestampIndexLine>,
}
impl TimestampIndex {
fn new(block: usize) -> Self {
Self {