-
-
Notifications
You must be signed in to change notification settings - Fork 408
Expand file tree
/
Copy pathlog_format_impls.cc
More file actions
2841 lines (2495 loc) · 103 KB
/
Copy pathlog_format_impls.cc
File metadata and controls
2841 lines (2495 loc) · 103 KB
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
/**
* Copyright (c) 2007-2017, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file log_format_impls.cc
*/
#include <algorithm>
#include <chrono>
#include <memory>
#include <mutex>
#include <utility>
#include "log_format.hh"
#include <stdio.h>
#include "base/humanize.hh"
#include "base/injector.bind.hh"
#include "base/separated_string.hh"
#include "base/string_attr_type.hh"
#include "config.h"
#include "formats/logfmt/logfmt.parser.hh"
#include "log_vtab_impl.hh"
#include "ptimec.hh"
#include "scn/scan.h"
#include "sql_util.hh"
#include "yajlpp/yajlpp.hh"
using std::string_literals::operator""s;
class piper_log_format : public log_format {
public:
const intern_string_t get_name() const override
{
static const intern_string_t RETVAL
= intern_string::lookup("lnav_piper_log");
return RETVAL;
}
scan_result_t scan(logfile& lf,
std::vector<logline>& dst,
const line_info& li,
shared_buffer_ref& sbr,
scan_batch_context& sbc) override
{
if (lf.has_line_metadata()
&& lf.get_text_format() == text_format_t::TF_LOG)
{
auto& ll = dst.back();
ll.set_time(li.li_timestamp);
ll.set_level(li.li_level);
return scan_match{1};
}
return scan_no_match{"not a piper capture"};
}
static constexpr int TIMESTAMP_SIZE = 28;
void annotate(logfile* lf,
uint64_t line_number,
string_attrs_t& sa,
logline_value_vector& values) const override
{
auto lr = line_range{0, TIMESTAMP_SIZE};
sa.emplace_back(lr, L_TIMESTAMP.value());
log_format::annotate(lf, line_number, sa, values);
}
void get_subline(const log_format_file_state& lffs,
const logline& ll,
shared_buffer_ref& sbr,
subline_options opts) override
{
this->plf_cached_line.resize(TIMESTAMP_SIZE);
auto tlen = sql_strftime(this->plf_cached_line.data(),
this->plf_cached_line.size(),
ll.get_timeval(),
'T');
this->plf_cached_line.resize(tlen);
{
char zone_str[16];
exttm tmptm;
tmptm.et_flags |= ETF_ZONE_SET;
tmptm.et_gmtoff
= lnav::local_time_to_info(
date::local_seconds{ll.get_time<std::chrono::seconds>()})
.first.offset.count();
off_t zone_len = 0;
ftime_z(zone_str, zone_len, sizeof(zone_str), tmptm);
for (off_t lpc = 0; lpc < zone_len; lpc++) {
this->plf_cached_line.push_back(zone_str[lpc]);
}
}
this->plf_cached_line.push_back(' ');
const auto prefix_len = this->plf_cached_line.size();
this->plf_cached_line.resize(this->plf_cached_line.size()
+ sbr.length());
memcpy(
&this->plf_cached_line[prefix_len], sbr.get_data(), sbr.length());
sbr.share(this->plf_share_manager,
this->plf_cached_line.data(),
this->plf_cached_line.size());
}
std::shared_ptr<log_format> specialized(scan_batch_context& sbc,
int fmt_lock) override
{
auto retval = std::make_shared<piper_log_format>(*this);
retval->lf_specialized = true;
retval->lf_timestamp_flags |= ETF_ZONE_SET | ETF_MICROS_SET;
return retval;
}
private:
shared_buffer plf_share_manager;
std::vector<char> plf_cached_line;
};
class o1_generic_log_format : public log_format {
public:
static const pcre_format* get_pcre_log_formats()
{
static const pcre_format log_fmt[] = {
pcre_format(R"(^(?:\*\*\*\s+)?(?<timestamp>@[0-9a-zA-Z]{16,24}))"),
pcre_format(
R"((?x)^
(?:\*\*\*\s+)? # optional "*** " prefix
(?<timestamp>
(?:
\s
| \d{4}[\-\/]\d{2}[\-\/]\d{2} # YYYY-MM-DD or YYYY/MM/DD
| T # ISO date/time separator
| \d{1,2}:\d{2}(?::\d{2}(?:[\.,]\d{1,9})?)? # HH:MM[:SS[.frac]]
| Z # UTC zulu marker
| [+\-]\d{2}:?\d{2} # timezone offset, +0500 or +05:00
| (?!DBG|DEBUG\d?|ERR|INFO|WARN|NONE|CRITICAL|FATAL) # ...not one of these levels
[A-Z]{3,4} # 3-4 uppercase letters (e.g. month/tz abbrev)
)+
)
(?: \d+)?
[:|\s\]]? # optional separator
(trc|trace|critical|fatal|dbg\d?|debug\d?|info|warn(?:ing)?|err(?:or)?) # log level
[:|\s] # separator
\s*
)"),
pcre_format(
R"(^(?:\*\*\*\s+)?(?<timestamp>[\w:+ \.,+/-]+) \[(trace|debug\d?|info|warn(?:ing)?|error|critical|fatal)\]\s+)"),
pcre_format(
R"(^(?:\*\*\*\s+)?\[(?<timestamp>[\w:+ \.,+/-]+)\] \[(trace|debug\d?|info|warn(?:ing)?|error|critical|fatal)\]\s+)"),
pcre_format(
R"(^(?:\*\*\*\s+)?(?<timestamp>[\w:+ \.,+/-]+) (?:-- )?(trace|debug\d?|info|warn(?:ing)?|error|critical|fatal)(?: --)?\s+)"),
pcre_format(R"(^(?:\*\*\*\s+)?(?<timestamp>\w.*))"),
pcre_format(),
};
return log_fmt;
}
std::string get_pattern_regex(const pattern_locks& pl,
uint64_t line_number) const override
{
auto pat_index = pl.pattern_index_for_line(line_number);
return get_pcre_log_formats()[pat_index].name;
}
const intern_string_t get_name() const override
{
static const intern_string_t RETVAL
= intern_string::lookup("generic_log");
return RETVAL;
}
scan_result_t scan(logfile& lf,
std::vector<logline>& dst,
const line_info& li,
shared_buffer_ref& sbr,
scan_batch_context& sbc) override
{
sbc.seed_for(this);
exttm log_time;
timeval log_tv;
string_fragment ts;
std::optional<string_fragment> level;
const char* last_pos;
if (dst.size() == 1) {
auto file_options = lf.get_file_options();
if (file_options) {
sbc.sbc_time_scanner.dts_default_zone
= file_options->second.fo_default_zone.pp_value;
} else {
sbc.sbc_time_scanner.dts_default_zone = nullptr;
}
}
if ((last_pos = this->log_scanf(sbc,
dst.size(),
sbr.to_string_fragment(),
get_pcre_log_formats(),
nullptr,
&log_time,
&log_tv,
&ts,
&level))
!= nullptr)
{
auto level_val = log_level_t::LEVEL_UNKNOWN;
if (level) {
level_val = string2level(level->data(), level->length());
}
if (!((log_time.et_flags & ETF_DAY_SET)
&& (log_time.et_flags & ETF_MONTH_SET)
&& (log_time.et_flags & ETF_YEAR_SET)))
{
this->check_for_new_year(dst, log_time, log_tv, sbc);
}
if (!(this->timestamp_flags_for(sbc)
& (ETF_MILLIS_SET | ETF_MICROS_SET | ETF_NANOS_SET))
&& !dst.empty()
&& dst.back().get_time<std::chrono::seconds>().count()
== log_tv.tv_sec
&& dst.back()
.get_subsecond_time<std::chrono::microseconds>()
.count()
!= 0)
{
auto log_us
= dst.back()
.get_subsecond_time<std::chrono::microseconds>();
log_time.et_nsec
= std::chrono::duration_cast<std::chrono::nanoseconds>(
log_us)
.count();
log_tv.tv_usec
= std::chrono::duration_cast<std::chrono::microseconds>(
log_us)
.count();
}
auto log_us = to_us(log_tv);
sbc.sbc_tids.add_no_tid(log_us, level_val);
auto& ll = dst.back();
ll.set_time(log_us);
ll.set_level(level_val);
return scan_match{5};
}
return scan_no_match{"no patterns matched"};
}
void annotate(logfile* lf,
uint64_t line_number,
string_attrs_t& sa,
logline_value_vector& values) const override
{
thread_local auto md = lnav::pcre2pp::match_data::unitialized();
auto lffs = lf->get_format_file_state();
auto& line = values.lvv_sbr;
int pat_index
= lffs.lffs_pattern_locks.pattern_index_for_line(line_number);
const auto& fmt = get_pcre_log_formats()[pat_index];
const auto line_sf = line.to_string_fragment();
auto match_res = fmt.pcre->capture_from(line_sf)
.into(md)
.matches(PCRE2_NO_UTF_CHECK)
.ignore_error();
if (!match_res) {
return;
}
int prefix_len = md.remaining().sf_begin;
auto ts_cap = md[fmt.pf_timestamp_index].value();
auto lr = to_line_range(ts_cap.trim());
auto level_cap = md[2];
if (!level_cap) {
lr.lr_end = prefix_len
= lr.lr_start + lf->get_time_scanner().dts_fmt_len;
auto rem_sf = line_sf.substr(prefix_len);
auto body_sf = rem_sf.consume(isspace);
if (body_sf) {
prefix_len = body_sf->sf_begin;
}
}
sa.emplace_back(lr, L_TIMESTAMP.value());
values.lvv_values.emplace_back(TS_META, line, lr);
values.lvv_values.back().lv_meta.lvm_format = (log_format*) this;
if (level_cap) {
if (string2level(level_cap->data(), level_cap->length(), true)
!= LEVEL_UNKNOWN)
{
values.lvv_values.emplace_back(
LEVEL_META, line, to_line_range(level_cap->trim()));
values.lvv_values.back().lv_meta.lvm_format
= (log_format*) this;
lr = to_line_range(level_cap->trim());
if (lr.lr_end != (ssize_t) line.length()) {
sa.emplace_back(lr, L_LEVEL.value());
}
}
}
lr.lr_start = 0;
lr.lr_end = prefix_len;
sa.emplace_back(lr, L_PREFIX.value());
if (prefix_len < line.length()) {
lr.lr_start = prefix_len;
lr.lr_end = line.length();
sa.emplace_back(lr, SA_BODY.value());
}
log_format::annotate(lf, line_number, sa, values);
}
std::shared_ptr<log_format> specialized(scan_batch_context& sbc,
int fmt_lock) override
{
auto retval = std::make_shared<o1_generic_log_format>(*this);
retval->lf_specialized = true;
return retval;
}
bool hide_field(const intern_string_t field_name, bool val) override
{
if (field_name == TS_META.lvm_name) {
TS_META.lvm_user_hidden = val;
return true;
}
if (field_name == LEVEL_META.lvm_name) {
LEVEL_META.lvm_user_hidden = val;
return true;
}
if (field_name == OPID_META.lvm_name) {
OPID_META.lvm_user_hidden = val;
return true;
}
return false;
}
std::map<intern_string_t, logline_value_meta> get_field_states() override
{
return {
{TS_META.lvm_name, TS_META},
{LEVEL_META.lvm_name, LEVEL_META},
{OPID_META.lvm_name, OPID_META},
};
}
private:
static logline_value_meta TS_META;
static logline_value_meta LEVEL_META;
static logline_value_meta OPID_META;
};
logline_value_meta o1_generic_log_format::TS_META{
intern_string::lookup("log_time"),
value_kind_t::VALUE_TEXT,
logline_value_meta::table_column{2},
};
logline_value_meta o1_generic_log_format::LEVEL_META{
intern_string::lookup("log_level"),
value_kind_t::VALUE_TEXT,
logline_value_meta::table_column{3},
};
logline_value_meta o1_generic_log_format::OPID_META{
intern_string::lookup("log_opid"),
value_kind_t::VALUE_TEXT,
logline_value_meta::internal_column{},
};
std::string
from_escaped_string(const char* str, size_t len)
{
std::string retval;
for (size_t lpc = 0; lpc < len; lpc++) {
switch (str[lpc]) {
case '\\':
if ((lpc + 3) < len && str[lpc + 1] == 'x') {
int ch;
if (sscanf(&str[lpc + 2], "%2x", &ch) == 1) {
retval.append(1, (char) ch & 0xff);
lpc += 3;
}
}
break;
default:
retval.append(1, str[lpc]);
break;
}
}
return retval;
}
// -----------------------------------------------------------------
// Recognizes CSV files whose first line is a header with a
// timestamp-like first column (`timestamp`, `time`, `ts`, or a name
// starting with `date`), and whose subsequent rows begin with a
// parseable timestamp. Tolerates a leading UTF-8 BOM, the
// Excel-style `sep=<ch>` delimiter hint, CRLF line endings, and
// CSV-style `""`-escaped double quotes inside quoted fields.
// The header line is emitted as an ignored logline so lnav stays
// locked to this format for the rest of the file.
//
// Each non-timestamp column is exposed as a `VALUE_FLOAT` field so
// queries such as `SELECT cpu_pct FROM metrics_log` work per-file.
// The cross-file long-format `all_metrics` SQL virtual table
// (source/metric/value across all loaded metric files) lives in
// `metrics_vtab.cc`.
// -----------------------------------------------------------------
class metrics_log_format : public log_format {
public:
metrics_log_format()
{
this->lf_multiline = false;
this->lf_is_metric = true;
this->lf_time_ordered = false;
this->lf_file_type = file_type_t::TABULAR;
}
const intern_string_t get_name() const override
{
static const intern_string_t RETVAL
= intern_string::lookup("metrics_log");
return RETVAL;
}
/** What this format works out from a metric file's CSV header. */
struct metrics_scan_state : format_scan_state {
std::vector<intern_string_t> mss_headers;
std::vector<logline_value_meta> mss_field_defs;
// Column separator; overridden by an Excel-style `sep=<ch>` hint
// on the first line of the file.
char mss_separator{','};
};
std::unique_ptr<format_scan_state> make_scan_state() const override
{
return std::make_unique<metrics_scan_state>();
}
void adopt_scan_state(format_scan_state& fss) override
{
this->mlf_state = std::move(static_cast<metrics_scan_state&>(fss));
}
/** @see bro_log_format::state_for() */
metrics_scan_state& state_for(scan_batch_context& sbc)
{
return this->lf_specialized ? this->mlf_state
: sbc.format_state<metrics_scan_state>();
}
scan_result_t parse_line(const string_fragment& line_sf,
std::vector<logline>& dst,
scan_batch_context& sbc)
{
auto& st = this->state_for(sbc);
separated_string ss{line_sf};
ss.with_separator(st.mss_separator);
if (!st.mss_headers.empty()) {
ss.ss_expected_count = st.mss_headers.size();
}
auto iter = ss.begin();
if (iter == ss.end()) {
return scan_error{"empty metric row"};
}
const auto ts_sf = *iter;
auto& dts = sbc.sbc_time_scanner;
exttm tm;
timeval tv;
if (dts.scan(ts_sf.data(), ts_sf.length(), nullptr, &tm, tv) == nullptr)
{
return scan_error{fmt::format(
FMT_STRING("metric row timestamp did not parse: {}"),
ts_sf.to_string())};
}
dst.back().set_time(to_us(tv));
// Propagate what the scanner learned (zone offset, subsecond
// precision) so downstream consumers can reproduce the
// timestamp in the right form.
this->timestamp_flags_for(sbc) |= tm.et_flags;
// Update per-column min/max stats. Every non-timestamp
// column is VALUE_FLOAT, so the field-def index maps 1:1
// onto `sbc_value_stats`. Dispatch on the iterator's
// `kind()` so integers skip the float parser and so unit-
// suffixed values (e.g. `1.5k`) fall back to `humanize`.
sbc.sbc_value_stats.resize(st.mss_field_defs.size());
++iter;
auto field_index = 0;
for (; iter != ss.end(); ++iter, ++field_index) {
if (field_index >= st.mss_field_defs.size()) {
return scan_error{
fmt::format(FMT_STRING("metric row has too many fields, "
"expecting only {} fields"),
st.mss_field_defs.size())};
}
auto& stats = sbc.sbc_value_stats[field_index];
// Track the widest raw cell so the LOG-view renderer can
// column-align values across rows.
const auto cell_len = static_cast<int64_t>((*iter).length());
if (cell_len > stats.lvs_width) {
stats.lvs_width = cell_len;
}
// Non-numeric cells get fed into the column's HLL distinct
// estimator instead of the numeric stats. Hash the raw
// cell bytes — CSV uses a consistent escape form for any
// given logical value, so unescape isn't required.
if (iter.kind() == separated_string::cell_kind::other) {
stats.add_text(*iter);
}
parse_cell(iter, parse_context::scan)
.match(
[](empty_cell) {},
[&stats](int64_t i) {
stats.add_value(static_cast<double>(i));
},
[&stats](double d) { stats.add_value(d); },
[&stats](humanized_cell hc) { stats.add_value(hc.value); },
[](const text_cell& tc) {});
}
if (field_index < st.mss_field_defs.size()) {
return scan_error{fmt::format(
FMT_STRING("metric row has too few fields: found {}, "
"expected {} fields"),
field_index,
st.mss_field_defs.size())};
}
if (!this->lf_specialized) {
auto number_cells = 0;
for (const auto& stats : sbc.sbc_value_stats) {
number_cells += stats.lvs_count;
}
if (number_cells == 0) {
return scan_error{"metric row has no numeric fields"};
}
}
return scan_match{500};
}
scan_result_t scan_int(std::vector<logline>& dst,
const line_info& li,
shared_buffer_ref& sbr,
scan_batch_context& sbc)
{
auto line_sf = sbr.to_string_fragment();
// Reindex (triggered by e.g. `:set-file-timezone`) clears
// `lf_index` but leaves `lf_specialized` set, so the first
// post-clear scan arrives here with an empty `dst`. Seed
// from epoch rather than reading `dst.back()` on an empty
// vector.
auto& ll = dst.back();
ll.set_level(LEVEL_STATS);
auto retval = this->parse_line(line_sf, dst, sbc);
return retval;
}
scan_result_t scan(logfile& lf,
std::vector<logline>& dst,
const line_info& li,
shared_buffer_ref& sbr,
scan_batch_context& sbc) override
{
sbc.seed_for(this);
auto& st = this->state_for(sbc);
if (li.li_partial) {
return scan_incomplete{};
}
// Keep the scanner's default zone in sync with the file's
// current options on every scan. `:set-file-timezone`
// mutates the options after the format has already specialized,
// so a once-at-detection sync leaves stale state and every
// subsequent timestamp parses against the wrong zone.
{
auto file_options = lf.get_file_options();
sbc.sbc_time_scanner.dts_default_zone = file_options
? file_options->second.fo_default_zone.pp_value
: nullptr;
}
if (this->lf_specialized) {
if (dst.size() == 1) {
// Reindex (e.g. after `:set-file-timezone`) clears
// `lf_index` and starts scanning from byte zero again.
// The format is still locked in from the prior pass,
// so just reproduce the header's ignored-logline so
// the data rows that follow land in `scan_int` with
// a valid `dst.back()`.
auto& ll = dst.back();
ll.set_level(LEVEL_UNKNOWN);
ll.set_ignore(true);
return scan_match{500};
}
// we've locked on, don't need to figure out the header
return scan_int(dst, li, sbr, sbc);
}
if (dst.size() < 2) {
return scan_no_match{"waiting for header and data row"};
}
if (dst.size() > 3) {
return scan_no_match{
"line is after CSV headers and first data row"};
}
// First part of the file — reset any per-file state left
// over from a prior file on this shared base instance.
st.mss_headers.clear();
st.mss_field_defs.clear();
st.mss_separator = ',';
auto has_sep_directive = false;
for (auto ll_iter = dst.begin(); ll_iter != dst.end(); ++ll_iter) {
if (ll_iter->get_sub_offset() != 0) {
continue;
}
auto read_res = lf.read_raw_message(ll_iter);
if (read_res.isErr()) {
return scan_no_match{"cannot read header"};
}
auto hdr_sbr = read_res.unwrap();
auto hdr_sf = hdr_sbr.to_string_fragment();
// Excel-flavor CSVs sometimes start with `sep=<ch>` to
// hint the delimiter. Consume that as metadata and wait
// for the real header on the next line.
if (ll_iter == dst.begin() && hdr_sf.startswith("sep=")) {
if (dst.size() == 1) {
return scan_no_match{"waiting for more data"};
}
const auto sep_sf = hdr_sf.substr(4);
if (sep_sf.empty()) {
return scan_error{"sep= hint missing separator character"};
}
st.mss_separator = sep_sf.data()[0];
ll_iter->set_time(std::chrono::microseconds::zero());
ll_iter->set_level(LEVEL_UNKNOWN);
ll_iter->set_ignore(true);
has_sep_directive = true;
log_info("metrics_log found 'sep=' header: %x",
st.mss_separator);
} else if (st.mss_headers.empty()) {
// Header row: require a shape like
// `timestamp,<name>,<name>...`. This is a conservative
// detector — files without a leading timestamp-named
// column are left to other formats.
separated_string ss{hdr_sf};
if (!has_sep_directive) {
auto detect_res
= separated_string::detect_separator(hdr_sf);
if (detect_res) {
st.mss_separator = detect_res.value();
log_info("metrics_log detected separator: %x",
st.mss_separator);
}
}
ss.with_separator(st.mss_separator);
std::vector<intern_string_t> fields;
for (auto iter = ss.begin(); iter != ss.end(); ++iter) {
// Header cells may be CSV-quoted (e.g. Grafana
// exports wrap PromQL expressions that contain
// commas or doubled quotes). Collapse `""` back
// to `"` so the interned column name matches what
// the user wrote.
fields.emplace_back(intern_string::lookup(
separated_string::unescape_quoted(*iter)));
}
if (fields.size() < 2) {
return scan_no_match{"too few columns for a metric CSV"};
}
const auto first = fields[0].to_string_fragment();
const bool is_time_header = first.iequal("timestamp"_frag)
|| first.iequal("time"_frag) || first.iequal("ts"_frag)
|| (first.length() >= 4
&& strncasecmp(first.data(), "date", 4) == 0);
if (!is_time_header) {
return scan_error{fmt::format(
FMT_STRING(
"first column '{}' is not a timestamp header "
"(expected 'timestamp', 'time', 'ts', or a "
"'date'-prefixed name)"),
first.to_string())};
}
st.mss_headers = std::move(fields);
log_info("metrics_log found %zu header columns",
st.mss_headers.size());
this->build_field_defs(st);
ll_iter->set_time(std::chrono::microseconds::zero());
ll_iter->set_level(LEVEL_UNKNOWN);
ll_iter->set_ignore(true);
} else {
auto scan_res = this->parse_line(hdr_sf, dst, sbc);
if (!scan_res.is<scan_match>()) {
log_warning("first data row did not match");
return scan_res;
}
ll_iter->set_level(LEVEL_STATS);
}
}
return this->scan_int(dst, li, sbr, sbc);
}
std::optional<size_t> stats_index_for_value(
const intern_string_t& name) const override
{
for (size_t i = 0; i < this->mlf_state.mss_field_defs.size(); ++i) {
if (this->mlf_state.mss_field_defs[i].lvm_name == name) {
return i;
}
}
return std::nullopt;
}
std::vector<logline_value_meta> get_value_metadata() const override
{
return this->mlf_state.mss_field_defs;
}
size_t get_value_metadata_count() const override
{
return this->mlf_state.mss_field_defs.size();
}
void annotate(logfile* lf,
uint64_t line_number,
string_attrs_t& sa,
logline_value_vector& values) const override
{
auto& sbr = values.lvv_sbr;
const auto line_sf = sbr.to_string_fragment().trim("\r\n");
separated_string ss{line_sf};
ss.with_separator(this->mlf_state.mss_separator);
for (auto iter = ss.begin(); iter != ss.end(); ++iter) {
const auto field = *iter;
const auto lr = line_range{field.sf_begin, field.sf_end};
if (iter.index() == 0) {
sa.emplace_back(lr, L_TIMESTAMP.value());
continue;
}
// The header row is emitted as an ignored logline, so
// `mlf_field_defs` (which excludes col 0) has one entry
// per data column. Extra trailing columns are dropped.
const auto field_index = iter.index() - 1;
if (field_index >= this->mlf_state.mss_field_defs.size()) {
break;
}
// Parse once rather than paying the re-parse cost each
// time SQL reads the cell. The variant preserves int vs
// float so the renderer can format integers without a
// trailing decimal point. The static `mlf_hidden_columns`
// registry is overlaid so hide state propagates across
// specialized instances that share column names.
auto meta = this->mlf_state.mss_field_defs[field_index];
if (mlf_hidden_columns.count(meta.lvm_name) != 0) {
meta.lvm_user_hidden = true;
}
parse_cell(iter, parse_context::annotate)
.match(
[&](empty_cell) { values.lvv_values.emplace_back(meta); },
[&](int64_t i) { values.lvv_values.emplace_back(meta, i); },
[&](double d) { values.lvv_values.emplace_back(meta, d); },
[&](humanized_cell hc) {
// Carry the detected unit on the per-value meta so
// downstream renderers can call humanize::format
// against the base-unit value.
auto cell_meta = meta;
cell_meta.lvm_unit_suffix = hc.unit_suffix;
values.lvv_values.emplace_back(cell_meta, hc.value);
},
[&](const text_cell& tc) {
values.lvv_values.emplace_back(meta, tc.value);
values.lvv_values.back().lv_meta.lvm_kind
= value_kind_t::VALUE_TEXT;
});
values.lvv_values.back().lv_origin = lr;
}
log_format::annotate(lf, line_number, sa, values);
}
std::shared_ptr<log_format> specialized(scan_batch_context& sbc,
int fmt_lock) override
{
auto retval = std::make_shared<metrics_log_format>(*this);
retval->lf_specialized = true;
return retval;
}
private:
// A parsed metric cell: either an int64, a double, or nothing
// (empty or unparseable). Keeping the original integer type
// lets the renderer format int cells without a decimal point,
// while callers that want a single numeric type can coerce via
// the `match` below.
struct empty_cell {};
// Humanized cell: the raw text had a recognized unit suffix
// ("1.5KB", "20ms", "2.5GHz"). The value is already normalized
// to the base unit (bytes, seconds, Hz) and `unit_suffix` carries
// the canonical suffix so downstream renderers can format it back
// to human-friendly form.
struct humanized_cell {
double value;
intern_string_t unit_suffix;
};
struct text_cell {
std::string value;
};
using parsed_cell_t = mapbox::util::
variant<empty_cell, int64_t, double, humanized_cell, text_cell>;
enum class parse_context {
scan,
annotate,
};
static parsed_cell_t parse_cell(const separated_string::iterator& iter,
parse_context pc)
{
const auto field = *iter;
switch (iter.kind()) {
case separated_string::cell_kind::empty: {
return parsed_cell_t{empty_cell{}};
}
case separated_string::cell_kind::integer: {
if (auto res = scn::scan_value<int64_t>(field.to_string_view()))
{
return parsed_cell_t{res->value()};
}
return parsed_cell_t{empty_cell{}};
}
case separated_string::cell_kind::floating: {
if (auto res = scn::scan_value<double>(field.to_string_view()))
{
return parsed_cell_t{res->value()};
}
return parsed_cell_t{empty_cell{}};
}
case separated_string::cell_kind::number_with_suffix: {
// Classifier already confirmed the shape is `<num><unit>`.
if (auto res = humanize::try_from<double>(field)) {
return parsed_cell_t{humanized_cell{
res->value,
intern_string::lookup(res->unit_suffix),
}};
}
return parsed_cell_t{empty_cell{}};
}
case separated_string::cell_kind::other: {
// Plain text; humanize wouldn't have parsed it.
switch (pc) {
case parse_context::scan:
// During scanning, treat unparseable text as
// empty so it doesn't mess with stats or
// trigger a type change on the column.
return parsed_cell_t{empty_cell{}};
case parse_context::annotate:
// During annotation, preserve the text so the
// renderer can show it and the user can query
// against it.
return parsed_cell_t{text_cell{
separated_string::unescape_quoted(field)}};
}
}
}
return parsed_cell_t{empty_cell{}};
}
void build_field_defs(metrics_scan_state& st)
{
st.mss_field_defs.clear();
// Columns 1..N (timestamp is column 0) become VALUE_FLOAT
// fields. Column names are kept verbatim from the header;
// the CREATE TABLE generator applies SQL quoting for names
// that need it. Pass `this` as the owning format so the
// field_overlay_source treats these as real table fields
// (show/hide, chart, etc.) rather than skipping them.
for (size_t h = 1; h < st.mss_headers.size(); ++h) {
st.mss_field_defs.emplace_back(
st.mss_headers[h],
value_kind_t::VALUE_FLOAT,
logline_value_meta::table_column{h - 1},
this);
if (mlf_hidden_columns.count(st.mss_headers[h]) != 0) {
st.mss_field_defs.back().lvm_user_hidden = true;
}
}
}
public:
// Hide state lives in a static set instead of on the meta so it
// survives file re-detection (which rebuilds `mlf_field_defs` from
// scratch) and propagates across every specialized instance that
// shares the column name. Only the currently-hidden columns are
// tracked — showing a column erases its entry rather than storing
// `false`, so the set stays bounded across hide/show cycles.
bool hide_field(const intern_string_t field_name, bool val) override
{
if (val) {
mlf_hidden_columns.insert(field_name);
} else {
mlf_hidden_columns.erase(field_name);
}
for (auto& meta : this->mlf_state.mss_field_defs) {
if (meta.lvm_name == field_name) {
if (val) {
meta.lvm_user_hidden = true;
} else {
meta.lvm_user_hidden.reset();
}
}
}
return true;
}
std::map<intern_string_t, logline_value_meta> get_field_states() override
{
std::map<intern_string_t, logline_value_meta> retval;
for (const auto& meta : this->mlf_state.mss_field_defs) {
retval.emplace(meta.lvm_name, meta);
}
// Include columns that were hidden before this instance saw
// its header, so session save still captures them.
for (const auto& name : mlf_hidden_columns) {
if (retval.count(name) != 0) {
continue;
}
logline_value_meta meta{name, value_kind_t::VALUE_FLOAT};
meta.lvm_user_hidden = true;
retval.emplace(name, std::move(meta));
}
return retval;
}
metrics_scan_state mlf_state;
// User-hidden metric column names. Shared across every
// `metrics_log_format` instance so hides set via
// `:hide-fields metrics_log.<col>` affect every open metric file
// that has the column, and survive file re-detection (which
// rebuilds `mlf_field_defs`). Only currently-hidden columns are