• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tstack / lnav / 23346808785-2859

20 Mar 2026 02:14PM UTC coverage: 69.012% (-0.009%) from 69.021%
23346808785-2859

push

github

tstack
[tests] update expected

52736 of 76416 relevant lines covered (69.01%)

522102.57 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.98
/src/log_format.cc
1
/**
2
 * Copyright (c) 2007-2015, Timothy Stack
3
 *
4
 * All rights reserved.
5
 *
6
 * Redistribution and use in source and binary forms, with or without
7
 * modification, are permitted provided that the following conditions are met:
8
 *
9
 * * Redistributions of source code must retain the above copyright notice, this
10
 * list of conditions and the following disclaimer.
11
 * * Redistributions in binary form must reproduce the above copyright notice,
12
 * this list of conditions and the following disclaimer in the documentation
13
 * and/or other materials provided with the distribution.
14
 * * Neither the name of Timothy Stack nor the names of its contributors
15
 * may be used to endorse or promote products derived from this software
16
 * without specific prior written permission.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
19
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
22
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29

30
#include <algorithm>
31
#include <chrono>
32
#include <memory>
33
#include <vector>
34

35
#include <fnmatch.h>
36
#include <stdio.h>
37
#include <string.h>
38

39
#include "base/fs_util.hh"
40
#include "base/humanize.hh"
41
#include "base/intern_string.hh"
42
#include "base/is_utf8.hh"
43
#include "base/itertools.enumerate.hh"
44
#include "base/itertools.hh"
45
#include "base/map_util.hh"
46
#include "base/opt_util.hh"
47
#include "base/snippet_highlighters.hh"
48
#include "base/string_attr_type.hh"
49
#include "base/string_util.hh"
50
#include "bookmarks.hh"
51
#include "command_executor.hh"
52
#include "config.h"
53
#include "fmt/format.h"
54
#include "lnav_util.hh"
55
#include "log_format_ext.hh"
56
#include "log_search_table.hh"
57
#include "log_vtab_impl.hh"
58
#include "logfile_sub_source.hh"
59
#include "ptimec.hh"
60
#include "readline_highlighters.hh"
61
#include "scn/scan.h"
62
#include "sql_util.hh"
63
#include "sqlite-extension-func.hh"
64
#include "sqlitepp.hh"
65
#include "yajlpp/yajlpp.hh"
66
#include "yajlpp/yajlpp_def.hh"
67

68
using namespace lnav::roles::literals;
69
using namespace std::chrono_literals;
70
using std::string_literals::operator""s;
71

72
static auto intern_lifetime = intern_string::get_table_lifetime();
73

74
constexpr string_attr_type<void> L_PREFIX("prefix");
75
constexpr string_attr_type<void> L_TIMESTAMP("timestamp");
76
constexpr string_attr_type<void> L_LEVEL("level");
77
constexpr string_attr_type<std::shared_ptr<logfile>> L_FILE("file");
78
constexpr string_attr_type<bookmark_metadata*> L_PARTITION("partition");
79
constexpr string_attr_type<void> L_OPID("opid");
80
constexpr string_attr_type<bookmark_metadata*> L_META("meta");
81

82
std::vector<std::shared_ptr<external_log_format>>
83
    external_log_format::GRAPH_ORDERED_FORMATS;
84

85
const intern_string_t log_format::LOG_TIME_STR
86
    = intern_string::lookup("log_time");
87
const intern_string_t log_format::LOG_LEVEL_STR
88
    = intern_string::lookup("log_level");
89
const intern_string_t log_format::LOG_OPID_STR
90
    = intern_string::lookup("log_opid");
91
const intern_string_t log_format::LOG_THREAD_ID_STR
92
    = intern_string::lookup("log_thread_id");
93

94
static constexpr uint32_t DATE_TIME_SET_FLAGS = ETF_YEAR_SET | ETF_MONTH_SET
95
    | ETF_DAY_SET | ETF_HOUR_SET | ETF_MINUTE_SET | ETF_SECOND_SET;
96

97
log_level_stats&
98
log_level_stats::operator|=(const log_level_stats& rhs)
886✔
99
{
100
    this->lls_error_count += rhs.lls_error_count;
886✔
101
    this->lls_warning_count += rhs.lls_warning_count;
886✔
102
    this->lls_total_count += rhs.lls_total_count;
886✔
103

104
    return *this;
886✔
105
}
106

107
log_op_description&
108
log_op_description::operator|=(const log_op_description& rhs)
380✔
109
{
110
    if (!this->lod_index && rhs.lod_index) {
380✔
111
        this->lod_index = rhs.lod_index;
×
112
    }
113
    if (this->lod_elements.size() < rhs.lod_elements.size()) {
380✔
114
        this->lod_elements = rhs.lod_elements;
×
115
    }
116

117
    return *this;
380✔
118
}
119

120
void
121
opid_time_range::clear()
×
122
{
123
    this->otr_range.invalidate();
×
124
    this->otr_sub_ops.clear();
×
125
    this->otr_level_stats = {};
×
126
}
127

128
opid_time_range&
129
opid_time_range::operator|=(const opid_time_range& rhs)
380✔
130
{
131
    this->otr_range |= rhs.otr_range;
380✔
132
    this->otr_description |= rhs.otr_description;
380✔
133
    this->otr_level_stats |= rhs.otr_level_stats;
380✔
134
    for (const auto& rhs_sub : rhs.otr_sub_ops) {
385✔
135
        bool found = false;
5✔
136

137
        for (auto& sub : this->otr_sub_ops) {
10✔
138
            if (sub.ostr_subid == rhs_sub.ostr_subid) {
5✔
139
                sub.ostr_range |= rhs_sub.ostr_range;
5✔
140
                found = true;
5✔
141
            }
142
        }
143
        if (!found) {
5✔
144
            this->otr_sub_ops.emplace_back(rhs_sub);
×
145
        }
146
    }
147
    std::stable_sort(this->otr_sub_ops.begin(), this->otr_sub_ops.end());
380✔
148

149
    return *this;
380✔
150
}
151

152
void
153
thread_id_time_range::clear()
×
154
{
155
    this->titr_range.invalidate();
×
156
    this->titr_level_stats = {};
×
157
}
158

159
thread_id_time_range&
160
thread_id_time_range::operator|=(const thread_id_time_range& rhs)
506✔
161
{
162
    this->titr_range |= rhs.titr_range;
506✔
163
    this->titr_level_stats |= rhs.titr_level_stats;
506✔
164

165
    return *this;
506✔
166
}
167

168
void
169
log_level_stats::update_msg_count(log_level_t lvl, int32_t amount)
39,709✔
170
{
171
    switch (lvl) {
39,709✔
172
        case LEVEL_FATAL:
3,170✔
173
        case LEVEL_CRITICAL:
174
        case LEVEL_ERROR:
175
            this->lls_error_count += amount;
3,170✔
176
            break;
3,170✔
177
        case LEVEL_WARNING:
222✔
178
            this->lls_warning_count += amount;
222✔
179
            break;
222✔
180
        default:
36,317✔
181
            break;
36,317✔
182
    }
183
    this->lls_total_count += amount;
39,709✔
184
}
39,709✔
185

186
void
187
opid_time_range::close_sub_ops(const string_fragment& subid)
×
188
{
189
    for (auto& other_sub : this->otr_sub_ops) {
×
190
        if (other_sub.ostr_subid == subid) {
×
191
            other_sub.ostr_open = false;
×
192
        }
193
    }
194
}
195

196
log_thread_id_map::iterator
197
log_thread_id_state::insert_tid(ArenaAlloc::Alloc<char>& alloc,
12,707✔
198
                                const string_fragment& tid,
199
                                const std::chrono::microseconds& us)
200
{
201
    auto retval = this->ltis_tid_ranges.find(tid);
12,707✔
202
    if (retval == this->ltis_tid_ranges.end()) {
12,707✔
203
        auto tid_copy = tid.to_owned(alloc);
7,417✔
204
        auto titr = thread_id_time_range{time_range{us, us}};
7,417✔
205
        auto emplace_res = this->ltis_tid_ranges.emplace(tid_copy, titr);
7,417✔
206
        retval = emplace_res.first;
7,417✔
207
    } else {
208
        retval->second.titr_range.extend_to(us);
5,290✔
209
    }
210

211
    return retval;
12,707✔
212
}
213

214
log_opid_map::iterator
215
log_opid_state::insert_op(ArenaAlloc::Alloc<char>& alloc,
13,238✔
216
                          const string_fragment& opid,
217
                          const std::chrono::microseconds& us,
218
                          timestamp_point_of_reference_t poref,
219
                          std::chrono::microseconds duration)
220
{
221
    auto retval = this->los_opid_ranges.find(opid);
13,238✔
222
    if (retval == this->los_opid_ranges.end()) {
13,238✔
223
        auto opid_copy = opid.to_owned(alloc);
6,982✔
224
        auto otr = opid_time_range{time_range{us, us}};
6,982✔
225
        auto emplace_res = this->los_opid_ranges.emplace(opid_copy, otr);
6,982✔
226
        retval = emplace_res.first;
6,982✔
227
    } else {
6,982✔
228
        retval->second.otr_range.extend_to(us);
6,256✔
229
    }
230
    if (duration > 0us) {
13,238✔
231
        auto other_us = us;
104✔
232
        switch (poref) {
104✔
233
            case timestamp_point_of_reference_t::send:
18✔
234
                other_us -= duration;
18✔
235
                break;
18✔
236
            case timestamp_point_of_reference_t::start:
86✔
237
                other_us += duration;
86✔
238
                break;
86✔
239
        }
240
        retval->second.otr_range.extend_to(other_us);
104✔
241
    }
242

243
    return retval;
13,238✔
244
}
245

246
opid_sub_time_range*
247
log_opid_state::sub_op_in_use(ArenaAlloc::Alloc<char>& alloc,
62✔
248
                              log_opid_map::iterator& op_iter,
249
                              const string_fragment& subid,
250
                              const std::chrono::microseconds& us,
251
                              log_level_t level)
252
{
253
    const auto& opid = op_iter->first;
62✔
254
    auto sub_iter = this->los_sub_in_use.find(subid);
62✔
255
    if (sub_iter == this->los_sub_in_use.end()) {
62✔
256
        auto emp_res
257
            = this->los_sub_in_use.emplace(subid.to_owned(alloc), opid);
41✔
258

259
        sub_iter = emp_res.first;
41✔
260
    }
261

262
    auto retval = sub_iter->first;
62✔
263
    if (sub_iter->second != opid) {
62✔
264
        auto other_otr
265
            = lnav::map::find(this->los_opid_ranges, sub_iter->second);
×
266
        if (other_otr) {
×
267
            other_otr->get().close_sub_ops(retval);
×
268
        }
269
    }
270
    sub_iter->second = opid;
62✔
271

272
    auto& otr = op_iter->second;
62✔
273
    auto sub_op_iter = otr.otr_sub_ops.rbegin();
62✔
274
    for (; sub_op_iter != otr.otr_sub_ops.rend(); ++sub_op_iter) {
62✔
275
        if (sub_op_iter->ostr_open && sub_op_iter->ostr_subid == retval) {
21✔
276
            break;
21✔
277
        }
278
    }
279
    if (sub_op_iter == otr.otr_sub_ops.rend()) {
62✔
280
        otr.otr_sub_ops.emplace_back(opid_sub_time_range{
41✔
281
            retval,
282
            time_range{us, us},
283
        });
284
        otr.otr_sub_ops.back().ostr_level_stats.update_msg_count(level);
41✔
285

286
        return &otr.otr_sub_ops.back();
41✔
287
    } else {
288
        sub_op_iter->ostr_range.extend_to(us);
21✔
289
        sub_op_iter->ostr_level_stats.update_msg_count(level);
21✔
290
        return &(*sub_op_iter);
21✔
291
    }
292
}
293

294
std::optional<std::string>
295
log_format::opid_descriptor::matches(const string_fragment& sf) const
2,168✔
296
{
297
    if (this->od_extractor.pp_value) {
2,168✔
298
        thread_local auto desc_md = lnav::pcre2pp::match_data::unitialized();
334✔
299

300
        auto desc_match_res = this->od_extractor.pp_value->capture_from(sf)
334✔
301
                                  .into(desc_md)
334✔
302
                                  .matches(PCRE2_NO_UTF_CHECK | PCRE2_ANCHORED)
668✔
303
                                  .ignore_error();
334✔
304
        if (desc_match_res) {
334✔
305
            return desc_md.to_string();
66✔
306
        }
307

308
        return std::nullopt;
268✔
309
    }
310
    return sf.to_string();
1,834✔
311
}
312

313
std::string
314
log_format::opid_descriptors::to_string(
1,025✔
315
    const lnav::map::small<size_t, std::string>& lod) const
316
{
317
    std::string retval;
1,025✔
318

319
    for (size_t lpc = 0; lpc < this->od_descriptors->size(); lpc++) {
2,063✔
320
        retval.append(this->od_descriptors->at(lpc).od_prefix);
1,038✔
321
        auto val = lod.value_for(lpc);
1,038✔
322
        if (val) {
1,038✔
323
            retval.append(*val.value());
1,036✔
324
        }
325
        retval.append(this->od_descriptors->at(lpc).od_suffix);
1,038✔
326
    }
327

328
    return retval;
1,025✔
329
}
×
330

331
bool
332
logline_value_meta::is_numeric() const
×
333
{
334
    if (this->lvm_identifier || this->lvm_foreign_key) {
×
335
        return false;
×
336
    }
337
    switch (this->lvm_kind) {
×
338
        case value_kind_t::VALUE_FLOAT:
×
339
        case value_kind_t::VALUE_INTEGER:
340
            return true;
×
341
        default:
×
342
            return false;
×
343
    }
344
}
345

346
chart_type_t
347
logline_value_meta::to_chart_type() const
54✔
348
{
349
    auto retval = chart_type_t::hist;
54✔
350
    switch (this->lvm_kind) {
54✔
351
        case value_kind_t::VALUE_NULL:
9✔
352
            retval = chart_type_t::none;
9✔
353
            break;
9✔
354
        case value_kind_t::VALUE_INTEGER:
10✔
355
            if (!this->lvm_identifier && !this->lvm_foreign_key) {
10✔
356
                retval = chart_type_t::spectro;
5✔
357
            }
358
            break;
10✔
359
        case value_kind_t::VALUE_FLOAT:
×
360
            retval = chart_type_t::spectro;
×
361
            break;
×
362
        case value_kind_t::VALUE_XML:
1✔
363
        case value_kind_t::VALUE_JSON:
364
        case value_kind_t::VALUE_BOOLEAN:
365
        case value_kind_t::VALUE_TIMESTAMP:
366
            retval = chart_type_t::none;
1✔
367
            break;
1✔
368
        default:
34✔
369
            break;
34✔
370
    }
371

372
    return retval;
54✔
373
}
374

375
struct line_range
376
logline_value::origin_in_full_msg(const char* msg, ssize_t len) const
×
377
{
378
    if (this->lv_sub_offset == 0) {
×
379
        return this->lv_origin;
×
380
    }
381

382
    if (len == -1) {
×
383
        len = strlen(msg);
×
384
    }
385

386
    struct line_range retval = this->lv_origin;
×
387
    const char *last = msg, *msg_end = msg + len;
×
388

389
    for (int lpc = 0; lpc < this->lv_sub_offset; lpc++) {
×
390
        const auto* next = (const char*) memchr(last, '\n', msg_end - last);
×
391
        require(next != nullptr);
×
392

393
        next += 1;
×
394
        int amount = (next - last);
×
395

396
        retval.lr_start += amount;
×
397
        if (retval.lr_end != -1) {
×
398
            retval.lr_end += amount;
×
399
        }
400

401
        last = next + 1;
×
402
    }
403

404
    if (retval.lr_end == -1) {
×
405
        const auto* eol = (const char*) memchr(last, '\n', msg_end - last);
×
406

407
        if (eol == nullptr) {
×
408
            retval.lr_end = len;
×
409
        } else {
410
            retval.lr_end = eol - msg;
×
411
        }
412
    }
413

414
    return retval;
×
415
}
416

417
logline_value::logline_value(logline_value_meta lvm,
641,787✔
418
                             shared_buffer_ref& sbr,
419
                             struct line_range origin)
641,787✔
420
    : lv_meta(std::move(lvm)), lv_origin(origin)
641,787✔
421
{
422
    if (sbr.get_data() == nullptr) {
641,787✔
423
        this->lv_meta.lvm_kind = value_kind_t::VALUE_NULL;
×
424
    }
425

426
    switch (this->lv_meta.lvm_kind) {
641,787✔
427
        case value_kind_t::VALUE_JSON:
327,848✔
428
        case value_kind_t::VALUE_XML:
429
        case value_kind_t::VALUE_STRUCT:
430
        case value_kind_t::VALUE_TEXT:
431
        case value_kind_t::VALUE_QUOTED:
432
        case value_kind_t::VALUE_W3C_QUOTED:
433
        case value_kind_t::VALUE_TIMESTAMP:
434
            require(origin.lr_end != -1);
327,848✔
435
            this->lv_frag = string_fragment::from_byte_range(
327,848✔
436
                sbr.get_data(), origin.lr_start, origin.lr_end);
327,848✔
437
            break;
327,848✔
438

439
        case value_kind_t::VALUE_NULL:
×
440
            break;
×
441

442
        case value_kind_t::VALUE_INTEGER: {
283,642✔
443
            auto scan_res
444
                = scn::scan_value<int64_t>(sbr.to_string_view(origin));
283,642✔
445
            if (scan_res) {
283,642✔
446
                this->lv_value.i = scan_res->value();
283,640✔
447
            } else {
448
                this->lv_value.i = 0;
2✔
449
            }
450
            break;
283,642✔
451
        }
452

453
        case value_kind_t::VALUE_FLOAT: {
30,297✔
454
            auto scan_res = scn::scan_value<double>(sbr.to_string_view(origin));
30,297✔
455
            if (scan_res) {
30,297✔
456
                this->lv_value.d = scan_res->value();
30,297✔
457
            } else {
458
                this->lv_value.d = 0;
×
459
            }
460
            break;
30,297✔
461
        }
462

463
        case value_kind_t::VALUE_BOOLEAN:
×
464
            if (strncmp(
×
465
                    sbr.get_data_at(origin.lr_start), "true", origin.length())
×
466
                    == 0
467
                || strncmp(
×
468
                       sbr.get_data_at(origin.lr_start), "yes", origin.length())
×
469
                    == 0)
470
            {
471
                this->lv_value.i = 1;
×
472
            } else {
473
                this->lv_value.i = 0;
×
474
            }
475
            break;
×
476

477
        case value_kind_t::VALUE_UNKNOWN:
×
478
        case value_kind_t::VALUE__MAX:
479
            ensure(0);
×
480
            break;
481
    }
482
}
641,787✔
483

484
void
485
logline_value::apply_scaling(const scaling_factor* sf)
43,649✔
486
{
487
    if (sf != nullptr) {
43,649✔
488
        switch (this->lv_meta.lvm_kind) {
10✔
489
            case value_kind_t::VALUE_INTEGER:
×
490
                sf->scale(this->lv_value.i);
×
491
                break;
×
492
            case value_kind_t::VALUE_FLOAT:
10✔
493
                sf->scale(this->lv_value.d);
10✔
494
                break;
10✔
495
            default:
×
496
                break;
×
497
        }
498
    }
499
}
43,649✔
500

501
std::string
502
logline_value::to_string() const
9,645✔
503
{
504
    char buffer[128];
505

506
    switch (this->lv_meta.lvm_kind) {
9,645✔
507
        case value_kind_t::VALUE_NULL:
77✔
508
            return "null";
154✔
509

510
        case value_kind_t::VALUE_JSON:
9,077✔
511
        case value_kind_t::VALUE_XML:
512
        case value_kind_t::VALUE_STRUCT:
513
        case value_kind_t::VALUE_TEXT:
514
        case value_kind_t::VALUE_TIMESTAMP:
515
            if (this->lv_str) {
9,077✔
516
                return this->lv_str.value();
1,723✔
517
            }
518
            if (this->lv_frag.empty()) {
7,354✔
519
                return this->lv_intern_string.to_string();
47✔
520
            }
521
            return this->lv_frag.to_string();
7,307✔
522

523
        case value_kind_t::VALUE_QUOTED:
7✔
524
        case value_kind_t::VALUE_W3C_QUOTED:
525
            if (this->lv_frag.empty()) {
7✔
526
                return "";
×
527
            } else {
528
                switch (this->lv_frag.data()[0]) {
7✔
529
                    case '\'':
7✔
530
                    case '"': {
531
                        auto unquote_func = this->lv_meta.lvm_kind
14✔
532
                                == value_kind_t::VALUE_W3C_QUOTED
533
                            ? unquote_w3c
7✔
534
                            : unquote;
535
                        stack_buf allocator;
7✔
536
                        auto* unquoted_str
537
                            = allocator.allocate(this->lv_frag.length());
7✔
538
                        size_t unquoted_len;
539

540
                        unquoted_len = unquote_func(unquoted_str,
7✔
541
                                                    this->lv_frag.data(),
542
                                                    this->lv_frag.length());
7✔
543
                        return {unquoted_str, unquoted_len};
14✔
544
                    }
7✔
545
                    default:
×
546
                        return this->lv_frag.to_string();
×
547
                }
548
            }
549
            break;
550

551
        case value_kind_t::VALUE_INTEGER:
454✔
552
            snprintf(buffer, sizeof(buffer), "%" PRId64, this->lv_value.i);
454✔
553
            break;
454✔
554

555
        case value_kind_t::VALUE_FLOAT:
24✔
556
            snprintf(buffer, sizeof(buffer), "%lf", this->lv_value.d);
24✔
557
            break;
24✔
558

559
        case value_kind_t::VALUE_BOOLEAN:
6✔
560
            if (this->lv_value.i) {
6✔
561
                return "true";
×
562
            } else {
563
                return "false";
12✔
564
            }
565
            break;
566
        case value_kind_t::VALUE_UNKNOWN:
×
567
        case value_kind_t::VALUE__MAX:
568
            ensure(0);
×
569
            break;
570
    }
571

572
    return {buffer};
956✔
573
}
574

575
string_fragment
576
logline_value::to_string_fragment(ArenaAlloc::Alloc<char>& alloc) const
1,099✔
577
{
578
    char buffer[128];
579

580
    switch (this->lv_meta.lvm_kind) {
1,099✔
581
        case value_kind_t::VALUE_NULL:
×
582
            return "null"_frag;
×
583

584
        case value_kind_t::VALUE_JSON:
1,099✔
585
        case value_kind_t::VALUE_XML:
586
        case value_kind_t::VALUE_STRUCT:
587
        case value_kind_t::VALUE_TEXT:
588
        case value_kind_t::VALUE_TIMESTAMP:
589
            if (this->lv_str) {
1,099✔
590
                return string_fragment::from_str(this->lv_str.value())
6✔
591
                    .to_owned(alloc);
6✔
592
            }
593
            if (this->lv_frag.empty()) {
1,093✔
594
                return this->lv_intern_string.to_string_fragment().to_owned(
×
595
                    alloc);
×
596
            }
597
            return this->lv_frag.to_owned(alloc);
1,093✔
598

599
        case value_kind_t::VALUE_QUOTED:
×
600
        case value_kind_t::VALUE_W3C_QUOTED:
601
            if (this->lv_frag.empty()) {
×
602
                return string_fragment{};
×
603
            } else {
604
                switch (this->lv_frag.data()[0]) {
×
605
                    case '\'':
×
606
                    case '"': {
607
                        auto unquote_func = this->lv_meta.lvm_kind
×
608
                                == value_kind_t::VALUE_W3C_QUOTED
609
                            ? unquote_w3c
×
610
                            : unquote;
611
                        stack_buf allocator;
×
612
                        auto* unquoted_str
613
                            = allocator.allocate(this->lv_frag.length());
×
614
                        size_t unquoted_len;
615

616
                        unquoted_len = unquote_func(unquoted_str,
×
617
                                                    this->lv_frag.data(),
618
                                                    this->lv_frag.length());
×
619
                        return string_fragment::from_bytes(unquoted_str,
×
620
                                                           unquoted_len)
621
                            .to_owned(alloc);
×
622
                    }
623
                    default:
×
624
                        return this->lv_frag.to_owned(alloc);
×
625
                }
626
            }
627
            break;
628

629
        case value_kind_t::VALUE_INTEGER:
×
630
            snprintf(buffer, sizeof(buffer), "%" PRId64, this->lv_value.i);
×
631
            break;
×
632

633
        case value_kind_t::VALUE_FLOAT:
×
634
            snprintf(buffer, sizeof(buffer), "%lf", this->lv_value.d);
×
635
            break;
×
636

637
        case value_kind_t::VALUE_BOOLEAN:
×
638
            if (this->lv_value.i) {
×
639
                return "true"_frag;
×
640
            }
641
            return "false"_frag;
×
642
            break;
643
        case value_kind_t::VALUE_UNKNOWN:
×
644
        case value_kind_t::VALUE__MAX:
645
            ensure(0);
×
646
            break;
647
    }
648

649
    return string_fragment::from_c_str(buffer).to_owned(alloc);
×
650
}
651

652
const char*
653
logline_value::text_value() const
68,640✔
654
{
655
    if (this->lv_str) {
68,640✔
656
        return this->lv_str->c_str();
191✔
657
    }
658
    if (this->lv_frag.empty()) {
68,449✔
659
        if (this->lv_intern_string.empty()) {
21✔
660
            return "";
21✔
661
        }
662
        return this->lv_intern_string.get();
×
663
    }
664
    return this->lv_frag.data();
68,428✔
665
}
666

667
size_t
668
logline_value::text_length() const
68,673✔
669
{
670
    if (this->lv_str) {
68,673✔
671
        return this->lv_str->size();
191✔
672
    }
673
    if (this->lv_frag.empty()) {
68,482✔
674
        return this->lv_intern_string.size();
21✔
675
    }
676
    return this->lv_frag.length();
68,461✔
677
}
678

679
string_fragment
680
logline_value::text_value_fragment() const
×
681
{
682
    return string_fragment::from_bytes(this->text_value(), this->text_length());
×
683
}
684

685
void
686
logline_value_vector::clear()
42,322✔
687
{
688
    this->lvv_values.clear();
42,322✔
689
    this->lvv_sbr.disown();
42,322✔
690
    this->lvv_opid_value = std::nullopt;
42,322✔
691
    this->lvv_opid_provenance = opid_provenance::none;
42,322✔
692
    this->lvv_thread_id_value = std::nullopt;
42,322✔
693
}
42,322✔
694

695
logline_value_vector::logline_value_vector(const logline_value_vector& other)
895✔
696
    : lvv_sbr(other.lvv_sbr.clone()), lvv_values(other.lvv_values),
895✔
697
      lvv_opid_value(other.lvv_opid_value),
895✔
698
      lvv_opid_provenance(other.lvv_opid_provenance),
895✔
699
      lvv_thread_id_value(other.lvv_thread_id_value)
895✔
700
{
701
}
895✔
702

703
logline_value_vector&
704
logline_value_vector::operator=(const logline_value_vector& other)
425✔
705
{
706
    this->lvv_sbr = other.lvv_sbr.clone();
425✔
707
    this->lvv_values = other.lvv_values;
425✔
708
    this->lvv_opid_value = other.lvv_opid_value;
425✔
709
    this->lvv_opid_provenance = other.lvv_opid_provenance;
425✔
710
    this->lvv_thread_id_value = other.lvv_thread_id_value;
425✔
711

712
    return *this;
425✔
713
}
714

715
std::vector<std::shared_ptr<log_format>> log_format::lf_root_formats;
716

717
date_time_scanner
718
log_format::build_time_scanner() const
241✔
719
{
720
    date_time_scanner retval;
241✔
721

722
    retval.set_base_time(this->lf_date_time.dts_base_time,
241✔
723
                         this->lf_date_time.dts_base_tm.et_tm);
241✔
724
    if (this->lf_date_time.dts_default_zone != nullptr) {
241✔
725
        retval.dts_default_zone = this->lf_date_time.dts_default_zone;
×
726
    }
727
    retval.dts_zoned_to_local = this->lf_date_time.dts_zoned_to_local;
241✔
728

729
    return retval;
241✔
730
}
731

732
std::vector<std::shared_ptr<log_format>>&
733
log_format::get_root_formats()
17,784✔
734
{
735
    return lf_root_formats;
17,784✔
736
}
737

738
void
739
external_log_format::update_op_description(
5,031✔
740
    const std::vector<opid_descriptors*>& desc_defs_vec,
741
    log_op_description& lod,
742
    const pattern* fpat,
743
    const lnav::pcre2pp::match_data& md)
744
{
745
    std::optional<std::string> desc_elem_str;
5,031✔
746
    if (!lod.lod_index) {
5,031✔
747
        for (const auto& desc_defs : desc_defs_vec) {
3,072✔
748
            if (lod.lod_index) {
1,265✔
749
                break;
26✔
750
            }
751
            for (const auto& desc_def : *desc_defs->od_descriptors) {
1,547✔
752
                auto desc_field_index_iter = fpat->p_value_name_to_index.find(
1,337✔
753
                    desc_def.od_field.pp_value);
1,337✔
754

755
                if (desc_field_index_iter == fpat->p_value_name_to_index.end())
1,337✔
756
                {
757
                    continue;
43✔
758
                }
759

760
                auto desc_cap_opt = md[desc_field_index_iter->second];
1,333✔
761
                if (!desc_cap_opt) {
1,333✔
762
                    continue;
39✔
763
                }
764

765
                desc_elem_str = desc_def.matches(desc_cap_opt.value());
1,294✔
766
                if (desc_elem_str) {
1,294✔
767
                    lod.lod_index = desc_defs->od_index;
1,029✔
768
                    break;
1,029✔
769
                }
770
            }
771
        }
772
    }
773
    if (lod.lod_index) {
5,031✔
774
        const auto& desc_def_v
775
            = *desc_defs_vec[lod.lod_index.value()]->od_descriptors;
4,227✔
776
        auto& desc_v = lod.lod_elements;
4,227✔
777

778
        if (desc_def_v.size() == desc_v.size()
4,227✔
779
            || (this->elf_opid_field.empty() && !desc_v.empty()))
4,227✔
780
        {
781
            return;
3,198✔
782
        }
783
        for (size_t desc_def_index = 0; desc_def_index < desc_def_v.size();
2,938✔
784
             desc_def_index++)
785
        {
786
            const auto& desc_def = desc_def_v[desc_def_index];
1,909✔
787
            auto found_desc = desc_v.value_for(desc_def_index);
1,909✔
788
            auto desc_field_index_iter
789
                = fpat->p_value_name_to_index.find(desc_def.od_field.pp_value);
1,909✔
790

791
            if (desc_field_index_iter == fpat->p_value_name_to_index.end()) {
1,909✔
792
                continue;
36✔
793
            }
794
            auto desc_cap_opt = md[desc_field_index_iter->second];
1,909✔
795
            if (!desc_cap_opt) {
1,909✔
796
                continue;
36✔
797
            }
798

799
            if (!desc_elem_str) {
1,873✔
800
                desc_elem_str = desc_def.matches(desc_cap_opt.value());
844✔
801
            }
802
            if (desc_elem_str) {
1,873✔
803
                if (!found_desc) {
1,870✔
804
                    desc_v.insert(desc_def_index, desc_elem_str.value());
1,870✔
805
                } else if (!desc_elem_str->empty()) {
×
806
                    found_desc.value()->append(desc_def.od_joiner);
×
807
                    found_desc.value()->append(desc_elem_str.value());
×
808
                }
809
            }
810
            desc_elem_str = std::nullopt;
1,873✔
811
        }
812
    }
813
}
5,031✔
814

815
void
816
external_log_format::update_op_description(
3,392✔
817
    const std::vector<opid_descriptors*>& desc_defs_vec,
818
    log_op_description& lod)
819
{
820
    std::optional<std::string> desc_elem_str;
3,392✔
821
    if (!lod.lod_index) {
3,392✔
822
        for (const auto& desc_defs : desc_defs_vec) {
3,401✔
823
            if (lod.lod_index) {
15✔
824
                break;
×
825
            }
826
            for (const auto& desc_def : *desc_defs->od_descriptors) {
15✔
827
                auto desc_cap_iter
828
                    = this->lf_desc_captures.find(desc_def.od_field.pp_value);
15✔
829

830
                if (desc_cap_iter == this->lf_desc_captures.end()) {
15✔
831
                    continue;
×
832
                }
833
                desc_elem_str = desc_def.matches(desc_cap_iter->second);
15✔
834
                if (desc_elem_str) {
15✔
835
                    lod.lod_index = desc_defs->od_index;
15✔
836
                    break;
15✔
837
                }
838
            }
839
        }
840
    }
841
    if (lod.lod_index) {
3,392✔
842
        const auto& desc_def_v
843
            = *desc_defs_vec[lod.lod_index.value()]->od_descriptors;
21✔
844
        auto& desc_v = lod.lod_elements;
21✔
845

846
        if (desc_def_v.size() == desc_v.size()
21✔
847
            || (this->elf_opid_field.empty() && !desc_v.empty()))
21✔
848
        {
849
            return;
6✔
850
        }
851
        for (size_t desc_def_index = 0; desc_def_index < desc_def_v.size();
45✔
852
             desc_def_index++)
853
        {
854
            const auto& desc_def = desc_def_v[desc_def_index];
30✔
855
            auto found_desc = desc_v.value_for(desc_def_index);
30✔
856
            auto desc_cap_iter
857
                = this->lf_desc_captures.find(desc_def.od_field.pp_value);
30✔
858
            if (desc_cap_iter == this->lf_desc_captures.end()) {
30✔
859
                continue;
×
860
            }
861

862
            if (!desc_elem_str) {
30✔
863
                desc_elem_str = desc_def.matches(desc_cap_iter->second);
15✔
864
            }
865
            if (desc_elem_str) {
30✔
866
                if (!found_desc) {
30✔
867
                    desc_v.insert(desc_def_index, desc_elem_str.value());
30✔
868
                } else if (!desc_elem_str->empty()) {
×
869
                    found_desc.value()->append(desc_def.od_joiner);
×
870
                    found_desc.value()->append(desc_elem_str.value());
×
871
                }
872
            }
873
            desc_elem_str = std::nullopt;
30✔
874
        }
875
    }
876
}
3,392✔
877

878
static bool
879
next_format(
2,357,263✔
880
    const std::vector<std::shared_ptr<external_log_format::pattern>>& patterns,
881
    int& index,
882
    int& locked_index)
883
{
884
    bool retval = true;
2,357,263✔
885

886
    if (locked_index == -1) {
2,357,263✔
887
        index += 1;
2,349,866✔
888
        if (index >= (int) patterns.size()) {
2,349,866✔
889
            retval = false;
713,485✔
890
        }
891
    } else if (index == locked_index) {
7,397✔
892
        retval = false;
1✔
893
    } else {
894
        index = locked_index;
7,396✔
895
    }
896

897
    return retval;
2,357,263✔
898
}
899

900
bool
901
log_format::next_format(const pcre_format* fmt, int& index, int& locked_index)
180,571✔
902
{
903
    bool retval = true;
180,571✔
904

905
    if (locked_index == -1) {
180,571✔
906
        index += 1;
180,387✔
907
        if (fmt[index].name == nullptr) {
180,387✔
908
            retval = false;
10,135✔
909
        }
910
    } else if (index == locked_index) {
184✔
911
        retval = false;
36✔
912
    } else {
913
        index = locked_index;
148✔
914
    }
915

916
    return retval;
180,571✔
917
}
918

919
const char*
920
log_format::log_scanf(scan_batch_context& sbc,
12,616✔
921
                      uint32_t line_number,
922
                      string_fragment line,
923
                      const pcre_format* fmt,
924
                      const char* time_fmt[],
925
                      exttm* tm_out,
926
                      timeval* tv_out,
927

928
                      string_fragment* ts_out,
929
                      std::optional<string_fragment>* level_out)
930
{
931
    int curr_fmt = -1;
12,616✔
932
    const char* retval = nullptr;
12,616✔
933
    bool done = false;
12,616✔
934
    int pat_index = sbc.sbc_pattern_locks.last_pattern_index();
12,616✔
935

936
    while (!done && next_format(fmt, curr_fmt, pat_index)) {
183,016✔
937
        thread_local auto md = lnav::pcre2pp::match_data::unitialized();
170,400✔
938

939
        auto match_res = fmt[curr_fmt]
170,400✔
940
                             .pcre->capture_from(line)
170,400✔
941
                             .into(md)
170,400✔
942
                             .matches(PCRE2_NO_UTF_CHECK)
340,800✔
943
                             .ignore_error();
170,400✔
944
        if (!match_res) {
170,400✔
945
            retval = nullptr;
146,481✔
946
        } else {
947
            auto ts = md[fmt[curr_fmt].pf_timestamp_index];
23,919✔
948

949
            retval = this->lf_date_time.scan(
23,919✔
950
                ts->data(), ts->length(), nullptr, tm_out, *tv_out);
23,919✔
951

952
            if (retval == nullptr) {
23,919✔
953
                auto ls = this->lf_date_time.unlock();
21,474✔
954
                retval = this->lf_date_time.scan(
21,474✔
955
                    ts->data(), ts->length(), nullptr, tm_out, *tv_out);
21,474✔
956
                if (retval != nullptr) {
21,474✔
957
                    auto old_flags
×
958
                        = this->lf_timestamp_flags & DATE_TIME_SET_FLAGS;
×
959
                    auto new_flags = tm_out->et_flags & DATE_TIME_SET_FLAGS;
×
960

961
                    // It is unlikely a valid timestamp would lose much
962
                    // precision.
963
                    if (new_flags != old_flags) {
×
964
                        retval = nullptr;
×
965
                    }
966
                }
967
                if (retval == nullptr) {
21,474✔
968
                    this->lf_date_time.relock(ls);
21,474✔
969
                } else {
970
                    log_debug(
×
971
                        "%d: changed time format to '%s' due to %.*s",
972
                        line_number,
973
                        PTIMEC_FORMAT_STR[this->lf_date_time.dts_fmt_lock],
974
                        ts->length(),
975
                        ts->data());
976
                }
977
            }
978

979
            if (retval) {
23,919✔
980
                *ts_out = ts.value();
2,445✔
981
                if (md[2]) {
2,445✔
982
                    *level_out = md[2];
260✔
983
                } else {
984
                    *level_out = line.substr(md[0]->sf_end);
2,185✔
985
                }
986
                if (curr_fmt != pat_index) {
2,445✔
987
                    uint32_t lock_line;
988

989
                    if (sbc.sbc_pattern_locks.empty()) {
2,333✔
990
                        lock_line = 0;
2,333✔
991
                    } else {
992
                        lock_line = line_number;
×
993
                    }
994

995
                    sbc.sbc_pattern_locks.pl_lines.emplace_back(lock_line,
2,333✔
996
                                                                curr_fmt);
997
                }
998
                this->lf_timestamp_flags = tm_out->et_flags;
2,445✔
999
                done = true;
2,445✔
1000
            }
1001
        }
1002
    }
1003

1004
    return retval;
12,616✔
1005
}
1006

1007
void
1008
log_format::annotate(logfile* lf,
37,690✔
1009
                     uint64_t line_number,
1010
                     string_attrs_t& sa,
1011
                     logline_value_vector& values) const
1012
{
1013
    if (lf != nullptr && !values.lvv_opid_value) {
37,690✔
1014
        const auto& bm = lf->get_bookmark_metadata();
2,981✔
1015
        auto bm_iter = bm.find(line_number);
2,981✔
1016
        if (bm_iter != bm.end() && !bm_iter->second.bm_opid.empty()) {
2,981✔
1017
            values.lvv_opid_value = bm_iter->second.bm_opid;
6✔
1018
            values.lvv_opid_provenance
1019
                = logline_value_vector::opid_provenance::user;
6✔
1020
        }
1021
    }
1022
}
37,690✔
1023

1024
void
1025
log_format::check_for_new_year(std::vector<logline>& dst,
1,614✔
1026
                               exttm etm,
1027
                               timeval log_tv) const
1028
{
1029
    if (dst.empty()) {
1,614✔
1030
        return;
233✔
1031
    }
1032

1033
    time_t diff
1034
        = dst.back().get_time<std::chrono::seconds>().count() - log_tv.tv_sec;
1,381✔
1035
    int off_year = 0, off_month = 0, off_day = 0, off_hour = 0;
1,381✔
1036
    bool do_change = true;
1,381✔
1037

1038
    if (diff <= 0) {
1,381✔
1039
        return;
1,321✔
1040
    }
1041
    if ((etm.et_flags & ETF_MONTH_SET) && diff >= (24 * 60 * 60)) {
60✔
1042
        off_year = 1;
11✔
1043
    } else if (diff >= (24 * 60 * 60)) {
49✔
1044
        off_month = 1;
2✔
1045
    } else if (!(etm.et_flags & ETF_DAY_SET) && (diff >= (60 * 60))) {
47✔
1046
        off_day = 1;
1✔
1047
    } else if (!(etm.et_flags & ETF_HOUR_SET) && (diff >= 60)) {
46✔
1048
        off_hour = 1;
4✔
1049
    } else {
1050
        do_change = false;
42✔
1051
    }
1052

1053
    if (!do_change) {
60✔
1054
        return;
42✔
1055
    }
1056
    log_debug("%zu:detected time rollover; offsets=%d %d %d %d",
18✔
1057
              dst.size(),
1058
              off_year,
1059
              off_month,
1060
              off_day,
1061
              off_hour);
1062
    for (auto& ll : dst) {
68✔
1063
        time_t ot = ll.get_time<std::chrono::seconds>().count();
50✔
1064
        struct tm otm;
1065

1066
        gmtime_r(&ot, &otm);
50✔
1067
        otm.tm_yday = -1;
50✔
1068
        if (otm.tm_year < off_year) {
50✔
1069
            otm.tm_year = 0;
×
1070
        } else {
1071
            otm.tm_year -= off_year;
50✔
1072
        }
1073
        otm.tm_mon -= off_month;
50✔
1074
        if (otm.tm_mon < 0) {
50✔
1075
            otm.tm_mon += 12;
2✔
1076
        }
1077
        auto new_time = tm2sec(&otm);
50✔
1078
        if (new_time == -1) {
50✔
1079
            continue;
×
1080
        }
1081
        new_time -= (off_day * 24 * 60 * 60) + (off_hour * 60 * 60);
50✔
1082
        auto old_sub = ll.get_subsecond_time<std::chrono::microseconds>();
50✔
1083
        ll.set_time(std::chrono::seconds{new_time});
50✔
1084
        ll.set_subsecond_time(old_sub);
50✔
1085
    }
1086
}
1087

1088
/*
1089
 * XXX This needs some cleanup.
1090
 */
1091
struct json_log_userdata {
1092
    json_log_userdata(shared_buffer_ref& sbr, scan_batch_context* sbc)
15,204✔
1093
        : jlu_shared_buffer(sbr), jlu_batch_context(sbc)
30,408✔
1094
    {
1095
    }
15,204✔
1096

1097
    const external_log_format::value_def* get_field_def(
463,159✔
1098
        yajlpp_parse_context* ypc)
1099
    {
1100
        const auto field_frag = ypc->get_path_as_string_fragment();
463,159✔
1101
        auto* format = this->jlu_format;
463,159✔
1102

1103
        if (this->jlu_read_order_index < format->elf_value_def_read_order.size()
463,159✔
1104
            && format->elf_value_def_read_order[this->jlu_read_order_index]
629,337✔
1105
                    .first
1106
                == field_frag)
166,178✔
1107
        {
1108
            auto retval
1109
                = format->elf_value_def_read_order[this->jlu_read_order_index++]
159,373✔
1110
                      .second;
159,373✔
1111
            if (retval != nullptr) {
159,373✔
1112
                this->jlu_precision += 1;
21,387✔
1113
            }
1114
            return retval;
159,373✔
1115
        }
1116

1117
        format->elf_value_def_read_order.resize(this->jlu_read_order_index);
303,786✔
1118
        auto vd_iter = format->elf_value_def_frag_map.find(field_frag);
303,786✔
1119
        if (vd_iter != format->elf_value_def_frag_map.end()) {
303,786✔
1120
            format->elf_value_def_read_order.emplace_back(vd_iter->first,
255,972✔
1121
                                                          vd_iter->second);
255,972✔
1122
            this->jlu_read_order_index += 1;
255,972✔
1123
            if (vd_iter->second != nullptr) {
255,972✔
1124
                this->jlu_precision += 1;
16,963✔
1125
            }
1126
            return vd_iter->second;
255,972✔
1127
        }
1128

1129
        auto owned_frag = field_frag.to_owned(format->elf_allocator);
47,814✔
1130
        format->elf_value_def_frag_map[owned_frag] = nullptr;
47,814✔
1131
        format->elf_value_def_read_order.emplace_back(owned_frag, nullptr);
47,814✔
1132
        this->jlu_read_order_index += 1;
47,814✔
1133
        return nullptr;
47,814✔
1134
    }
1135

1136
    void add_sub_lines_for(const external_log_format::value_def* vd,
326,145✔
1137
                           bool top_level,
1138
                           std::optional<double> val,
1139
                           const unsigned char* str,
1140
                           ssize_t len,
1141
                           yajl_string_props_t* props)
1142
    {
1143
        auto res = this->jlu_format->value_line_count(
326,145✔
1144
            *this->jlu_batch_context, vd, top_level, val, str, len, props);
326,145✔
1145
        this->jlu_has_ansi |= res.vlcr_has_ansi;
326,145✔
1146
        if (!res.vlcr_valid_utf) {
326,145✔
1147
            this->jlu_valid_utf = false;
×
1148
        }
1149
        this->jlu_sub_line_count += res.vlcr_count;
326,145✔
1150
        this->jlu_quality += res.vlcr_line_format_count;
326,145✔
1151
        if (res.vlcr_line_format_index) {
326,145✔
1152
            this->jlu_format_hits[res.vlcr_line_format_index.value()] = true;
3,989✔
1153
        }
1154
    }
326,145✔
1155

1156
    external_log_format* jlu_format{nullptr};
1157
    const logline* jlu_line{nullptr};
1158
    logline* jlu_base_line{nullptr};
1159
    int jlu_sub_line_count{1};
1160
    bool jlu_has_ansi{false};
1161
    bool jlu_valid_utf{true};
1162
    yajl_handle jlu_handle{nullptr};
1163
    const char* jlu_line_value{nullptr};
1164
    size_t jlu_line_size{0};
1165
    std::stack<size_t> jlu_sub_start;
1166
    uint32_t jlu_quality{0};
1167
    uint32_t jlu_strikes{0};
1168
    uint32_t jlu_precision{0};
1169
    std::vector<bool> jlu_format_hits;
1170
    shared_buffer_ref& jlu_shared_buffer;
1171
    scan_batch_context* jlu_batch_context;
1172
    std::optional<string_fragment> jlu_opid_frag;
1173
    std::optional<string_fragment> jlu_opid_desc_frag;
1174
    std::optional<string_fragment> jlu_tid_frag;
1175
    std::optional<int64_t> jlu_tid_number;
1176
    std::optional<std::string> jlu_subid;
1177
    std::optional<log_format::scan_error> jlu_scan_error;
1178
    hasher jlu_opid_hasher;
1179
    std::chrono::microseconds jlu_duration{0};
15,204✔
1180
    exttm jlu_exttm;
1181
    size_t jlu_read_order_index{0};
1182
    subline_options jlu_subline_opts;
1183
};
1184

1185
static int read_json_field(yajlpp_parse_context* ypc,
1186
                           const unsigned char* str,
1187
                           size_t len,
1188
                           yajl_string_props_t*);
1189

1190
static int
1191
read_json_null(yajlpp_parse_context* ypc)
5,054✔
1192
{
1193
    json_log_userdata* jlu = (json_log_userdata*) ypc->ypc_userdata;
5,054✔
1194
    const auto* vd = jlu->get_field_def(ypc);
5,054✔
1195

1196
    jlu->add_sub_lines_for(
10,108✔
1197
        vd, ypc->is_level(1), std::nullopt, nullptr, -1, nullptr);
5,054✔
1198

1199
    return 1;
5,054✔
1200
}
1201

1202
static int
1203
read_json_bool(yajlpp_parse_context* ypc, int val)
24,006✔
1204
{
1205
    json_log_userdata* jlu = (json_log_userdata*) ypc->ypc_userdata;
24,006✔
1206
    const auto* vd = jlu->get_field_def(ypc);
24,006✔
1207

1208
    jlu->add_sub_lines_for(
48,012✔
1209
        vd, ypc->is_level(1), std::nullopt, nullptr, -1, nullptr);
24,006✔
1210

1211
    return 1;
24,006✔
1212
}
1213

1214
static int
1215
read_json_number(yajlpp_parse_context* ypc,
37,792✔
1216
                 const char* numberVal,
1217
                 size_t numberLen)
1218
{
1219
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
37,792✔
1220
    auto number_frag = string_fragment::from_bytes(numberVal, numberLen);
37,792✔
1221
    std::optional<double> val;
37,792✔
1222

1223
    intern_string_t field_name;
37,792✔
1224
    const auto* vd = jlu->get_field_def(ypc);
37,792✔
1225
    if (vd != nullptr) {
37,792✔
1226
        field_name = vd->vd_meta.lvm_name;
1,800✔
1227
    }
1228

1229
    if (field_name.empty()) {
37,792✔
1230
    } else if (jlu->jlu_format->lf_timestamp_field == field_name) {
1,800✔
1231
        long long divisor = jlu->jlu_format->elf_timestamp_divisor;
113✔
1232
        auto scan_res = scn::scan_value<double>(number_frag.to_string_view());
113✔
1233
        if (!scan_res) {
113✔
1234
            log_error("invalid number %.*s", (int) numberLen, numberVal);
×
1235
            return 0;
×
1236
        }
1237
        auto ts_val = scan_res.value().value();
113✔
1238
        timeval tv;
1239
        tv.tv_sec = ts_val / divisor;
113✔
1240
        tv.tv_usec = fmod(ts_val, divisor) * (1000000.0 / divisor);
113✔
1241
        jlu->jlu_format->lf_date_time.to_localtime(tv.tv_sec, jlu->jlu_exttm);
113✔
1242
        tv.tv_sec = tm2sec(&jlu->jlu_exttm.et_tm);
113✔
1243
        jlu->jlu_exttm.et_gmtoff
1244
            = jlu->jlu_format->lf_date_time.dts_local_offset_cache;
113✔
1245
        jlu->jlu_exttm.et_flags
113✔
1246
            |= ETF_MACHINE_ORIENTED | ETF_SUB_NOT_IN_FORMAT | ETF_ZONE_SET;
113✔
1247
        if (divisor == 1000) {
113✔
1248
            jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
17✔
1249
        } else {
1250
            jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
96✔
1251
        }
1252
        jlu->jlu_exttm.et_nsec = tv.tv_usec * 1000;
113✔
1253
        jlu->jlu_base_line->set_time(tv);
113✔
1254
    } else if (jlu->jlu_format->lf_subsecond_field == field_name) {
1,687✔
1255
        auto scan_res = scn::scan_value<double>(number_frag.to_string_view());
3✔
1256
        if (!scan_res) {
3✔
1257
            log_error("invalid number %.*s", (int) numberLen, numberVal);
×
1258
            return 0;
×
1259
        }
1260
        auto ts_val = scan_res.value().value();
3✔
1261

1262
        uint64_t millis = 0;
3✔
1263
        jlu->jlu_exttm.et_flags &= ~(ETF_MICROS_SET | ETF_MILLIS_SET);
3✔
1264
        switch (jlu->jlu_format->lf_subsecond_unit.value()) {
3✔
1265
            case log_format::subsecond_unit::milli:
×
1266
                millis = ts_val;
×
1267
                jlu->jlu_exttm.et_nsec = ts_val * 1000000;
×
1268
                jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
×
1269
                break;
×
1270
            case log_format::subsecond_unit::micro:
×
1271
                millis = std::chrono::duration_cast<std::chrono::milliseconds>(
×
1272
                             std::chrono::microseconds((int64_t) ts_val))
×
1273
                             .count();
×
1274
                jlu->jlu_exttm.et_nsec = ts_val * 1000;
×
1275
                jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
×
1276
                break;
×
1277
            case log_format::subsecond_unit::nano:
3✔
1278
                millis = std::chrono::duration_cast<std::chrono::milliseconds>(
3✔
1279
                             std::chrono::nanoseconds((int64_t) ts_val))
3✔
1280
                             .count();
3✔
1281
                jlu->jlu_exttm.et_nsec = ts_val;
3✔
1282
                jlu->jlu_exttm.et_flags |= ETF_NANOS_SET;
3✔
1283
                break;
3✔
1284
        }
1285
        jlu->jlu_exttm.et_flags |= ETF_SUB_NOT_IN_FORMAT;
3✔
1286
        jlu->jlu_base_line->set_subsecond_time(
3✔
1287
            std::chrono::milliseconds(millis));
1288
    } else if (jlu->jlu_format->elf_level_field == field_name) {
1,684✔
1289
        if (jlu->jlu_format->elf_level_pairs.empty()) {
516✔
1290
            jlu->jlu_base_line->set_level(jlu->jlu_format->convert_level(
321✔
1291
                number_frag, jlu->jlu_batch_context));
1292
        } else {
1293
            auto scan_res
1294
                = scn::scan_int<int64_t>(number_frag.to_string_view());
195✔
1295
            if (!scan_res) {
195✔
1296
                log_error("invalid number %.*s", (int) numberLen, numberVal);
×
1297
                return 0;
×
1298
            }
1299
            auto level_int = scan_res.value().value();
195✔
1300

1301
            for (const auto& pair : jlu->jlu_format->elf_level_pairs) {
705✔
1302
                if (pair.first == level_int) {
632✔
1303
                    jlu->jlu_base_line->set_level(pair.second);
122✔
1304
                    break;
122✔
1305
                }
1306
            }
1307
        }
1308
    } else if (vd != nullptr) {
1,168✔
1309
        if (jlu->jlu_format->elf_thread_id_field == field_name) {
1,168✔
1310
            auto& sbc = *jlu->jlu_batch_context;
124✔
1311
            auto tid_iter = sbc.sbc_tids.ltis_tid_ranges.find(number_frag);
124✔
1312
            if (tid_iter == sbc.sbc_tids.ltis_tid_ranges.end()) {
124✔
1313
                jlu->jlu_tid_frag = number_frag.to_owned(sbc.sbc_allocator);
71✔
1314
            } else {
1315
                jlu->jlu_tid_frag = tid_iter->first;
53✔
1316
            }
1317
        }
1318
        if ((vd->vd_meta.lvm_kind == value_kind_t::VALUE_INTEGER
1,168✔
1319
             || vd->vd_meta.lvm_kind == value_kind_t::VALUE_FLOAT)
154✔
1320
            && !vd->vd_meta.lvm_foreign_key && !vd->vd_meta.lvm_identifier)
1,032✔
1321
        {
1322
            auto scan_res
1323
                = scn::scan_value<double>(number_frag.to_string_view());
182✔
1324
            if (!scan_res) {
182✔
1325
                log_error("invalid number %.*s", (int) numberLen, numberVal);
×
1326
                return 0;
×
1327
            }
1328
            val = scan_res.value().value();
182✔
1329
            if (jlu->jlu_format->elf_duration_field == field_name) {
182✔
1330
                jlu->jlu_duration = std::chrono::microseconds(
×
1331
                    static_cast<int64_t>(val.value() * 1000000));
18✔
1332
            }
1333
        }
1334
    }
1335

1336
    jlu->add_sub_lines_for(vd,
37,792✔
1337
                           ypc->is_level(1),
37,792✔
1338
                           val,
1339
                           (const unsigned char*) numberVal,
1340
                           numberLen,
1341
                           nullptr);
1342

1343
    return 1;
37,792✔
1344
}
1345

1346
static int
1347
json_array_start(void* ctx)
65,275✔
1348
{
1349
    auto* ypc = (yajlpp_parse_context*) ctx;
65,275✔
1350
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
65,275✔
1351

1352
    jlu->jlu_sub_start.push(yajl_get_bytes_consumed(jlu->jlu_handle) - 1);
65,275✔
1353
    if (ypc->ypc_path_index_stack.size() == 2) {
65,275✔
1354
        const auto* vd = jlu->get_field_def(ypc);
20,063✔
1355

1356
        jlu->add_sub_lines_for(vd, true, std::nullopt, nullptr, -1, nullptr);
20,063✔
1357
    }
1358

1359
    return 1;
65,275✔
1360
}
1361

1362
static int
1363
json_array_start_const(void* ctx)
9,699✔
1364
{
1365
    auto* ypc = (yajlpp_parse_context*) ctx;
9,699✔
1366
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
9,699✔
1367

1368
    jlu->jlu_sub_start.push(yajl_get_bytes_consumed(jlu->jlu_handle) - 1);
9,699✔
1369

1370
    return 1;
9,699✔
1371
}
1372

1373
static int
1374
json_array_end(void* ctx)
9,679✔
1375
{
1376
    auto* ypc = (yajlpp_parse_context*) ctx;
9,679✔
1377
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
9,679✔
1378
    const auto* vd = jlu->get_field_def(ypc);
9,679✔
1379

1380
    if (ypc->ypc_path_index_stack.size() == 1 || vd != nullptr) {
9,679✔
1381
        intern_string_t field_name;
2,594✔
1382
        if (vd != nullptr) {
2,594✔
1383
            field_name = vd->vd_meta.lvm_name;
2,204✔
1384
        } else {
1385
            field_name = ypc->get_path();
390✔
1386
        }
1387
        auto sub_start = jlu->jlu_sub_start.top();
2,594✔
1388
        size_t sub_end = yajl_get_bytes_consumed(jlu->jlu_handle);
2,594✔
1389
        auto json_frag = string_fragment::from_byte_range(
2,594✔
1390
            jlu->jlu_shared_buffer.get_data(), sub_start, sub_end);
2,594✔
1391
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
2,594✔
1392
            jlu->jlu_format->get_value_meta(field_name,
5,188✔
1393
                                            value_kind_t::VALUE_JSON),
1394
            json_frag);
1395
        if (field_name == jlu->jlu_format->elf_opid_field) {
2,594✔
1396
            jlu->jlu_opid_desc_frag = json_frag;
29✔
1397
        }
1398
    }
1399
    jlu->jlu_sub_start.pop();
9,679✔
1400

1401
    return 1;
9,679✔
1402
}
1403

1404
static int
1405
read_array_end(void* ctx)
65,031✔
1406
{
1407
    auto* ypc = (yajlpp_parse_context*) ctx;
65,031✔
1408
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
65,031✔
1409
    const auto* vd = jlu->get_field_def(ypc);
65,031✔
1410

1411
    if (ypc->ypc_path_index_stack.size() == 1 || vd != nullptr) {
65,031✔
1412
        const intern_string_t field_name = ypc->get_path_fragment_i(0);
20,032✔
1413
        auto sub_start = jlu->jlu_sub_start.top();
20,032✔
1414
        jlu->jlu_sub_start.pop();
20,032✔
1415
        size_t sub_end = yajl_get_bytes_consumed(jlu->jlu_handle);
20,032✔
1416
        auto json_frag = string_fragment::from_byte_range(
20,032✔
1417
            jlu->jlu_shared_buffer.get_data(), sub_start, sub_end);
20,032✔
1418
        if (field_name == jlu->jlu_format->elf_opid_field) {
20,032✔
1419
            jlu->jlu_opid_desc_frag = json_frag;
2,370✔
1420
        }
1421
    }
1422

1423
    return 1;
65,031✔
1424
}
1425

1426
static const json_path_container json_log_handlers = {
1427
    yajlpp::pattern_property_handler("\\w+")
1428
        .add_cb(read_json_null)
1429
        .add_cb(read_json_bool)
1430
        .add_cb(read_json_number)
1431
        .add_cb(read_json_field),
1432
};
1433

1434
static int rewrite_json_field(yajlpp_parse_context* ypc,
1435
                              const unsigned char* str,
1436
                              size_t len,
1437
                              yajl_string_props_t*);
1438

1439
static int
1440
rewrite_json_null(yajlpp_parse_context* ypc)
1,290✔
1441
{
1442
    auto jlu = (json_log_userdata*) ypc->ypc_userdata;
1,290✔
1443
    const auto* vd = jlu->get_field_def(ypc);
1,290✔
1444

1445
    if (!ypc->is_level(1) && vd == nullptr) {
1,290✔
1446
        return 1;
1,228✔
1447
    }
1448
    jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
62✔
1449
        jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_NULL));
124✔
1450

1451
    return 1;
62✔
1452
}
1453

1454
static int
1455
rewrite_json_bool(yajlpp_parse_context* ypc, int val)
5,639✔
1456
{
1457
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
5,639✔
1458
    const auto* vd = jlu->get_field_def(ypc);
5,639✔
1459

1460
    if (!ypc->is_level(1) && vd == nullptr) {
5,639✔
1461
        return 1;
5,007✔
1462
    }
1463
    jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
632✔
1464
        jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_BOOLEAN),
632✔
1465
        (bool) val);
632✔
1466
    return 1;
632✔
1467
}
1468

1469
static int
1470
rewrite_json_int(yajlpp_parse_context* ypc, long long val)
7,462✔
1471
{
1472
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
7,462✔
1473
    const auto* vd = jlu->get_field_def(ypc);
7,462✔
1474

1475
    if (vd != nullptr) {
7,462✔
1476
        const intern_string_t field_name = vd->vd_meta.lvm_name;
790✔
1477
        if (jlu->jlu_format->lf_timestamp_field == field_name) {
790✔
1478
            long long divisor = jlu->jlu_format->elf_timestamp_divisor;
22✔
1479
            timeval tv;
1480

1481
            tv.tv_sec = val / divisor;
22✔
1482
            tv.tv_usec = fmod(val, divisor) * (1000000.0 / divisor);
22✔
1483
            jlu->jlu_format->lf_date_time.to_localtime(tv.tv_sec,
22✔
1484
                                                       jlu->jlu_exttm);
22✔
1485
            jlu->jlu_exttm.et_gmtoff
1486
                = jlu->jlu_format->lf_date_time.dts_local_offset_cache;
22✔
1487
            jlu->jlu_exttm.et_flags |= ETF_MACHINE_ORIENTED
22✔
1488
                | ETF_SUB_NOT_IN_FORMAT | ETF_ZONE_SET | ETF_Z_FOR_UTC;
1489
            if (divisor == 1) {
22✔
1490
                jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
4✔
1491
            } else {
1492
                jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
18✔
1493
            }
1494
            jlu->jlu_exttm.et_nsec = tv.tv_usec * 1000;
22✔
1495
        } else if (jlu->jlu_format->lf_subsecond_field == field_name) {
768✔
1496
            jlu->jlu_exttm.et_flags &= ~(ETF_MICROS_SET | ETF_MILLIS_SET);
4✔
1497
            switch (jlu->jlu_format->lf_subsecond_unit.value()) {
4✔
1498
                case log_format::subsecond_unit::milli:
×
1499
                    jlu->jlu_exttm.et_nsec = val * 1000000;
×
1500
                    jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
×
1501
                    break;
×
1502
                case log_format::subsecond_unit::micro:
×
1503
                    jlu->jlu_exttm.et_nsec = val * 1000;
×
1504
                    jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
×
1505
                    break;
×
1506
                case log_format::subsecond_unit::nano:
4✔
1507
                    jlu->jlu_exttm.et_nsec = val;
4✔
1508
                    jlu->jlu_exttm.et_flags |= ETF_NANOS_SET;
4✔
1509
                    break;
4✔
1510
            }
1511
            jlu->jlu_exttm.et_flags |= ETF_SUB_NOT_IN_FORMAT;
4✔
1512
        }
1513
    }
1514

1515
    if (!ypc->is_level(1) && vd == nullptr) {
7,462✔
1516
        return 1;
6,625✔
1517
    }
1518
    if (vd != nullptr
837✔
1519
        && vd->vd_meta.lvm_name == jlu->jlu_format->elf_thread_id_field)
837✔
1520
    {
1521
        jlu->jlu_tid_number = val;
156✔
1522
    }
1523
    jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
837✔
1524
        jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_INTEGER),
837✔
1525
        (int64_t) val);
837✔
1526
    return 1;
837✔
1527
}
1528

1529
static int
1530
rewrite_json_double(yajlpp_parse_context* ypc, double val)
142✔
1531
{
1532
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
142✔
1533
    const auto* vd = jlu->get_field_def(ypc);
142✔
1534

1535
    if (vd != nullptr) {
142✔
1536
        const intern_string_t field_name = vd->vd_meta.lvm_name;
138✔
1537
        if (jlu->jlu_format->lf_timestamp_field == field_name) {
138✔
1538
            long long divisor = jlu->jlu_format->elf_timestamp_divisor;
118✔
1539
            timeval tv;
1540

1541
            tv.tv_sec = val / divisor;
118✔
1542
            tv.tv_usec = fmod(val, divisor) * (1000000.0 / divisor);
118✔
1543
            jlu->jlu_format->lf_date_time.to_localtime(tv.tv_sec,
118✔
1544
                                                       jlu->jlu_exttm);
118✔
1545
            jlu->jlu_exttm.et_gmtoff
1546
                = jlu->jlu_format->lf_date_time.dts_local_offset_cache;
118✔
1547
            jlu->jlu_exttm.et_flags |= ETF_MACHINE_ORIENTED
118✔
1548
                | ETF_SUB_NOT_IN_FORMAT | ETF_ZONE_SET | ETF_Z_FOR_UTC;
1549
            if (divisor == 1) {
118✔
1550
                jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
110✔
1551
            } else {
1552
                jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
8✔
1553
            }
1554
            jlu->jlu_exttm.et_nsec = tv.tv_usec * 1000;
118✔
1555
        } else if (jlu->jlu_format->lf_subsecond_field == field_name) {
20✔
1556
            jlu->jlu_exttm.et_flags &= ~(ETF_MICROS_SET | ETF_MILLIS_SET);
×
1557
            switch (jlu->jlu_format->lf_subsecond_unit.value()) {
×
1558
                case log_format::subsecond_unit::milli:
×
1559
                    jlu->jlu_exttm.et_nsec = val * 1000000;
×
1560
                    jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
×
1561
                    break;
×
1562
                case log_format::subsecond_unit::micro:
×
1563
                    jlu->jlu_exttm.et_nsec = val * 1000;
×
1564
                    jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
×
1565
                    break;
×
1566
                case log_format::subsecond_unit::nano:
×
1567
                    jlu->jlu_exttm.et_nsec = val;
×
1568
                    jlu->jlu_exttm.et_flags |= ETF_NANOS_SET;
×
1569
                    break;
×
1570
            }
1571
            jlu->jlu_exttm.et_flags |= ETF_SUB_NOT_IN_FORMAT;
×
1572
        } else if (jlu->jlu_format->elf_duration_field == field_name) {
20✔
1573
            jlu->jlu_duration = std::chrono::microseconds(
40✔
1574
                static_cast<int64_t>(val * 1000000.0));
20✔
1575
        }
1576
    }
1577

1578
    if (!ypc->is_level(1) && vd == nullptr) {
142✔
1579
        return 1;
×
1580
    }
1581
    jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
142✔
1582
        jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_FLOAT),
284✔
1583
        val);
1584

1585
    return 1;
142✔
1586
}
1587

1588
static const json_path_container json_log_rewrite_handlers = {
1589
    yajlpp::pattern_property_handler("\\w+")
1590
        .add_cb(rewrite_json_null)
1591
        .add_cb(rewrite_json_bool)
1592
        .add_cb(rewrite_json_int)
1593
        .add_cb(rewrite_json_double)
1594
        .add_cb(rewrite_json_field),
1595
};
1596

1597
bool
1598
external_log_format::scan_for_partial(const log_format_file_state& lffs,
1✔
1599
                                      shared_buffer_ref& sbr,
1600
                                      size_t& len_out) const
1601
{
1602
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
1✔
1603
        return false;
×
1604
    }
1605

1606
    const auto& pat
1607
        = this->elf_pattern_order[lffs.lffs_pattern_locks.last_pattern_index()];
1✔
1608
    if (!this->lf_multiline) {
1✔
1609
        len_out = pat->p_pcre.pp_value->match_partial(sbr.to_string_fragment());
1✔
1610
        return true;
1✔
1611
    }
1612

1613
    if (pat->p_timestamp_end == -1 || pat->p_timestamp_end > (int) sbr.length())
×
1614
    {
1615
        len_out = 0;
×
1616
        return false;
×
1617
    }
1618

1619
    len_out = pat->p_pcre.pp_value->match_partial(sbr.to_string_fragment());
×
1620
    return (int) len_out > pat->p_timestamp_end;
×
1621
}
1622

1623
std::vector<lnav::console::snippet>
1624
external_log_format::get_snippets() const
23✔
1625
{
1626
    std::vector<lnav::console::snippet> retval;
23✔
1627

1628
    for (const auto& src_pair : this->elf_format_sources) {
46✔
1629
        retval.emplace_back(lnav::console::snippet::from(src_pair.first, "")
46✔
1630
                                .with_line(src_pair.second));
23✔
1631
    }
1632

1633
    return retval;
23✔
1634
}
×
1635

1636
log_format::scan_result_t
1637
external_log_format::scan_json(std::vector<logline>& dst,
180,534✔
1638
                               const line_info& li,
1639
                               shared_buffer_ref& sbr,
1640
                               scan_batch_context& sbc)
1641
{
1642
    logline ll(
1643
        li.li_file_range.fr_offset, std::chrono::microseconds{0}, LEVEL_INFO);
180,534✔
1644
    auto line_frag = sbr.to_string_fragment();
180,534✔
1645

1646
    if (!line_frag.startswith("{")) {
180,534✔
1647
        if (!this->lf_specialized) {
167,599✔
1648
            return scan_no_match{"line is not a JSON object"};
167,594✔
1649
        }
1650

1651
        if (!dst.empty()) {
5✔
1652
            ll.set_time(dst.back().get_time<std::chrono::microseconds>());
5✔
1653
        }
1654
        ll.set_level(LEVEL_INVALID);
5✔
1655
        dst.emplace_back(ll);
5✔
1656
        return scan_match{0};
5✔
1657
    }
1658

1659
    auto& ypc = *(this->jlf_parse_context);
12,935✔
1660
    yajl_handle handle = this->jlf_yajl_handle.get();
12,935✔
1661
    json_log_userdata jlu(sbr, &sbc);
12,935✔
1662

1663
    if (li.li_partial) {
12,935✔
1664
        log_debug("skipping partial line at offset %lld",
28✔
1665
                  li.li_file_range.fr_offset);
1666
        if (this->lf_specialized) {
28✔
1667
            if (!dst.empty()) {
2✔
1668
                ll.set_time(dst.back().get_time<std::chrono::microseconds>());
2✔
1669
            }
1670
            ll.set_level(LEVEL_INVALID);
2✔
1671
            dst.emplace_back(ll);
2✔
1672
        }
1673
        return scan_incomplete{};
28✔
1674
    }
1675

1676
    const auto* line_data = (const unsigned char*) sbr.get_data();
12,907✔
1677

1678
    this->lf_desc_captures.clear();
12,907✔
1679
    this->lf_desc_allocator.reset();
12,907✔
1680

1681
    yajl_reset(handle);
12,907✔
1682
    ypc.set_static_handler(json_log_handlers.jpc_children[0]);
12,907✔
1683
    ypc.ypc_userdata = &jlu;
12,907✔
1684
    ypc.ypc_ignore_unused = true;
12,907✔
1685
    ypc.ypc_alt_callbacks.yajl_start_array = json_array_start;
12,907✔
1686
    ypc.ypc_alt_callbacks.yajl_start_map = json_array_start;
12,907✔
1687
    ypc.ypc_alt_callbacks.yajl_end_array = read_array_end;
12,907✔
1688
    ypc.ypc_alt_callbacks.yajl_end_map = read_array_end;
12,907✔
1689
    jlu.jlu_format = this;
12,907✔
1690
    jlu.jlu_base_line = &ll;
12,907✔
1691
    jlu.jlu_line_value = sbr.get_data();
12,907✔
1692
    jlu.jlu_line_size = sbr.length();
12,907✔
1693
    jlu.jlu_handle = handle;
12,907✔
1694
    jlu.jlu_format_hits.resize(this->jlf_line_format.size());
12,907✔
1695
    if (yajl_parse(handle, line_data, sbr.length()) == yajl_status_ok
12,907✔
1696
        && yajl_complete_parse(handle) == yajl_status_ok)
12,907✔
1697
    {
1698
        if (jlu.jlu_scan_error) {
12,694✔
1699
            if (this->lf_specialized) {
19✔
1700
                if (!dst.empty()) {
10✔
1701
                    ll.set_time(
10✔
1702
                        dst.back().get_time<std::chrono::microseconds>());
10✔
1703
                }
1704
                ll.set_level(LEVEL_INVALID);
10✔
1705
                dst.emplace_back(ll);
10✔
1706
                return scan_match{0};
10✔
1707
            }
1708
            return jlu.jlu_scan_error.value();
9✔
1709
        }
1710
        if (ll.get_time<std::chrono::microseconds>().count() == 0) {
12,675✔
1711
            if (this->lf_specialized) {
8,449✔
1712
                if (!dst.empty()) {
×
1713
                    ll.set_time(
×
1714
                        dst.back().get_time<std::chrono::microseconds>());
×
1715
                }
1716
                ll.set_ignore(true);
×
1717
                dst.emplace_back(ll);
×
1718
                return scan_match{0};
×
1719
            }
1720

1721
            return scan_no_match{
8,449✔
1722
                "JSON message does not have expected timestamp property"};
8,449✔
1723
        }
1724

1725
        if (jlu.jlu_tid_frag) {
4,226✔
1726
            this->jlf_line_values.lvv_thread_id_value
1727
                = jlu.jlu_tid_frag->to_string();
124✔
1728
            auto tid_iter = sbc.sbc_tids.insert_tid(
248✔
1729
                sbc.sbc_allocator,
1730
                jlu.jlu_tid_frag.value(),
124✔
1731
                ll.get_time<std::chrono::microseconds>());
124✔
1732
            tid_iter->second.titr_level_stats.update_msg_count(
124✔
1733
                ll.get_msg_level());
1734
            ll.merge_bloom_bits(jlu.jlu_tid_frag->bloom_bits());
124✔
1735
        } else {
1736
            auto tid_iter = sbc.sbc_tids.insert_tid(
4,102✔
1737
                sbc.sbc_allocator,
1738
                string_fragment{},
×
1739
                ll.get_time<std::chrono::microseconds>());
4,102✔
1740
            tid_iter->second.titr_level_stats.update_msg_count(
4,102✔
1741
                ll.get_msg_level());
1742
        }
1743

1744
        auto found_opid_desc = false;
4,226✔
1745
        if (this->elf_opid_field.empty()
4,226✔
1746
            && this->lf_opid_source.value_or(opid_source_t::from_description)
799✔
1747
                == opid_source_t::from_description
1748
            && this->lf_opid_description_def->size() == 1)
5,025✔
1749
        {
1750
            const auto& od = this->lf_opid_description_def->begin()->second;
322✔
1751
            for (const auto& desc : *od.od_descriptors) {
966✔
1752
                auto desc_iter
1753
                    = this->lf_desc_captures.find(desc.od_field.pp_value);
644✔
1754
                if (desc_iter == this->lf_desc_captures.end()) {
644✔
1755
                    continue;
602✔
1756
                }
1757
                jlu.jlu_opid_hasher.update(desc_iter->second);
42✔
1758
                found_opid_desc = true;
42✔
1759
            }
1760

1761
        } else if (!jlu.jlu_opid_desc_frag && !jlu.jlu_opid_frag
5,438✔
1762
                   && jlu.jlu_duration > 0us)
5,438✔
1763
        {
1764
            jlu.jlu_opid_hasher.update(sbr.to_string_fragment());
×
1765
        }
1766

1767
        if (jlu.jlu_opid_desc_frag || jlu.jlu_duration > 0us
6,082✔
1768
            || (found_opid_desc && this->lf_opid_description_def->size() == 1))
6,082✔
1769
        {
1770
            char buf[hasher::STRING_SIZE];
1771
            jlu.jlu_opid_hasher.to_string(buf);
2,391✔
1772
            auto opid_frag = string_fragment::from_bytes(buf, sizeof(buf) - 1);
2,391✔
1773
            auto opid_iter = sbc.sbc_opids.los_opid_ranges.find(opid_frag);
2,391✔
1774
            if (opid_iter == sbc.sbc_opids.los_opid_ranges.end()) {
2,391✔
1775
                jlu.jlu_opid_frag = opid_frag.to_owned(sbc.sbc_allocator);
2,379✔
1776
            } else {
1777
                jlu.jlu_opid_frag = opid_iter->first;
12✔
1778
            }
1779
        }
1780

1781
        if (jlu.jlu_opid_frag) {
4,226✔
1782
            ll.merge_bloom_bits(jlu.jlu_opid_frag->bloom_bits());
3,392✔
1783
            this->jlf_line_values.lvv_opid_value
1784
                = jlu.jlu_opid_frag->to_string();
3,392✔
1785
            this->jlf_line_values.lvv_opid_provenance
1786
                = logline_value_vector::opid_provenance::file;
3,392✔
1787
            auto opid_iter = sbc.sbc_opids.insert_op(
6,784✔
1788
                sbc.sbc_allocator,
1789
                jlu.jlu_opid_frag.value(),
3,392✔
1790
                ll.get_time<std::chrono::microseconds>(),
3,392✔
1791
                this->lf_timestamp_point_of_reference,
1792
                jlu.jlu_duration);
1793
            opid_iter->second.otr_level_stats.update_msg_count(
3,392✔
1794
                ll.get_msg_level());
1795
            auto& elems = opid_iter->second.otr_description.lod_elements;
3,392✔
1796
            if (jlu.jlu_opid_desc_frag && elems.empty()) {
3,392✔
1797
                elems.insert(0,
×
1798
                             fmt::format(FMT_STRING(" {}"),
9,456✔
1799
                                         jlu.jlu_opid_desc_frag.value()));
1800
            }
1801

1802
            if (jlu.jlu_subid) {
3,392✔
1803
                auto subid_frag
1804
                    = string_fragment::from_str(jlu.jlu_subid.value());
×
1805

1806
                auto* ostr = sbc.sbc_opids.sub_op_in_use(
×
1807
                    sbc.sbc_allocator,
1808
                    opid_iter,
1809
                    subid_frag,
1810
                    ll.get_time<std::chrono::microseconds>(),
×
1811
                    ll.get_msg_level());
1812
                if (ostr != nullptr && ostr->ostr_description.empty()) {
×
1813
                    log_op_description sub_desc;
×
1814
                    this->update_op_description(
×
1815
                        *this->lf_subid_description_def_vec, sub_desc);
×
1816
                    if (!sub_desc.lod_elements.empty()) {
×
1817
                        auto& sub_desc_def
1818
                            = this->lf_subid_description_def_vec->at(
×
1819
                                sub_desc.lod_index.value());
×
1820
                        ostr->ostr_description
1821
                            = sub_desc_def->to_string(sub_desc.lod_elements);
×
1822
                    }
1823
                }
1824
            }
1825

1826
            auto& otr = opid_iter->second;
3,392✔
1827
            this->update_op_description(*this->lf_opid_description_def_vec,
3,392✔
1828
                                        otr.otr_description);
3,392✔
1829
        } else {
1830
            this->jlf_line_values.lvv_opid_value = std::nullopt;
834✔
1831
        }
1832

1833
        jlu.jlu_sub_line_count += this->jlf_line_format_init_count;
4,226✔
1834
        ll.set_has_ansi(jlu.jlu_has_ansi);
4,226✔
1835
        ll.set_valid_utf(jlu.jlu_valid_utf);
4,226✔
1836
        for (int lpc = 0; lpc < jlu.jlu_sub_line_count; lpc++) {
25,917✔
1837
            ll.set_sub_offset(lpc);
21,691✔
1838
            ll.set_continued(lpc > 0);
21,691✔
1839
            dst.emplace_back(ll);
21,691✔
1840
        }
1841
        this->lf_timestamp_flags = jlu.jlu_exttm.et_flags;
4,226✔
1842

1843
        if (!this->lf_specialized) {
4,226✔
1844
            static const intern_string_t ts_field
1845
                = intern_string::lookup("__timestamp__", -1);
3,629✔
1846
            static const intern_string_t level_field
1847
                = intern_string::lookup("__level__");
5,201✔
1848
            for (const auto& [index, jfe] :
33,883✔
1849
                 lnav::itertools::enumerate(this->jlf_line_format))
37,512✔
1850
            {
1851
                if (jfe.jfe_type != json_log_field::VARIABLE
80,739✔
1852
                    || jfe.jfe_value.pp_value == ts_field
19,597✔
1853
                    || jfe.jfe_value.pp_value == level_field
16,049✔
1854
                    || jfe.jfe_default_value != "-")
49,851✔
1855
                {
1856
                    continue;
20,231✔
1857
                }
1858
                if (!jlu.jlu_format_hits[index]) {
10,023✔
1859
                    jlu.jlu_strikes += 1;
9,483✔
1860
                }
1861
            }
1862
        }
1863
    } else {
1864
        unsigned char* msg;
1865
        int line_count = 2;
213✔
1866

1867
        msg = yajl_get_error(
426✔
1868
            handle, 1, (const unsigned char*) sbr.get_data(), sbr.length());
213✔
1869
        if (msg != nullptr) {
213✔
1870
            auto msg_frag = string_fragment::from_c_str(msg);
213✔
1871
            log_debug("Unable to parse line at offset %lld: %.*s",
213✔
1872
                      li.li_file_range.fr_offset,
1873
                      msg_frag.length(),
1874
                      msg_frag.data());
1875
            line_count = msg_frag.count('\n') + 1;
213✔
1876
            yajl_free_error(handle, msg);
213✔
1877
        }
1878
        if (!this->lf_specialized || dst.empty()) {
213✔
1879
            return scan_no_match{"JSON parsing failed"};
210✔
1880
        }
1881
        for (int lpc = 0; lpc < line_count; lpc++) {
15✔
1882
            log_level_t level = LEVEL_INVALID;
12✔
1883

1884
            ll.set_time(dst.back().get_timeval());
12✔
1885
            ll.set_continued(lpc > 0);
12✔
1886
            ll.set_level(level);
12✔
1887
            ll.set_sub_offset(lpc);
12✔
1888
            dst.emplace_back(ll);
12✔
1889
        }
1890
    }
1891

1892
    if (jlu.jlu_quality > 0) {
4,229✔
1893
        jlu.jlu_quality += 3000;
924✔
1894
    }
1895
    return scan_match{jlu.jlu_quality, jlu.jlu_strikes, jlu.jlu_precision};
4,229✔
1896
}
12,935✔
1897

1898
log_format::scan_result_t
1899
external_log_format::scan(logfile& lf,
896,910✔
1900
                          std::vector<logline>& dst,
1901
                          const line_info& li,
1902
                          shared_buffer_ref& sbr,
1903
                          scan_batch_context& sbc)
1904
{
1905
    if (dst.empty()) {
896,910✔
1906
        auto file_options = lf.get_file_options();
36,552✔
1907

1908
        if (file_options) {
36,552✔
1909
            this->lf_date_time.dts_default_zone
1910
                = file_options->second.fo_default_zone.pp_value;
2,400✔
1911
        } else {
1912
            this->lf_date_time.dts_default_zone = nullptr;
34,152✔
1913
        }
1914
    }
36,552✔
1915

1916
    sbc.sbc_value_stats.resize(this->elf_value_defs.size());
896,910✔
1917
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
896,910✔
1918
        return this->scan_json(dst, li, sbr, sbc);
177,388✔
1919
    }
1920

1921
    int curr_fmt = -1, orig_lock = sbc.sbc_pattern_locks.last_pattern_index();
719,522✔
1922
    int pat_index = orig_lock;
719,522✔
1923
    auto line_sf = sbr.to_string_fragment();
719,522✔
1924
    thread_local auto md = lnav::pcre2pp::match_data::unitialized();
719,522✔
1925
    char tmp_opid_buf[hasher::STRING_SIZE];
1926

1927
    while (::next_format(this->elf_pattern_order, curr_fmt, pat_index)) {
2,357,263✔
1928
        auto* fpat = this->elf_pattern_order[curr_fmt].get();
1,643,777✔
1929
        auto* pat = fpat->p_pcre.pp_value.get();
1,643,777✔
1930

1931
        auto found_match
1932
            = pat->capture_from(line_sf).into(md).found_p(PCRE2_NO_UTF_CHECK);
1,643,777✔
1933
        if (!found_match) {
1,643,777✔
1934
            if (!sbc.sbc_pattern_locks.empty() && pat_index != -1) {
1,637,738✔
1935
                curr_fmt = -1;
2,011✔
1936
                pat_index = -1;
2,011✔
1937
            }
1938
            continue;
1,637,741✔
1939
        }
1940

1941
        auto ts = md[fpat->p_timestamp_field_index];
6,039✔
1942
        auto level_cap = md[fpat->p_level_field_index];
6,039✔
1943
        auto opid_cap = md[fpat->p_opid_field_index];
6,039✔
1944
        const char* last;
1945
        exttm log_time_tm;
6,039✔
1946
        timeval log_tv;
1947
        uint64_t opid_bloom = 0;
6,039✔
1948
        char combined_datetime_buf[512];
1949

1950
        if (fpat->p_time_field_index != -1) {
6,039✔
1951
            auto time_cap = md[fpat->p_time_field_index];
×
1952
            if (ts && time_cap) {
×
1953
                auto ts_str_len = snprintf(combined_datetime_buf,
×
1954
                                           sizeof(combined_datetime_buf),
1955
                                           "%.*sT%.*s",
1956
                                           ts->length(),
1957
                                           ts->data(),
1958
                                           time_cap->length(),
1959
                                           time_cap->data());
1960
                ts = string_fragment::from_bytes(combined_datetime_buf,
×
1961
                                                 ts_str_len);
×
1962
            }
1963
        }
1964

1965
        auto level = this->convert_level(
6,039✔
1966
            level_cap.value_or(string_fragment::invalid()), &sbc);
6,039✔
1967

1968
        if (!ts) {
6,039✔
1969
            level = log_level_t::LEVEL_INVALID;
×
1970
        } else if ((last
6,039✔
1971
                    = this->lf_date_time.scan(ts->data(),
12,078✔
1972
                                              ts->length(),
6,039✔
1973
                                              this->get_timestamp_formats(),
1974
                                              &log_time_tm,
1975
                                              log_tv))
1976
                   == nullptr)
6,039✔
1977
        {
1978
            auto ls = this->lf_date_time.unlock();
13✔
1979
            if ((last = this->lf_date_time.scan(ts->data(),
26✔
1980
                                                ts->length(),
13✔
1981
                                                this->get_timestamp_formats(),
1982
                                                &log_time_tm,
1983
                                                log_tv))
1984
                == nullptr)
13✔
1985
            {
1986
                this->lf_date_time.relock(ls);
2✔
1987
                continue;
3✔
1988
            }
1989
            if (last != nullptr) {
11✔
1990
                auto old_flags = this->lf_timestamp_flags & DATE_TIME_SET_FLAGS;
11✔
1991
                auto new_flags = log_time_tm.et_flags & DATE_TIME_SET_FLAGS;
11✔
1992

1993
                // It is unlikely a valid timestamp would lose much
1994
                // precision.
1995
                if (new_flags != old_flags) {
11✔
1996
                    continue;
1✔
1997
                }
1998
            }
1999

2000
            log_debug("%s:%zu: date-time re-locked to %d",
10✔
2001
                      lf.get_unique_path().c_str(),
2002
                      dst.size(),
2003
                      this->lf_date_time.dts_fmt_lock);
2004
        }
2005

2006
        this->lf_timestamp_flags = log_time_tm.et_flags;
6,036✔
2007

2008
        if (!(this->lf_timestamp_flags
12,072✔
2009
              & (ETF_MILLIS_SET | ETF_MICROS_SET | ETF_NANOS_SET))
6,036✔
2010
            && !dst.empty()
5,400✔
2011
            && dst.back().get_time<std::chrono::seconds>().count()
4,624✔
2012
                == log_tv.tv_sec
4,624✔
2013
            && dst.back()
14,927✔
2014
                    .get_subsecond_time<std::chrono::milliseconds>()
9,527✔
2015
                    .count()
3,491✔
2016
                != 0)
2017
        {
2018
            auto log_ms
2019
                = dst.back().get_subsecond_time<std::chrono::microseconds>();
×
2020

2021
            log_time_tm.et_nsec
2022
                = std::chrono::duration_cast<std::chrono::nanoseconds>(log_ms)
×
2023
                      .count();
×
2024
            log_tv.tv_usec
2025
                = std::chrono::duration_cast<std::chrono::microseconds>(log_ms)
×
2026
                      .count();
×
2027
        }
2028

2029
        if (!((log_time_tm.et_flags & ETF_DAY_SET)
6,036✔
2030
              && (log_time_tm.et_flags & ETF_MONTH_SET)
5,995✔
2031
              && (log_time_tm.et_flags & ETF_YEAR_SET)))
5,995✔
2032
        {
2033
            this->check_for_new_year(dst, log_time_tm, log_tv);
884✔
2034
        }
2035

2036
        auto log_us = to_us(log_tv);
6,036✔
2037
        if (this->elf_opid_field.empty()
6,036✔
2038
            && !fpat->p_opid_description_field_indexes.empty())
6,036✔
2039
        {
2040
            auto empty_desc = true;
4,054✔
2041
            hasher h;
4,054✔
2042
            for (const auto& fidx : fpat->p_opid_description_field_indexes) {
12,162✔
2043
                auto desc_cap = md[fidx];
8,108✔
2044
                if (desc_cap) {
8,108✔
2045
                    h.update(desc_cap.value());
8,060✔
2046
                    empty_desc = false;
8,060✔
2047
                }
2048
            }
2049
            if (!empty_desc) {
4,054✔
2050
                h.to_string(tmp_opid_buf);
4,054✔
2051
                opid_cap = string_fragment::from_bytes(
8,108✔
2052
                    tmp_opid_buf, sizeof(tmp_opid_buf) - 1);
4,054✔
2053
            }
2054
        }
2055

2056
        auto duration_cap = md[fpat->p_duration_field_index];
6,036✔
2057
        if (duration_cap && !opid_cap) {
6,036✔
2058
            hasher h;
86✔
2059
            h.update(line_sf);
86✔
2060
            h.to_string(tmp_opid_buf);
86✔
2061
            opid_cap = string_fragment::from_bytes(tmp_opid_buf,
172✔
2062
                                                   sizeof(tmp_opid_buf) - 1);
86✔
2063
        }
2064
        if (opid_cap && !opid_cap->empty()) {
6,036✔
2065
            auto duration = std::chrono::microseconds{0};
4,990✔
2066
            if (duration_cap) {
4,990✔
2067
                auto from_res
2068
                    = humanize::try_from<double>(duration_cap.value());
86✔
2069
                if (from_res) {
86✔
2070
                    duration = std::chrono::microseconds(
×
2071
                        static_cast<int64_t>(from_res.value() * 1000000));
86✔
2072
                }
2073
            }
2074
            auto opid_iter
2075
                = sbc.sbc_opids.insert_op(sbc.sbc_allocator,
9,980✔
2076
                                          opid_cap.value(),
4,990✔
2077
                                          log_us,
2078
                                          this->lf_timestamp_point_of_reference,
2079
                                          duration);
2080
            auto& otr = opid_iter->second;
4,990✔
2081

2082
            otr.otr_level_stats.update_msg_count(level);
4,990✔
2083
            if (fpat->p_subid_field_index != -1) {
4,990✔
2084
                auto subid_cap = md[fpat->p_subid_field_index];
62✔
2085
                if (subid_cap && !subid_cap->empty()) {
62✔
2086
                    auto* ostr = sbc.sbc_opids.sub_op_in_use(sbc.sbc_allocator,
186✔
2087
                                                             opid_iter,
2088
                                                             subid_cap.value(),
62✔
2089
                                                             log_us,
2090
                                                             level);
2091
                    if (ostr != nullptr && ostr->ostr_description.empty()) {
62✔
2092
                        log_op_description sub_desc;
41✔
2093
                        this->update_op_description(
41✔
2094
                            *this->lf_subid_description_def_vec,
41✔
2095
                            sub_desc,
2096
                            fpat,
2097
                            md);
2098
                        if (!sub_desc.lod_elements.empty()) {
41✔
2099
                            auto& sub_desc_def
2100
                                = this->lf_subid_description_def_vec->at(
39✔
2101
                                    sub_desc.lod_index.value());
39✔
2102
                            ostr->ostr_description = sub_desc_def->to_string(
78✔
2103
                                sub_desc.lod_elements);
39✔
2104
                        }
2105
                    }
41✔
2106
                }
2107
            }
2108
            this->update_op_description(*this->lf_opid_description_def_vec,
4,990✔
2109
                                        otr.otr_description,
4,990✔
2110
                                        fpat,
2111
                                        md);
2112
            opid_bloom = opid_cap->bloom_bits();
4,990✔
2113
        }
2114

2115
        for (const auto& ivd : fpat->p_value_by_index) {
67,789✔
2116
            if (!ivd.ivd_value_def->vd_meta.lvm_values_index) {
61,753✔
2117
                continue;
11,379✔
2118
            }
2119

2120
            ssize_t cap_size = md.capture_size(ivd.ivd_index);
50,374✔
2121
            auto& lvs = sbc.sbc_value_stats[ivd.ivd_value_def->vd_meta
50,374✔
2122
                                                .lvm_values_index.value()];
50,374✔
2123

2124
            if (cap_size > lvs.lvs_width) {
50,374✔
2125
                lvs.lvs_width = cap_size;
6,646✔
2126
            }
2127
        }
2128

2129
        for (auto value_index : fpat->p_numeric_value_indexes) {
10,930✔
2130
            const indexed_value_def& ivd = fpat->p_value_by_index[value_index];
4,894✔
2131
            const value_def& vd = *ivd.ivd_value_def;
4,894✔
2132
            auto num_cap = md[ivd.ivd_index];
4,894✔
2133

2134
            if (vd.vd_meta.lvm_identifier) {
4,894✔
2135
                continue;
×
2136
            }
2137

2138
            if (num_cap && num_cap->is_valid()) {
4,894✔
2139
                const scaling_factor* scaling = nullptr;
4,828✔
2140

2141
                if (ivd.ivd_unit_field_index >= 0) {
4,828✔
2142
                    auto unit_cap = md[ivd.ivd_unit_field_index];
80✔
2143

2144
                    if (unit_cap && unit_cap->is_valid()) {
80✔
2145
                        intern_string_t unit_val
2146
                            = intern_string::lookup(unit_cap.value());
80✔
2147

2148
                        auto unit_iter = vd.vd_unit_scaling.find(unit_val);
80✔
2149
                        if (unit_iter != vd.vd_unit_scaling.end()) {
80✔
2150
                            const auto& sf = unit_iter->second;
80✔
2151

2152
                            scaling = &sf;
80✔
2153
                        }
2154
                    }
2155
                }
2156

2157
                std::optional<double> dvalue_opt;
4,828✔
2158
                switch (vd.vd_meta.lvm_kind) {
4,828✔
2159
                    case value_kind_t::VALUE_INTEGER: {
4,662✔
2160
                        auto scan_res
2161
                            = scn::scan_int<int64_t>(num_cap->to_string_view());
4,662✔
2162
                        if (scan_res) {
4,662✔
2163
                            dvalue_opt = scan_res->value();
4,662✔
2164
                        }
2165
                        break;
4,662✔
2166
                    }
2167
                    case value_kind_t::VALUE_FLOAT: {
166✔
2168
                        auto scan_res = scn::scan_value<double>(
2169
                            num_cap->to_string_view());
166✔
2170
                        if (scan_res) {
166✔
2171
                            dvalue_opt = scan_res->value();
166✔
2172
                        }
2173
                        break;
166✔
2174
                    }
2175
                    default:
×
2176
                        break;
×
2177
                }
2178
                if (dvalue_opt) {
4,828✔
2179
                    auto dvalue = dvalue_opt.value();
4,828✔
2180
                    if (scaling != nullptr) {
4,828✔
2181
                        scaling->scale(dvalue);
80✔
2182
                    }
2183
                    sbc.sbc_value_stats[vd.vd_meta.lvm_values_index.value()]
4,828✔
2184
                        .add_value(dvalue);
4,828✔
2185
                }
2186
            }
2187
        }
2188

2189
        dst.emplace_back(li.li_file_range.fr_offset, log_us, level);
6,036✔
2190
        auto& new_line = dst.back();
6,036✔
2191
        new_line.merge_bloom_bits(opid_bloom);
6,036✔
2192

2193
        auto src_file_cap = md[fpat->p_src_file_field_index];
6,036✔
2194
        auto src_line_cap = md[fpat->p_src_line_field_index];
6,036✔
2195
        if (src_file_cap && src_line_cap) {
6,036✔
2196
            auto h = hasher();
142✔
2197
            h.update(this->get_name().c_str());
142✔
2198
            h.update(src_file_cap.value());
142✔
2199
            h.update(src_line_cap.value());
142✔
2200
            new_line.merge_bloom_bits(h.to_bloom_bits());
142✔
2201
            new_line.set_schema_computed(true);
142✔
2202
        }
2203
        auto thread_id_cap = md[fpat->p_thread_id_field_index];
6,036✔
2204
        if (thread_id_cap) {
6,036✔
2205
            auto tid_iter = sbc.sbc_tids.insert_tid(
2,270✔
2206
                sbc.sbc_allocator, thread_id_cap.value(), log_us);
1,135✔
2207
            tid_iter->second.titr_level_stats.update_msg_count(level);
1,135✔
2208
            new_line.merge_bloom_bits(thread_id_cap->bloom_bits());
1,135✔
2209
        } else {
2210
            auto tid_iter = sbc.sbc_tids.insert_tid(
4,901✔
2211
                sbc.sbc_allocator, string_fragment{}, log_us);
×
2212
            tid_iter->second.titr_level_stats.update_msg_count(level);
4,901✔
2213
        }
2214

2215
        if (orig_lock != curr_fmt) {
6,036✔
2216
            uint32_t lock_line;
2217

2218
            if (!this->lf_specialized && orig_lock != -1) {
652✔
2219
                log_debug("%s:%zu: changing pattern lock %d -> (%d)%s",
×
2220
                          lf.get_unique_path().c_str(),
2221
                          dst.size() - 1,
2222
                          orig_lock,
2223
                          curr_fmt,
2224
                          this->elf_pattern_order[curr_fmt]->p_name.c_str());
2225
            }
2226
            if (sbc.sbc_pattern_locks.empty()) {
652✔
2227
                lock_line = 0;
626✔
2228
            } else {
2229
                lock_line = dst.size() - 1;
26✔
2230
            }
2231
            sbc.sbc_pattern_locks.pl_lines.emplace_back(lock_line, curr_fmt);
652✔
2232
        }
2233
        return scan_match{1000};
6,036✔
2234
    }
2235

2236
    if (this->lf_specialized && !this->lf_multiline && !dst.empty()) {
713,486✔
2237
        const auto& last_line = dst.back();
1✔
2238

2239
        log_debug("%s: invalid line %zu file_offset=%" PRIu64,
1✔
2240
                  lf.get_filename().c_str(),
2241
                  dst.size(),
2242
                  li.li_file_range.fr_offset);
2243
        dst.emplace_back(li.li_file_range.fr_offset,
1✔
2244
                         last_line.get_time<std::chrono::microseconds>(),
×
2245
                         log_level_t::LEVEL_INVALID);
1✔
2246

2247
        return scan_match{0};
1✔
2248
    }
2249

2250
    return scan_no_match{"no patterns matched"};
713,485✔
2251
}
2252

2253
void
2254
external_log_format::annotate(logfile* lf,
7,587✔
2255
                              uint64_t line_number,
2256
                              string_attrs_t& sa,
2257
                              logline_value_vector& values) const
2258
{
2259
    thread_local auto md = lnav::pcre2pp::match_data::unitialized();
7,587✔
2260

2261
    auto& line = values.lvv_sbr;
7,587✔
2262
    line_range lr;
7,587✔
2263

2264
    line.erase_ansi();
7,587✔
2265
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
7,587✔
2266
        if (this->jlf_cached_opts.full_message) {
795✔
2267
            values = this->jlf_line_values;
337✔
2268
            sa = this->jlf_attr_line.al_attrs;
337✔
2269
        } else {
2270
            values.lvv_sbr = this->jlf_line_values.lvv_sbr.clone();
458✔
2271
            for (const auto& llv : this->jlf_line_values.lvv_values) {
4,691✔
2272
                if (this->jlf_cached_sub_range.contains(llv.lv_origin)) {
4,233✔
2273
                    values.lvv_values.emplace_back(llv);
953✔
2274
                    values.lvv_values.back().lv_origin.shift(
953✔
2275
                        this->jlf_cached_sub_range.lr_start,
953✔
2276
                        -this->jlf_cached_sub_range.lr_start);
953✔
2277
                }
2278
            }
2279
            for (const auto& attr : this->jlf_attr_line.al_attrs) {
2,615✔
2280
                if (this->jlf_cached_sub_range.contains(attr.sa_range)) {
2,157✔
2281
                    sa.emplace_back(attr);
749✔
2282
                    sa.back().sa_range.shift(
749✔
2283
                        this->jlf_cached_sub_range.lr_start,
749✔
2284
                        -this->jlf_cached_sub_range.lr_start);
749✔
2285
                }
2286
            }
2287
            values.lvv_opid_value = this->jlf_line_values.lvv_opid_value;
458✔
2288
            values.lvv_opid_provenance
2289
                = this->jlf_line_values.lvv_opid_provenance;
458✔
2290
            values.lvv_thread_id_value
2291
                = this->jlf_line_values.lvv_thread_id_value;
458✔
2292
        }
2293
        log_format::annotate(lf, line_number, sa, values);
795✔
2294
        return;
2,444✔
2295
    }
2296

2297
    if (line.empty()) {
6,792✔
2298
        return;
5✔
2299
    }
2300

2301
    values.lvv_values.reserve(this->elf_value_defs.size());
6,787✔
2302

2303
    auto lffs = lf->get_format_file_state();
6,787✔
2304
    int pat_index = lffs.lffs_pattern_locks.pattern_index_for_line(line_number);
6,787✔
2305
    const auto& pat = *this->elf_pattern_order[pat_index];
6,787✔
2306
    char tmp_opid_buf[hasher::STRING_SIZE];
2307

2308
    sa.reserve(pat.p_pcre.pp_value->get_capture_count());
6,787✔
2309
    auto match_res
2310
        = pat.p_pcre.pp_value->capture_from(line.to_string_fragment())
6,787✔
2311
              .into(md)
6,787✔
2312
              .matches(PCRE2_NO_UTF_CHECK)
13,574✔
2313
              .ignore_error();
6,787✔
2314
    if (!match_res) {
6,787✔
2315
        // A continued line still needs a body.
2316
        lr.lr_start = 0;
1,644✔
2317
        lr.lr_end = line.length();
1,644✔
2318
        sa.emplace_back(lr, SA_BODY.value());
1,644✔
2319
        if (!this->lf_multiline) {
1,644✔
2320
            auto len
2321
                = pat.p_pcre.pp_value->match_partial(line.to_string_fragment());
×
2322
            sa.emplace_back(
×
2323
                line_range{(int) len, -1},
×
2324
                SA_INVALID.value("Log line does not match any pattern"));
×
2325
        }
2326
        return;
1,644✔
2327
    }
2328

2329
    auto duration_cap = md[pat.p_duration_field_index];
5,143✔
2330

2331
    auto ts_cap = md[pat.p_timestamp_field_index];
5,143✔
2332
    if (ts_cap) {
5,143✔
2333
        sa.emplace_back(to_line_range(ts_cap.value()), L_TIMESTAMP.value());
5,143✔
2334
    }
2335

2336
    auto opid_cap = md[pat.p_opid_field_index];
5,143✔
2337

2338
    if (this->elf_opid_field.empty()
5,143✔
2339
        && !pat.p_opid_description_field_indexes.empty())
5,143✔
2340
    {
2341
        auto empty_desc = true;
3,793✔
2342
        hasher h;
3,793✔
2343
        for (const auto& fidx : pat.p_opid_description_field_indexes) {
11,379✔
2344
            auto desc_cap = md[fidx];
7,586✔
2345
            if (desc_cap) {
7,586✔
2346
                h.update(desc_cap.value());
7,558✔
2347
                empty_desc = false;
7,558✔
2348
            }
2349
        }
2350
        if (!empty_desc) {
3,793✔
2351
            h.to_string(tmp_opid_buf);
3,793✔
2352
            opid_cap = string_fragment::from_bytes(tmp_opid_buf,
7,586✔
2353
                                                   sizeof(tmp_opid_buf) - 1);
3,793✔
2354
        }
2355
    } else if (duration_cap && !opid_cap) {
1,350✔
2356
        hasher h;
3✔
2357
        h.update(line.to_string_fragment());
3✔
2358
        h.to_string(tmp_opid_buf);
3✔
2359
        opid_cap = string_fragment::from_bytes(tmp_opid_buf,
6✔
2360
                                               sizeof(tmp_opid_buf) - 1);
3✔
2361
    }
2362
    if (opid_cap && !opid_cap->empty()) {
5,143✔
2363
        sa.emplace_back(to_line_range(opid_cap.value()), L_OPID.value());
4,276✔
2364
        values.lvv_opid_value = opid_cap->to_string();
4,276✔
2365
        values.lvv_opid_provenance
2366
            = logline_value_vector::opid_provenance::file;
4,276✔
2367
    }
2368

2369
    auto body_cap = md[pat.p_body_field_index];
5,143✔
2370
    auto level_cap = md[pat.p_level_field_index];
5,143✔
2371
    auto src_file_cap = md[pat.p_src_file_field_index];
5,143✔
2372
    auto src_line_cap = md[pat.p_src_line_field_index];
5,143✔
2373
    auto thread_id_cap = md[pat.p_thread_id_field_index];
5,143✔
2374

2375
    if (level_cap
5,143✔
2376
        && (!body_cap
10,240✔
2377
            || (body_cap && level_cap->sf_begin != body_cap->sf_begin)))
10,240✔
2378
    {
2379
        sa.emplace_back(to_line_range(level_cap.value()), L_LEVEL.value());
4,669✔
2380
    }
2381

2382
    if (src_file_cap) {
5,143✔
2383
        sa.emplace_back(to_line_range(src_file_cap.value()),
150✔
2384
                        SA_SRC_FILE.value());
300✔
2385
    }
2386
    if (src_line_cap) {
5,143✔
2387
        sa.emplace_back(to_line_range(src_line_cap.value()),
150✔
2388
                        SA_SRC_LINE.value());
300✔
2389
    }
2390
    if (thread_id_cap) {
5,143✔
2391
        sa.emplace_back(to_line_range(thread_id_cap.value()),
695✔
2392
                        SA_THREAD_ID.value());
1,390✔
2393
        values.lvv_thread_id_value = thread_id_cap->to_string();
695✔
2394
    }
2395
    if (duration_cap) {
5,143✔
2396
        sa.emplace_back(to_line_range(duration_cap.value()),
3✔
2397
                        SA_DURATION.value());
6✔
2398
    }
2399

2400
    for (size_t lpc = 0; lpc < pat.p_value_by_index.size(); lpc++) {
58,545✔
2401
        const auto& ivd = pat.p_value_by_index[lpc];
53,402✔
2402
        const scaling_factor* scaling = nullptr;
53,402✔
2403
        auto cap = md[ivd.ivd_index];
53,402✔
2404
        const auto& vd = *ivd.ivd_value_def;
53,402✔
2405

2406
        if (ivd.ivd_unit_field_index >= 0) {
53,402✔
2407
            auto unit_cap = md[ivd.ivd_unit_field_index];
10✔
2408

2409
            if (unit_cap) {
10✔
2410
                intern_string_t unit_val
2411
                    = intern_string::lookup(unit_cap.value());
10✔
2412
                auto unit_iter = vd.vd_unit_scaling.find(unit_val);
10✔
2413
                if (unit_iter != vd.vd_unit_scaling.end()) {
10✔
2414
                    const auto& sf = unit_iter->second;
10✔
2415

2416
                    scaling = &sf;
10✔
2417
                }
2418
            }
2419
        }
2420

2421
        if (cap) {
53,402✔
2422
            if (vd.vd_meta.lvm_kind == value_kind_t::VALUE_TIMESTAMP) {
43,656✔
2423
                auto dts = this->build_time_scanner();
7✔
2424
                exttm tm;
7✔
2425
                timeval tv;
2426
                auto val_sf = cap.value();
7✔
2427

2428
                if (dts.scan(val_sf.data(),
14✔
2429
                             val_sf.length(),
7✔
2430
                             this->get_timestamp_formats(),
2431
                             &tm,
2432
                             tv,
2433
                             true))
2434
                {
2435
                    char ts[64];
2436
                    tm.et_gmtoff = tm.et_orig_gmtoff;
7✔
2437
                    auto len = dts.ftime(
7✔
2438
                        ts, sizeof(ts), this->get_timestamp_formats(), tm);
2439
                    ts[len] = '\0';
7✔
2440
                    values.lvv_values.emplace_back(vd.vd_meta,
7✔
2441
                                                   std::string{ts, len});
21✔
2442
                    values.lvv_values.back().lv_origin
7✔
2443
                        = to_line_range(cap.value());
14✔
2444
                } else {
2445
                    values.lvv_values.emplace_back(
×
2446
                        vd.vd_meta, line, to_line_range(cap.value()));
×
2447
                }
2448
            } else {
2449
                values.lvv_values.emplace_back(
87,298✔
2450
                    vd.vd_meta, line, to_line_range(cap.value()));
43,649✔
2451
                values.lvv_values.back().apply_scaling(scaling);
43,649✔
2452
            }
2453
        } else {
2454
            values.lvv_values.emplace_back(vd.vd_meta);
9,746✔
2455
        }
2456
    }
2457

2458
    if (body_cap && body_cap->is_valid()) {
5,143✔
2459
        lr = to_line_range(body_cap.value());
5,131✔
2460
    } else {
2461
        lr.lr_start = line.length();
12✔
2462
        lr.lr_end = line.length();
12✔
2463
    }
2464
    sa.emplace_back(lr, SA_BODY.value());
5,143✔
2465

2466
    log_format::annotate(lf, line_number, sa, values);
5,143✔
2467
}
2468

2469
void
2470
external_log_format::rewrite(exec_context& ec,
43✔
2471
                             shared_buffer_ref& line,
2472
                             string_attrs_t& sa,
2473
                             std::string& value_out)
2474
{
2475
    auto pg = ec.with_provenance(exec_context::format_rewrite{});
43✔
2476
    auto& values = *ec.ec_line_values;
43✔
2477

2478
    value_out.assign(line.get_data(), line.length());
43✔
2479

2480
    for (auto iter = values.lvv_values.begin(); iter != values.lvv_values.end();
251✔
2481
         ++iter)
208✔
2482
    {
2483
        if (!iter->lv_origin.is_valid()) {
208✔
2484
            log_debug("%d: not rewriting value with invalid origin -- %s",
22✔
2485
                      (int) ec.ec_top_line,
2486
                      iter->lv_meta.lvm_name.get());
2487
            continue;
178✔
2488
        }
2489

2490
        auto vd_iter = this->elf_value_defs.find(iter->lv_meta.lvm_name);
186✔
2491
        if (vd_iter == this->elf_value_defs.end()) {
186✔
2492
            log_debug("%d: not rewriting undefined value -- %s",
×
2493
                      (int) ec.ec_top_line,
2494
                      iter->lv_meta.lvm_name.get());
2495
            continue;
×
2496
        }
2497

2498
        const auto& vd = *vd_iter->second;
186✔
2499

2500
        if (vd.vd_rewriter.empty()) {
186✔
2501
            continue;
156✔
2502
        }
2503

2504
        auto _sg = ec.enter_source(
2505
            vd_iter->second->vd_rewrite_src_name, 1, vd.vd_rewriter);
30✔
2506
        std::string field_value;
30✔
2507

2508
        auto_mem<FILE> tmpout(fclose);
30✔
2509

2510
        tmpout = std::tmpfile();
30✔
2511
        if (!tmpout) {
30✔
2512
            log_error("unable to create temporary file");
×
2513
            return;
×
2514
        }
2515
        fcntl(fileno(tmpout), F_SETFD, FD_CLOEXEC);
30✔
2516
        auto fd_copy = auto_fd::dup_of(fileno(tmpout));
30✔
2517
        fd_copy.close_on_exec();
30✔
2518
        auto ec_out = std::make_pair(tmpout.release(), fclose);
30✔
2519
        {
2520
            exec_context::output_guard og(ec, "tmp", ec_out);
60✔
2521

2522
            auto exec_res = execute_any(ec, vd.vd_rewriter);
30✔
2523
            if (exec_res.isOk()) {
30✔
2524
                field_value = exec_res.unwrap();
30✔
2525
            } else {
2526
                field_value = exec_res.unwrapErr().to_attr_line().get_string();
×
2527
            }
2528
        }
30✔
2529
        struct stat st;
2530
        fstat(fd_copy.get(), &st);
30✔
2531
        if (st.st_size > 0) {
30✔
2532
            auto buf = auto_buffer::alloc(st.st_size);
2✔
2533

2534
            buf.resize(st.st_size);
2✔
2535
            pread(fd_copy.get(), buf.in(), st.st_size, 0);
2✔
2536
            field_value = buf.to_string();
2✔
2537
        }
2✔
2538
        value_out.erase(iter->lv_origin.lr_start, iter->lv_origin.length());
30✔
2539

2540
        int32_t shift_amount
2541
            = ((int32_t) field_value.length()) - iter->lv_origin.length();
30✔
2542
        auto orig_lr = iter->lv_origin;
30✔
2543
        value_out.insert(iter->lv_origin.lr_start, field_value);
30✔
2544
        for (auto shift_iter = values.lvv_values.begin();
30✔
2545
             shift_iter != values.lvv_values.end();
170✔
2546
             ++shift_iter)
140✔
2547
        {
2548
            shift_iter->lv_origin.shift_range(orig_lr, shift_amount);
140✔
2549
        }
2550
        shift_string_attrs(sa, orig_lr, shift_amount);
30✔
2551
    }
30✔
2552
}
43✔
2553

2554
static int
2555
read_json_field(yajlpp_parse_context* ypc,
239,230✔
2556
                const unsigned char* str,
2557
                size_t len,
2558
                yajl_string_props_t* props)
2559
{
2560
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
239,230✔
2561
    timeval tv_out;
2562
    const auto frag = string_fragment::from_bytes(str, len);
239,230✔
2563
    intern_string_t field_name;
239,230✔
2564
    const auto* vd = jlu->get_field_def(ypc);
239,230✔
2565

2566
    if (vd != nullptr) {
239,230✔
2567
        field_name = vd->vd_meta.lvm_name;
20,983✔
2568
    }
2569

2570
    if (field_name.empty()) {
239,230✔
2571
        if (!jlu->jlu_format->elf_opid_field.empty()) {
218,247✔
2572
            auto path_sf = ypc->get_path_as_string_fragment();
71,353✔
2573
            if (path_sf.startswith(jlu->jlu_format->elf_opid_field.c_str())) {
71,353✔
2574
                jlu->jlu_opid_hasher.update(path_sf);
9,453✔
2575
                jlu->jlu_opid_hasher.update(frag);
9,453✔
2576
            }
2577
        }
2578
    } else if (jlu->jlu_format->lf_timestamp_field == field_name) {
20,983✔
2579
        const auto* last = jlu->jlu_format->lf_date_time.scan(
4,138✔
2580
            (const char*) str,
2581
            len,
2582
            jlu->jlu_format->get_timestamp_formats(),
4,138✔
2583
            &jlu->jlu_exttm,
2584
            tv_out);
2585
        if (last == nullptr) {
4,138✔
2586
            auto ls = jlu->jlu_format->lf_date_time.unlock();
41✔
2587
            if ((last = jlu->jlu_format->lf_date_time.scan(
41✔
2588
                     (const char*) str,
2589
                     len,
2590
                     jlu->jlu_format->get_timestamp_formats(),
41✔
2591
                     &jlu->jlu_exttm,
2592
                     tv_out))
2593
                == nullptr)
41✔
2594
            {
2595
                jlu->jlu_format->lf_date_time.relock(ls);
19✔
2596
            }
2597
            if (last != nullptr) {
41✔
2598
                auto old_flags
22✔
2599
                    = jlu->jlu_format->lf_timestamp_flags & DATE_TIME_SET_FLAGS;
22✔
2600
                auto new_flags = jlu->jlu_exttm.et_flags & DATE_TIME_SET_FLAGS;
22✔
2601

2602
                // It is unlikely a valid timestamp would lose much
2603
                // precision.
2604
                if (new_flags != old_flags) {
22✔
2605
                    last = nullptr;
×
2606
                }
2607
            }
2608
        }
2609
        if (last != nullptr) {
4,138✔
2610
            jlu->jlu_format->lf_timestamp_flags = jlu->jlu_exttm.et_flags;
4,119✔
2611
            jlu->jlu_base_line->set_time(tv_out);
4,119✔
2612
        } else {
2613
            jlu->jlu_scan_error = log_format::scan_error{fmt::format(
19✔
2614
                "failed to parse timestamp '{}' in string property '{}'",
2615
                frag,
2616
                field_name)};
19✔
2617
        }
2618
    } else if (jlu->jlu_format->elf_level_pointer.pp_value != nullptr) {
16,845✔
2619
        if (jlu->jlu_format->elf_level_pointer.pp_value
230✔
2620
                ->find_in(field_name.to_string_fragment(), PCRE2_NO_UTF_CHECK)
230✔
2621
                .ignore_error()
230✔
2622
                .has_value())
115✔
2623
        {
2624
            jlu->jlu_base_line->set_level(
×
2625
                jlu->jlu_format->convert_level(frag, jlu->jlu_batch_context));
×
2626
        }
2627
    }
2628
    if (!field_name.empty() && jlu->jlu_format->elf_level_field == field_name) {
239,230✔
2629
        jlu->jlu_base_line->set_level(
4,293✔
2630
            jlu->jlu_format->convert_level(frag, jlu->jlu_batch_context));
4,293✔
2631
    }
2632
    if (!field_name.empty() && jlu->jlu_format->elf_opid_field == field_name) {
239,230✔
2633
        jlu->jlu_base_line->merge_bloom_bits(frag.bloom_bits());
1,002✔
2634

2635
        auto& sbc = *jlu->jlu_batch_context;
1,002✔
2636
        auto opid_iter = sbc.sbc_opids.los_opid_ranges.find(frag);
1,002✔
2637
        if (opid_iter == sbc.sbc_opids.los_opid_ranges.end()) {
1,002✔
2638
            jlu->jlu_opid_frag = frag.to_owned(sbc.sbc_allocator);
972✔
2639
        } else {
2640
            jlu->jlu_opid_frag = opid_iter->first;
30✔
2641
        }
2642
    }
2643
    if (!field_name.empty()
239,230✔
2644
        && jlu->jlu_format->elf_thread_id_field == field_name)
239,230✔
2645
    {
2646
        auto& sbc = *jlu->jlu_batch_context;
×
2647
        auto tid_iter = sbc.sbc_tids.ltis_tid_ranges.find(frag);
×
2648
        if (tid_iter == sbc.sbc_tids.ltis_tid_ranges.end()) {
×
2649
            jlu->jlu_tid_frag = frag.to_owned(sbc.sbc_allocator);
×
2650
        } else {
2651
            jlu->jlu_tid_frag = tid_iter->first;
×
2652
        }
2653
    }
2654
    if (!jlu->jlu_format->elf_subid_field.empty()
239,230✔
2655
        && jlu->jlu_format->elf_subid_field == field_name)
239,230✔
2656
    {
2657
        jlu->jlu_subid = frag.to_string();
×
2658
    }
2659
    if (!field_name.empty()
239,230✔
2660
        && jlu->jlu_format->elf_duration_field == field_name)
239,230✔
2661
    {
2662
        auto from_res = humanize::try_from<double>(frag);
×
2663
        if (from_res) {
×
2664
            jlu->jlu_duration = std::chrono::microseconds(
×
2665
                static_cast<int64_t>(from_res.value() * 1000000));
2666
        }
2667
    }
2668

2669
    if (vd != nullptr && vd->vd_is_desc_field) {
239,230✔
2670
        auto frag_copy = frag.to_owned(jlu->jlu_format->lf_desc_allocator);
42✔
2671

2672
        jlu->jlu_format->lf_desc_captures.emplace(field_name, frag_copy);
42✔
2673
    }
2674

2675
    jlu->add_sub_lines_for(vd, ypc->is_level(1), std::nullopt, str, len, props);
239,230✔
2676

2677
    return 1;
239,230✔
2678
}
2679

2680
static int
2681
rewrite_json_field(yajlpp_parse_context* ypc,
47,771✔
2682
                   const unsigned char* str,
2683
                   size_t len,
2684
                   yajl_string_props_t* props)
2685
{
2686
    static const intern_string_t body_name = intern_string::lookup("body", -1);
47,771✔
2687
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
47,771✔
2688
    intern_string_t field_name;
47,771✔
2689
    const auto* vd = jlu->get_field_def(ypc);
47,771✔
2690
    auto frag = string_fragment::from_bytes(str, len);
47,771✔
2691

2692
    if (!ypc->is_level(1) && vd == nullptr) {
47,771✔
2693
        if (!jlu->jlu_format->elf_opid_field.empty()) {
37,266✔
2694
            auto path_sf = ypc->get_path_as_string_fragment();
36,642✔
2695
            if (path_sf.startswith(jlu->jlu_format->elf_opid_field.c_str())) {
36,642✔
2696
                jlu->jlu_opid_hasher.update(path_sf);
48✔
2697
                jlu->jlu_opid_hasher.update(frag);
48✔
2698
            }
2699
        }
2700
        return 1;
37,266✔
2701
    }
2702
    if (vd != nullptr) {
10,505✔
2703
        field_name = vd->vd_meta.lvm_name;
9,879✔
2704
    } else {
2705
        field_name = ypc->get_path();
626✔
2706
    }
2707

2708
    if (jlu->jlu_format->elf_opid_field == field_name) {
10,505✔
2709
        jlu->jlu_format->jlf_line_values.lvv_opid_value = frag.to_string();
646✔
2710
        jlu->jlu_format->jlf_line_values.lvv_opid_provenance
646✔
2711
            = logline_value_vector::opid_provenance::file;
646✔
2712
    }
2713
    if (jlu->jlu_format->elf_thread_id_field == field_name) {
10,505✔
2714
        jlu->jlu_format->jlf_line_values.lvv_thread_id_value = frag.to_string();
×
2715
    }
2716
    if (jlu->jlu_format->lf_timestamp_field == field_name) {
10,505✔
2717
        char time_buf[64];
2718

2719
        // TODO add a timeval kind to logline_value
2720
        if (jlu->jlu_line->is_time_skewed()
2,036✔
2721
            || jlu->jlu_line->get_msg_level() == LEVEL_INVALID
2,036✔
2722
            || (jlu->jlu_format->lf_timestamp_flags
4,072✔
2723
                & (ETF_MICROS_SET | ETF_NANOS_SET | ETF_ZONE_SET)))
1,954✔
2724
        {
2725
            timeval tv;
2726

2727
            const auto* last = jlu->jlu_format->lf_date_time.scan(
2,036✔
2728
                (const char*) str,
2729
                len,
2730
                jlu->jlu_format->get_timestamp_formats(),
2,036✔
2731
                &jlu->jlu_exttm,
2732
                tv);
2733
            if (last == nullptr) {
2,036✔
2734
                auto ls = jlu->jlu_format->lf_date_time.unlock();
124✔
2735
                if ((last = jlu->jlu_format->lf_date_time.scan(
124✔
2736
                         (const char*) str,
2737
                         len,
2738
                         jlu->jlu_format->get_timestamp_formats(),
124✔
2739
                         &jlu->jlu_exttm,
2740
                         tv))
2741
                    == nullptr)
124✔
2742
                {
2743
                    jlu->jlu_format->lf_date_time.relock(ls);
66✔
2744
                    jlu->jlu_scan_error = log_format::scan_error{
66✔
2745
                        fmt::format("failed to parse timestamp '{}' in string "
2746
                                    "property '{}'",
2747
                                    frag,
2748
                                    field_name)};
66✔
2749
                }
2750
            }
2751
            if (!jlu->jlu_subline_opts.hash_hack) {
2,036✔
2752
                if (jlu->jlu_exttm.et_flags & ETF_ZONE_SET
2,036✔
2753
                    && jlu->jlu_format->lf_date_time.dts_zoned_to_local)
1,970✔
2754
                {
2755
                    jlu->jlu_exttm.et_flags &= ~ETF_Z_IS_UTC;
1,970✔
2756
                }
2757
                jlu->jlu_exttm.et_gmtoff
2758
                    = jlu->jlu_format->lf_date_time.dts_local_offset_cache;
2,036✔
2759
            }
2760
            jlu->jlu_format->lf_date_time.ftime(
2,036✔
2761
                time_buf,
2762
                sizeof(time_buf),
2763
                jlu->jlu_format->get_timestamp_formats(),
2,036✔
2764
                jlu->jlu_exttm);
2,036✔
2765
        } else {
2766
            sql_strftime(
×
2767
                time_buf, sizeof(time_buf), jlu->jlu_line->get_timeval(), 'T');
×
2768
        }
2769
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
4,072✔
2770
            jlu->jlu_format->get_value_meta(field_name,
4,072✔
2771
                                            value_kind_t::VALUE_TEXT),
2772
            std::string{time_buf});
6,108✔
2773
    } else if (vd != nullptr
8,469✔
2774
               && vd->vd_meta.lvm_kind == value_kind_t::VALUE_TIMESTAMP)
7,843✔
2775
    {
2776
        auto dts = jlu->jlu_format->build_time_scanner();
223✔
2777
        exttm tm;
223✔
2778
        timeval tv;
2779

2780
        if (dts.scan((const char*) str,
223✔
2781
                     len,
2782
                     jlu->jlu_format->get_timestamp_formats(),
223✔
2783
                     &tm,
2784
                     tv,
2785
                     true))
2786
        {
2787
            char ts[64];
2788
            tm.et_gmtoff = tm.et_orig_gmtoff;
223✔
2789
            auto tslen = dts.ftime(
223✔
2790
                ts, sizeof(ts), jlu->jlu_format->get_timestamp_formats(), tm);
223✔
2791
            ts[tslen] = '\0';
223✔
2792
            jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
223✔
2793
                jlu->jlu_format->get_value_meta(
446✔
2794
                    ypc, vd, value_kind_t::VALUE_TIMESTAMP),
2795
                std::string{(const char*) ts, tslen});
892✔
2796
        } else {
2797
            jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
×
2798
                jlu->jlu_format->get_value_meta(
×
2799
                    ypc, vd, value_kind_t::VALUE_TEXT),
2800
                std::string{(const char*) str, len});
×
2801
        }
2802
    } else if (jlu->jlu_shared_buffer.contains((const char*) str)) {
8,469✔
2803
        auto str_offset = (int) ((const char*) str - jlu->jlu_line_value);
7,752✔
2804
        if (field_name == jlu->jlu_format->elf_body_field) {
7,752✔
2805
            jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
881✔
2806
                logline_value_meta(body_name,
1,762✔
2807
                                   value_kind_t::VALUE_TEXT,
2808
                                   logline_value_meta::internal_column{},
×
2809
                                   jlu->jlu_format),
881✔
2810
                string_fragment::from_byte_range(
1,762✔
2811
                    jlu->jlu_shared_buffer.get_data(),
881✔
2812
                    str_offset,
2813
                    str_offset + len));
881✔
2814
        }
2815

2816
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
7,752✔
2817
            jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_TEXT),
15,504✔
2818
            string_fragment::from_byte_range(jlu->jlu_shared_buffer.get_data(),
15,504✔
2819
                                             str_offset,
2820
                                             str_offset + len));
7,752✔
2821
    } else {
2822
        if (field_name == jlu->jlu_format->elf_body_field) {
494✔
2823
            jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
403✔
2824
                logline_value_meta(body_name,
806✔
2825
                                   value_kind_t::VALUE_TEXT,
2826
                                   logline_value_meta::internal_column{},
×
2827
                                   jlu->jlu_format),
403✔
2828
                std::string{(const char*) str, len});
1,612✔
2829
        }
2830

2831
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
494✔
2832
            jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_TEXT),
988✔
2833
            std::string{(const char*) str, len});
1,976✔
2834
    }
2835
    if (vd != nullptr && vd->vd_is_desc_field
9,879✔
2836
        && jlu->jlu_format->elf_opid_field.empty())
20,384✔
2837
    {
2838
        auto frag_copy = frag.to_owned(jlu->jlu_format->lf_desc_allocator);
48✔
2839

2840
        jlu->jlu_format->lf_desc_captures.emplace(field_name, frag_copy);
48✔
2841
    }
2842

2843
    return 1;
10,505✔
2844
}
2845

2846
void
2847
external_log_format::get_subline(const log_format_file_state& lffs,
22,670✔
2848
                                 const logline& ll,
2849
                                 shared_buffer_ref& sbr,
2850
                                 subline_options opts)
2851
{
2852
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT) {
22,670✔
2853
        return;
18,015✔
2854
    }
2855

2856
    if (this->jlf_cached_offset != ll.get_offset()
4,655✔
2857
        || this->jlf_cached_opts != opts)
4,655✔
2858
    {
2859
        auto& ypc = *(this->jlf_parse_context);
2,269✔
2860
        yajl_handle handle = this->jlf_yajl_handle.get();
2,269✔
2861
        json_log_userdata jlu(sbr, nullptr);
2,269✔
2862

2863
        jlu.jlu_subline_opts = opts;
2,269✔
2864

2865
        this->lf_desc_captures.clear();
2,269✔
2866
        this->lf_desc_allocator.reset();
2,269✔
2867
        this->jlf_share_manager.invalidate_refs();
2,269✔
2868
        this->jlf_attr_line.clear();
2,269✔
2869
        this->jlf_line_values.clear();
2,269✔
2870
        this->jlf_line_offsets.clear();
2,269✔
2871

2872
        auto line_frag = sbr.to_string_fragment();
2,269✔
2873

2874
        if (!line_frag.startswith("{")) {
2,269✔
2875
            this->jlf_attr_line.al_string.assign(line_frag.data(),
93✔
2876
                                                 line_frag.length());
93✔
2877
            this->jlf_line_values.clear();
93✔
2878
            sbr.share(this->jlf_share_manager,
186✔
2879
                      this->jlf_attr_line.al_string.data(),
93✔
2880
                      this->jlf_attr_line.al_string.size());
2881
            this->jlf_line_values.lvv_sbr = sbr.clone();
93✔
2882
            this->jlf_attr_line.al_attrs.emplace_back(
93✔
2883
                line_range{0, -1},
×
2884
                SA_INVALID.value(fmt::format(
186✔
2885
                    FMT_STRING("line at offset {} is not a JSON-line"),
186✔
2886
                    ll.get_offset())));
93✔
2887
            return;
93✔
2888
        }
2889

2890
        yajl_reset(handle);
2,176✔
2891
        ypc.set_static_handler(json_log_rewrite_handlers.jpc_children[0]);
2,176✔
2892
        ypc.ypc_userdata = &jlu;
2,176✔
2893
        ypc.ypc_ignore_unused = true;
2,176✔
2894
        ypc.ypc_alt_callbacks.yajl_start_array = json_array_start_const;
2,176✔
2895
        ypc.ypc_alt_callbacks.yajl_end_array = json_array_end;
2,176✔
2896
        ypc.ypc_alt_callbacks.yajl_start_map = json_array_start_const;
2,176✔
2897
        ypc.ypc_alt_callbacks.yajl_end_map = json_array_end;
2,176✔
2898
        jlu.jlu_format = this;
2,176✔
2899
        jlu.jlu_line = &ll;
2,176✔
2900
        jlu.jlu_handle = handle;
2,176✔
2901
        jlu.jlu_line_value = sbr.get_data();
2,176✔
2902
        jlu.jlu_format_hits.resize(this->jlf_line_format.size());
2,176✔
2903

2904
        yajl_status parse_status = yajl_parse(
4,352✔
2905
            handle, (const unsigned char*) sbr.get_data(), sbr.length());
2,176✔
2906
        if (parse_status != yajl_status_ok
2,176✔
2907
            || yajl_complete_parse(handle) != yajl_status_ok
2,176✔
2908
            || jlu.jlu_scan_error)
4,352✔
2909
        {
2910
            unsigned char* msg;
2911
            std::string full_msg;
80✔
2912

2913
            msg = yajl_get_error(
160✔
2914
                handle, 1, (const unsigned char*) sbr.get_data(), sbr.length());
80✔
2915
            if (msg != nullptr) {
80✔
2916
                full_msg = fmt::format(
80✔
2917
                    FMT_STRING("[offset: {}] {}\n{}"),
160✔
2918
                    ll.get_offset(),
80✔
2919
                    fmt::string_view{sbr.get_data(), sbr.length()},
80✔
2920
                    reinterpret_cast<char*>(msg));
160✔
2921
                yajl_free_error(handle, msg);
80✔
2922
            }
2923

2924
            this->jlf_attr_line.al_string.assign(full_msg.data(),
80✔
2925
                                                 full_msg.size());
2926
            this->jlf_line_values.clear();
80✔
2927
            this->jlf_attr_line.al_attrs.emplace_back(
80✔
2928
                line_range{0, -1},
×
2929
                SA_INVALID.value(jlu.jlu_scan_error
240✔
2930
                                     ? jlu.jlu_scan_error->se_message
174✔
2931
                                     : "JSON line failed to parse"));
2932
        } else {
80✔
2933
            std::vector<logline_value>::iterator lv_iter;
2,096✔
2934
            bool used_values[this->jlf_line_values.lvv_values.size()];
4,192✔
2935
            struct line_range lr;
2,096✔
2936

2937
            memset(used_values, 0, sizeof(used_values));
2,096✔
2938
            for (lv_iter = this->jlf_line_values.lvv_values.begin();
2,096✔
2939
                 lv_iter != this->jlf_line_values.lvv_values.end();
17,865✔
2940
                 ++lv_iter)
15,769✔
2941
            {
2942
                lv_iter->lv_meta.lvm_format = this;
15,769✔
2943
            }
2944

2945
            if (jlu.jlu_tid_number) {
2,096✔
2946
                this->jlf_line_values.lvv_thread_id_value
2947
                    = fmt::to_string(jlu.jlu_tid_number.value());
156✔
2948
            } else if (jlu.jlu_tid_frag) {
1,940✔
2949
                this->jlf_line_values.lvv_thread_id_value
2950
                    = jlu.jlu_tid_frag->to_string();
×
2951
            }
2952

2953
            if (this->elf_opid_field.empty()
2,096✔
2954
                && this->lf_opid_source.value_or(
1,411✔
2955
                       opid_source_t::from_description)
1,411✔
2956
                    == opid_source_t::from_description
2957
                && this->lf_opid_description_def->size() == 1)
3,507✔
2958
            {
2959
                auto found_opid_desc = false;
215✔
2960
                const auto& od = this->lf_opid_description_def->begin()->second;
215✔
2961
                for (const auto& desc : *od.od_descriptors) {
645✔
2962
                    auto desc_iter
2963
                        = this->lf_desc_captures.find(desc.od_field.pp_value);
430✔
2964
                    if (desc_iter == this->lf_desc_captures.end()) {
430✔
2965
                        continue;
382✔
2966
                    }
2967
                    found_opid_desc = true;
48✔
2968
                    jlu.jlu_opid_hasher.update(desc_iter->second);
48✔
2969
                }
2970
                if (found_opid_desc) {
215✔
2971
                    this->jlf_line_values.lvv_opid_value
2972
                        = jlu.jlu_opid_hasher.to_string();
24✔
2973
                    this->jlf_line_values.lvv_opid_provenance
2974
                        = logline_value_vector::opid_provenance::file;
24✔
2975
                }
2976
            } else if (!jlu.jlu_opid_desc_frag && !jlu.jlu_opid_frag
3,733✔
2977
                       && jlu.jlu_duration > 0us)
3,733✔
2978
            {
2979
                jlu.jlu_opid_hasher.update(line_frag);
×
2980
                this->jlf_line_values.lvv_opid_value
2981
                    = jlu.jlu_opid_hasher.to_string();
×
2982
                this->jlf_line_values.lvv_opid_provenance
2983
                    = logline_value_vector::opid_provenance::file;
×
2984
            }
2985
            if (jlu.jlu_opid_desc_frag) {
2,096✔
2986
                this->jlf_line_values.lvv_opid_value
2987
                    = jlu.jlu_opid_hasher.to_string();
29✔
2988
                this->jlf_line_values.lvv_opid_provenance
2989
                    = logline_value_vector::opid_provenance::file;
29✔
2990
            }
2991
            if (jlu.jlu_opid_frag) {
2,096✔
2992
                this->jlf_line_values.lvv_opid_value
2993
                    = jlu.jlu_opid_frag->to_string();
×
2994
                this->jlf_line_values.lvv_opid_provenance
2995
                    = logline_value_vector::opid_provenance::file;
×
2996
            }
2997

2998
            int sub_offset = this->jlf_line_format_init_count;
2,096✔
2999
            for (const auto& jfe : this->jlf_line_format) {
25,147✔
3000
                static const intern_string_t ts_field
3001
                    = intern_string::lookup("__timestamp__", -1);
23,051✔
3002
                static const intern_string_t level_field
3003
                    = intern_string::lookup("__level__");
23,153✔
3004
                size_t begin_size = this->jlf_attr_line.al_string.size();
23,051✔
3005

3006
                switch (jfe.jfe_type) {
23,051✔
3007
                    case json_log_field::CONSTANT:
3,979✔
3008
                        this->json_append_to_cache(
3,979✔
3009
                            jfe.jfe_default_value.c_str(),
3010
                            jfe.jfe_default_value.size());
3,979✔
3011
                        break;
3,979✔
3012
                    case json_log_field::VARIABLE:
19,072✔
3013
                        lv_iter = find_if(
19,072✔
3014
                            this->jlf_line_values.lvv_values.begin(),
3015
                            this->jlf_line_values.lvv_values.end(),
3016
                            logline_value_name_cmp(&jfe.jfe_value.pp_value));
3017
                        if (lv_iter != this->jlf_line_values.lvv_values.end()) {
19,072✔
3018
                            auto str = lv_iter->to_string();
7,425✔
3019
                            value_def* vd = nullptr;
7,425✔
3020

3021
                            if (lv_iter->lv_meta.lvm_values_index) {
7,425✔
3022
                                vd = this->elf_value_def_order
3023
                                         [lv_iter->lv_meta.lvm_values_index
7,425✔
3024
                                              .value()]
7,425✔
3025
                                             .get();
7,425✔
3026
                            }
3027
                            while (endswith(str, "\n")) {
7,707✔
3028
                                str.pop_back();
282✔
3029
                            }
3030
                            size_t nl_pos = str.find('\n');
7,425✔
3031

3032
                            if (!jfe.jfe_prefix.empty()) {
7,425✔
3033
                                this->json_append_to_cache(jfe.jfe_prefix);
3,545✔
3034
                            }
3035
                            lr.lr_start = this->jlf_attr_line.al_string.size();
7,425✔
3036

3037
                            if ((int) str.size() > jfe.jfe_max_width) {
7,425✔
3038
                                switch (jfe.jfe_overflow) {
232✔
3039
                                    case json_format_element::overflow_t::
173✔
3040
                                        ABBREV: {
3041
                                        size_t new_size
3042
                                            = abbreviate_str(&str[0],
173✔
3043
                                                             str.size(),
3044
                                                             jfe.jfe_max_width);
173✔
3045
                                        str.resize(new_size);
173✔
3046
                                        this->json_append(lffs, jfe, vd, str);
173✔
3047
                                        break;
173✔
3048
                                    }
3049
                                    case json_format_element::overflow_t::
53✔
3050
                                        TRUNCATE: {
3051
                                        this->json_append_to_cache(
53✔
3052
                                            str.c_str(), jfe.jfe_max_width);
53✔
3053
                                        break;
53✔
3054
                                    }
3055
                                    case json_format_element::overflow_t::
6✔
3056
                                        DOTDOT: {
3057
                                        size_t middle
6✔
3058
                                            = (jfe.jfe_max_width / 2) - 1;
6✔
3059
                                        this->json_append_to_cache(str.c_str(),
6✔
3060
                                                                   middle);
3061
                                        this->json_append_to_cache("..", 2);
6✔
3062
                                        size_t rest
6✔
3063
                                            = (jfe.jfe_max_width - middle - 2);
6✔
3064
                                        this->json_append_to_cache(
12✔
3065
                                            str.c_str() + str.size() - rest,
6✔
3066
                                            rest);
3067
                                        break;
6✔
3068
                                    }
3069
                                    case json_format_element::overflow_t::
×
3070
                                        LASTWORD: {
3071
                                        size_t new_size
3072
                                            = last_word_str(&str[0],
×
3073
                                                            str.size(),
3074
                                                            jfe.jfe_max_width);
×
3075
                                        str.resize(new_size);
×
3076
                                        this->json_append(lffs, jfe, vd, str);
×
3077
                                        break;
×
3078
                                    }
3079
                                }
3080
                            } else {
3081
                                sub_offset
3082
                                    += std::count(str.begin(), str.end(), '\n');
7,193✔
3083
                                if (vd != nullptr
7,193✔
3084
                                    && vd->vd_meta.lvm_kind
7,193✔
3085
                                        == value_kind_t::VALUE_JSON)
3086
                                {
3087
                                    auto json_al = attr_line_t();
24✔
3088
                                    json_al.append(str);
24✔
3089
                                    highlight_syntax(text_format_t::TF_JSON,
24✔
3090
                                                     json_al,
3091
                                                     std::nullopt);
3092
                                    this->jlf_attr_line.append(json_al);
24✔
3093
                                } else {
24✔
3094
                                    this->json_append(lffs, jfe, vd, str);
7,169✔
3095
                                }
3096
                            }
3097

3098
                            if (nl_pos == std::string::npos
7,425✔
3099
                                || opts.full_message)
3✔
3100
                            {
3101
                                lr.lr_end
3102
                                    = this->jlf_attr_line.al_string.size();
7,422✔
3103
                            } else {
3104
                                lr.lr_end = lr.lr_start + nl_pos;
3✔
3105
                            }
3106

3107
                            if (lv_iter->lv_meta.lvm_name
7,425✔
3108
                                == this->lf_timestamp_field)
7,425✔
3109
                            {
3110
                                this->jlf_attr_line.al_attrs.emplace_back(
1,043✔
3111
                                    lr, L_TIMESTAMP.value());
2,086✔
3112
                            } else if (lv_iter->lv_meta.lvm_name
6,382✔
3113
                                       == this->elf_body_field)
6,382✔
3114
                            {
3115
                                this->jlf_attr_line.al_attrs.emplace_back(
1,223✔
3116
                                    lr, SA_BODY.value());
2,446✔
3117
                            } else if (lv_iter->lv_meta.lvm_name
5,159✔
3118
                                       == this->elf_src_loc_field)
5,159✔
3119
                            {
3120
                                size_t digits = 0;
×
3121
                                for (auto str_iter = str.rbegin();
×
3122
                                     str_iter != str.rend();
×
3123
                                     ++str_iter)
×
3124
                                {
3125
                                    if (isdigit(*str_iter)) {
×
3126
                                        digits += 1;
×
3127
                                    } else {
3128
                                        break;
×
3129
                                    }
3130
                                }
3131
                                auto diff = str.size() - digits;
×
3132
                                auto file_lr = lr;
×
3133
                                file_lr.lr_end -= digits + 1;
×
3134
                                auto line_lr = lr;
×
3135
                                line_lr.lr_start += diff;
×
3136
                                this->jlf_attr_line.al_attrs.emplace_back(
×
3137
                                    lr, SA_SRC_LOC.value());
×
3138
                                this->jlf_attr_line.al_attrs.emplace_back(
×
3139
                                    file_lr, SA_SRC_FILE.value());
×
3140
                                this->jlf_attr_line.al_attrs.emplace_back(
×
3141
                                    line_lr, SA_SRC_LINE.value());
×
3142
                            } else if (lv_iter->lv_meta.lvm_name
5,159✔
3143
                                       == this->elf_src_file_field)
5,159✔
3144
                            {
3145
                                this->jlf_attr_line.al_attrs.emplace_back(
14✔
3146
                                    lr, SA_SRC_FILE.value());
28✔
3147
                            } else if (lv_iter->lv_meta.lvm_name
5,145✔
3148
                                       == this->elf_src_line_field)
5,145✔
3149
                            {
3150
                                this->jlf_attr_line.al_attrs.emplace_back(
14✔
3151
                                    lr, SA_SRC_LINE.value());
28✔
3152
                            } else if (lv_iter->lv_meta.lvm_name
5,131✔
3153
                                       == this->elf_thread_id_field)
5,131✔
3154
                            {
3155
                                this->jlf_attr_line.al_attrs.emplace_back(
105✔
3156
                                    lr, SA_THREAD_ID.value());
210✔
3157
                            } else if (lv_iter->lv_meta.lvm_name
5,026✔
3158
                                       == this->elf_duration_field)
5,026✔
3159
                            {
3160
                                this->jlf_attr_line.al_attrs.emplace_back(
×
3161
                                    lr, SA_DURATION.value());
×
3162
                            } else if (lv_iter->lv_meta.lvm_name
5,026✔
3163
                                       == this->elf_level_field)
5,026✔
3164
                            {
3165
                                this->jlf_attr_line.al_attrs.emplace_back(
1,113✔
3166
                                    lr, L_LEVEL.value());
2,226✔
3167
                            } else if (lv_iter->lv_meta.lvm_name
7,826✔
3168
                                           == this->elf_opid_field
3,913✔
3169
                                       && !lr.empty())
3,913✔
3170
                            {
3171
                                this->jlf_attr_line.al_attrs.emplace_back(
646✔
3172
                                    lr, L_OPID.value());
1,292✔
3173
                            }
3174
                            lv_iter->lv_origin = lr;
7,425✔
3175
                            lv_iter->lv_sub_offset = sub_offset;
7,425✔
3176
                            used_values[std::distance(
7,425✔
3177
                                this->jlf_line_values.lvv_values.begin(),
3178
                                lv_iter)] = true;
7,425✔
3179

3180
                            if (!jfe.jfe_suffix.empty()) {
7,425✔
3181
                                this->json_append_to_cache(jfe.jfe_suffix);
1,014✔
3182
                            }
3183
                        } else if (jfe.jfe_value.pp_value == ts_field) {
19,072✔
3184
                            line_range lr;
1,196✔
3185
                            ssize_t ts_len;
3186
                            char ts[64];
3187
                            exttm et;
1,196✔
3188

3189
                            ll.to_exttm(et);
1,196✔
3190
                            et.et_nsec += jlu.jlu_exttm.et_nsec % 1000;
1,196✔
3191
                            et.et_gmtoff = jlu.jlu_exttm.et_gmtoff;
1,196✔
3192
                            et.et_flags |= jlu.jlu_exttm.et_flags;
1,196✔
3193
                            if (!jfe.jfe_prefix.empty()) {
1,196✔
3194
                                this->json_append_to_cache(jfe.jfe_prefix);
4✔
3195
                            }
3196
                            if (jfe.jfe_ts_format.empty()) {
1,196✔
3197
                                ts_len = this->lf_date_time.ftime(
1,041✔
3198
                                    ts,
3199
                                    sizeof(ts),
3200
                                    this->get_timestamp_formats(),
3201
                                    et);
3202
                            } else {
3203
                                ts_len = ftime_fmt(ts,
155✔
3204
                                                   sizeof(ts),
3205
                                                   jfe.jfe_ts_format.c_str(),
3206
                                                   et);
3207
                            }
3208
                            lr.lr_start = this->jlf_attr_line.al_string.size();
1,196✔
3209
                            this->json_append_to_cache(ts, ts_len);
1,196✔
3210
                            lr.lr_end = this->jlf_attr_line.al_string.size();
1,196✔
3211
                            this->jlf_attr_line.al_attrs.emplace_back(
1,196✔
3212
                                lr, L_TIMESTAMP.value());
2,392✔
3213

3214
                            lv_iter = find_if(
1,196✔
3215
                                this->jlf_line_values.lvv_values.begin(),
3216
                                this->jlf_line_values.lvv_values.end(),
3217
                                logline_value_name_cmp(
3218
                                    &this->lf_timestamp_field));
1,196✔
3219
                            if (lv_iter
1,196✔
3220
                                != this->jlf_line_values.lvv_values.end())
1,196✔
3221
                            {
3222
                                used_values[distance(
1,196✔
3223
                                    this->jlf_line_values.lvv_values.begin(),
3224
                                    lv_iter)] = true;
1,196✔
3225
                            }
3226
                            if (!jfe.jfe_suffix.empty()) {
1,196✔
3227
                                this->json_append_to_cache(jfe.jfe_suffix);
4✔
3228
                            }
3229
                        } else if (jfe.jfe_value.pp_value == level_field
10,451✔
3230
                                   || jfe.jfe_value.pp_value
20,766✔
3231
                                       == this->elf_level_field)
10,315✔
3232
                        {
3233
                            auto level_name = ll.get_level_name();
136✔
3234
                            lr.lr_start = this->jlf_attr_line.al_string.size();
136✔
3235
                            this->json_append(lffs, jfe, nullptr, level_name);
136✔
3236
                            if (jfe.jfe_auto_width) {
136✔
3237
                                this->json_append_to_cache(
105✔
3238
                                    MAX_LEVEL_NAME_LEN - level_name.length());
105✔
3239
                            }
3240
                            lr.lr_end = this->jlf_attr_line.al_string.size();
136✔
3241
                            this->jlf_attr_line.al_attrs.emplace_back(
136✔
3242
                                lr, L_LEVEL.value());
272✔
3243
                        } else if (!jfe.jfe_default_value.empty()) {
10,315✔
3244
                            if (!jfe.jfe_prefix.empty()) {
122✔
3245
                                this->json_append_to_cache(jfe.jfe_prefix);
×
3246
                            }
3247
                            this->json_append(
122✔
3248
                                lffs, jfe, nullptr, jfe.jfe_default_value);
122✔
3249
                            if (!jfe.jfe_suffix.empty()) {
122✔
3250
                                this->json_append_to_cache(jfe.jfe_suffix);
×
3251
                            }
3252
                        }
3253

3254
                        switch (jfe.jfe_text_transform) {
19,072✔
3255
                            case json_format_element::transform_t::NONE:
18,936✔
3256
                                break;
18,936✔
3257
                            case json_format_element::transform_t::UPPERCASE:
136✔
3258
                                for (size_t cindex = begin_size; cindex
136✔
3259
                                     < this->jlf_attr_line.al_string.size();
1,104✔
3260
                                     cindex++)
3261
                                {
3262
                                    this->jlf_attr_line.al_string[cindex]
1,936✔
3263
                                        = toupper(this->jlf_attr_line
968✔
3264
                                                      .al_string[cindex]);
968✔
3265
                                }
3266
                                break;
136✔
3267
                            case json_format_element::transform_t::LOWERCASE:
×
3268
                                for (size_t cindex = begin_size; cindex
×
3269
                                     < this->jlf_attr_line.al_string.size();
×
3270
                                     cindex++)
3271
                                {
3272
                                    this->jlf_attr_line.al_string[cindex]
×
3273
                                        = tolower(this->jlf_attr_line
×
3274
                                                      .al_string[cindex]);
×
3275
                                }
3276
                                break;
×
3277
                            case json_format_element::transform_t::CAPITALIZE:
×
3278
                                for (size_t cindex = begin_size;
×
3279
                                     cindex < begin_size + 1;
×
3280
                                     cindex++)
3281
                                {
3282
                                    this->jlf_attr_line.al_string[cindex]
×
3283
                                        = toupper(this->jlf_attr_line
×
3284
                                                      .al_string[cindex]);
×
3285
                                }
3286
                                for (size_t cindex = begin_size + 1; cindex
×
3287
                                     < this->jlf_attr_line.al_string.size();
×
3288
                                     cindex++)
3289
                                {
3290
                                    this->jlf_attr_line.al_string[cindex]
×
3291
                                        = tolower(this->jlf_attr_line
×
3292
                                                      .al_string[cindex]);
×
3293
                                }
3294
                                break;
×
3295
                        }
3296
                        break;
19,072✔
3297
                }
3298
            }
3299
            this->json_append_to_cache("\n", 1);
2,096✔
3300
            sub_offset += 1;
2,096✔
3301

3302
            for (size_t lpc = 0; lpc < this->jlf_line_values.lvv_values.size();
17,865✔
3303
                 lpc++)
3304
            {
3305
                static const intern_string_t body_name
3306
                    = intern_string::lookup("body", -1);
15,769✔
3307
                auto& lv = this->jlf_line_values.lvv_values[lpc];
15,769✔
3308

3309
                if (lv.lv_meta.is_hidden() || used_values[lpc]
24,827✔
3310
                    || body_name == lv.lv_meta.lvm_name)
24,827✔
3311
                {
3312
                    continue;
14,374✔
3313
                }
3314

3315
                auto str = lv.to_string();
1,395✔
3316
                while (endswith(str, "\n")) {
1,395✔
3317
                    str.pop_back();
×
3318
                }
3319

3320
                lv.lv_sub_offset = sub_offset;
1,395✔
3321
                lv.lv_origin.lr_start = this->jlf_attr_line.al_string.size() + 2
1,395✔
3322
                    + lv.lv_meta.lvm_name.size() + 2;
1,395✔
3323
                auto frag = string_fragment::from_str(str);
1,395✔
3324
                while (true) {
3325
                    auto utf_scan_res = is_utf8(frag, '\n');
1,401✔
3326

3327
                    this->json_append_to_cache("  ", 2);
1,401✔
3328
                    this->json_append_to_cache(
1,401✔
3329
                        lv.lv_meta.lvm_name.to_string_fragment());
1,401✔
3330
                    this->json_append_to_cache(": ", 2);
1,401✔
3331
                    lr.lr_start = this->jlf_attr_line.al_string.size();
1,401✔
3332
                    this->json_append_to_cache(utf_scan_res.usr_valid_frag);
1,401✔
3333
                    lr.lr_end = this->jlf_attr_line.al_string.size();
1,401✔
3334
                    if (lv.lv_meta.lvm_name == this->elf_body_field) {
1,401✔
3335
                        this->jlf_attr_line.al_attrs.emplace_back(
×
3336
                            lr, SA_BODY.value());
×
3337
                    } else {
3338
                        this->jlf_attr_line.al_attrs.emplace_back(
1,401✔
3339
                            lr, SA_EXTRA_CONTENT.value());
2,802✔
3340
                    }
3341
                    this->json_append_to_cache("\n", 1);
1,401✔
3342
                    sub_offset += 1;
1,401✔
3343
                    if (utf_scan_res.usr_remaining) {
1,401✔
3344
                        frag = utf_scan_res.usr_remaining.value();
6✔
3345
                    } else {
3346
                        break;
1,395✔
3347
                    }
3348
                }
6✔
3349
                lv.lv_origin.lr_end = this->jlf_attr_line.al_string.size() - 1;
1,395✔
3350
                if (lv.lv_meta.lvm_name == this->elf_opid_field
1,395✔
3351
                    && !lv.lv_origin.empty())
1,395✔
3352
                {
3353
                    this->jlf_attr_line.al_attrs.emplace_back(lv.lv_origin,
×
3354
                                                              L_OPID.value());
×
3355
                }
3356
            }
1,395✔
3357
        }
2,096✔
3358

3359
        this->jlf_line_offsets.push_back(0);
2,176✔
3360
        for (size_t lpc = 0; lpc < this->jlf_attr_line.al_string.size(); lpc++)
260,563✔
3361
        {
3362
            if (this->jlf_attr_line.al_string[lpc] == '\n') {
258,387✔
3363
                this->jlf_line_offsets.push_back(lpc + 1);
4,596✔
3364
            }
3365
        }
3366
        this->jlf_line_offsets.push_back(this->jlf_attr_line.al_string.size());
2,176✔
3367
        this->jlf_cached_offset = ll.get_offset();
2,176✔
3368
        this->jlf_cached_opts = opts;
2,176✔
3369
    }
2,269✔
3370

3371
    off_t this_off = 0, next_off = 0;
4,562✔
3372

3373
    if (!this->jlf_line_offsets.empty()
4,562✔
3374
        && ll.get_sub_offset() < this->jlf_line_offsets.size())
4,562✔
3375
    {
3376
        require(ll.get_sub_offset() < this->jlf_line_offsets.size());
4,562✔
3377

3378
        this_off = this->jlf_line_offsets[ll.get_sub_offset()];
4,562✔
3379
        if ((ll.get_sub_offset() + 1) < (int) this->jlf_line_offsets.size()) {
4,562✔
3380
            next_off = this->jlf_line_offsets[ll.get_sub_offset() + 1];
4,562✔
3381
        } else {
3382
            next_off = this->jlf_attr_line.al_string.size();
×
3383
        }
3384
        if (next_off > 0 && this->jlf_attr_line.al_string[next_off - 1] == '\n'
4,562✔
3385
            && this_off != next_off)
9,124✔
3386
        {
3387
            next_off -= 1;
4,562✔
3388
        }
3389
    }
3390

3391
    if (opts.full_message) {
4,562✔
3392
        sbr.share(this->jlf_share_manager,
664✔
3393
                  this->jlf_attr_line.al_string.data(),
332✔
3394
                  this->jlf_attr_line.al_string.size());
3395
    } else {
3396
        sbr.share(this->jlf_share_manager,
8,460✔
3397
                  this->jlf_attr_line.al_string.data() + this_off,
4,230✔
3398
                  next_off - this_off);
4,230✔
3399
    }
3400
    sbr.get_metadata().m_valid_utf = ll.is_valid_utf();
4,562✔
3401
    sbr.get_metadata().m_has_ansi = ll.has_ansi();
4,562✔
3402
    this->jlf_cached_sub_range.lr_start = this_off;
4,562✔
3403
    this->jlf_cached_sub_range.lr_end = next_off;
4,562✔
3404
    this->jlf_line_values.lvv_sbr = sbr.clone();
4,562✔
3405
}
3406

3407
struct compiled_header_expr {
3408
    auto_mem<sqlite3_stmt> che_stmt{sqlite3_finalize};
3409
    bool che_enabled{true};
3410
};
3411

3412
struct format_header_expressions : public lnav_config_listener {
3413
    format_header_expressions() : lnav_config_listener(__FILE__) {}
1,207✔
3414

3415
    auto_sqlite3 e_db;
3416
    std::map<intern_string_t, std::map<std::string, compiled_header_expr>>
3417
        e_header_exprs;
3418
};
3419

3420
using safe_format_header_expressions = safe::Safe<format_header_expressions>;
3421

3422
static safe_format_header_expressions format_header_exprs;
3423

3424
std::optional<external_file_format>
3425
detect_mime_type(const std::filesystem::path& filename)
648✔
3426
{
3427
    uint8_t buffer[1024];
3428
    size_t buffer_size = 0;
648✔
3429

3430
    {
3431
        auto_fd fd;
648✔
3432

3433
        if ((fd = lnav::filesystem::openp(filename, O_RDONLY)) == -1) {
648✔
3434
            return std::nullopt;
×
3435
        }
3436

3437
        ssize_t rc;
3438

3439
        if ((rc = read(fd, buffer, sizeof(buffer))) == -1) {
648✔
3440
            return std::nullopt;
×
3441
        }
3442
        buffer_size = rc;
648✔
3443
    }
648✔
3444

3445
    auto hexbuf = auto_buffer::alloc(buffer_size * 2);
648✔
3446

3447
    for (size_t lpc = 0; lpc < buffer_size; lpc++) {
343,733✔
3448
        fmt::format_to(
343,085✔
3449
            std::back_inserter(hexbuf), FMT_STRING("{:02x}"), buffer[lpc]);
1,372,340✔
3450
    }
3451

3452
    safe::WriteAccess<safe_format_header_expressions> in(format_header_exprs);
648✔
3453

3454
    for (const auto& format : log_format::get_root_formats()) {
50,484✔
3455
        auto elf = std::dynamic_pointer_cast<external_log_format>(format);
49,836✔
3456
        if (elf == nullptr) {
49,836✔
3457
            continue;
3,240✔
3458
        }
3459

3460
        if (elf->elf_converter.c_header.h_exprs.he_exprs.empty()) {
46,596✔
3461
            continue;
45,300✔
3462
        }
3463

3464
        if (buffer_size < elf->elf_converter.c_header.h_size) {
1,296✔
3465
            log_debug(
107✔
3466
                "%s: file content too small (%zu) for header detection: %s",
3467
                filename.c_str(),
3468
                buffer_size,
3469
                elf->get_name().get());
3470
            continue;
107✔
3471
        }
3472
        for (const auto& hpair : elf->elf_converter.c_header.h_exprs.he_exprs) {
4,259✔
3473
            auto& he = in->e_header_exprs[elf->get_name()][hpair.first];
3,070✔
3474

3475
            if (!he.che_enabled) {
3,070✔
3476
                continue;
×
3477
            }
3478

3479
            auto* stmt = he.che_stmt.in();
3,070✔
3480

3481
            if (stmt == nullptr) {
3,070✔
3482
                continue;
×
3483
            }
3484
            sqlite3_reset(stmt);
3,070✔
3485
            auto count = sqlite3_bind_parameter_count(stmt);
3,070✔
3486
            for (int lpc = 0; lpc < count; lpc++) {
6,140✔
3487
                const auto* name = sqlite3_bind_parameter_name(stmt, lpc + 1);
3,070✔
3488

3489
                if (name[0] == '$') {
3,070✔
3490
                    const char* env_value;
3491

3492
                    if ((env_value = getenv(&name[1])) != nullptr) {
×
3493
                        sqlite3_bind_text(
×
3494
                            stmt, lpc + 1, env_value, -1, SQLITE_STATIC);
3495
                    }
3496
                    continue;
×
3497
                }
3498
                if (strcmp(name, ":header") == 0) {
3,070✔
3499
                    sqlite3_bind_text(stmt,
3,070✔
3500
                                      lpc + 1,
3501
                                      hexbuf.in(),
3,070✔
3502
                                      hexbuf.size(),
3,070✔
3503
                                      SQLITE_STATIC);
3504
                    continue;
3,070✔
3505
                }
3506
                if (strcmp(name, ":filepath") == 0) {
×
3507
                    sqlite3_bind_text(
×
3508
                        stmt, lpc + 1, filename.c_str(), -1, SQLITE_STATIC);
3509
                    continue;
×
3510
                }
3511
            }
3512

3513
            auto step_res = sqlite3_step(stmt);
3,070✔
3514

3515
            switch (step_res) {
3,070✔
3516
                case SQLITE_OK:
3,070✔
3517
                case SQLITE_DONE:
3518
                    continue;
3,070✔
3519
                case SQLITE_ROW:
×
3520
                    break;
×
3521
                default: {
×
3522
                    log_error(
×
3523
                        "failed to execute file-format header expression: "
3524
                        "%s:%s -- %s",
3525
                        elf->get_name().get(),
3526
                        hpair.first.c_str(),
3527
                        sqlite3_errmsg(in->e_db));
3528
                    he.che_enabled = false;
×
3529
                    continue;
×
3530
                }
3531
            }
3532

3533
            log_info("detected format for: %s -- %s (header-expr: %s)",
×
3534
                     filename.c_str(),
3535
                     elf->get_name().get(),
3536
                     hpair.first.c_str());
3537
            return external_file_format{
×
3538
                elf->get_name().to_string(),
×
3539
                elf->elf_converter.c_command.pp_value,
×
3540
                elf->elf_converter.c_command.pp_location.sl_source.to_string(),
×
3541
            };
3542
        }
3543
    }
49,836✔
3544

3545
    return std::nullopt;
648✔
3546
}
648✔
3547

3548
log_format::scan_result_t
3549
log_format::test_line(sample_t& sample,
×
3550
                      std::vector<lnav::console::user_message>& msgs)
3551
{
3552
    return scan_no_match{};
×
3553
}
3554

3555
log_format::scan_result_t
3556
external_log_format::test_line(sample_t& sample,
198,986✔
3557
                               std::vector<lnav::console::user_message>& msgs)
3558
{
3559
    auto lines
3560
        = string_fragment::from_str(sample.s_line.pp_value).split_lines();
198,986✔
3561

3562
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
198,986✔
3563
        auto alloc = ArenaAlloc::Alloc<char>{};
3,146✔
3564
        pattern_locks pats;
3,146✔
3565
        auto sbc = scan_batch_context{
3,146✔
3566
            alloc,
3567
            pats,
3568
        };
3,146✔
3569
        sbc.sbc_value_stats.resize(this->elf_value_defs.size());
3,146✔
3570
        std::vector<logline> dst;
3,146✔
3571
        auto li = line_info{
3,146✔
3572
            {0, lines[0].length()},
3,146✔
3573
        };
3,146✔
3574
        shared_buffer sb;
3,146✔
3575
        shared_buffer_ref sbr;
3,146✔
3576
        sbr.share(sb, lines[0].data(), (size_t) lines[0].length());
3,146✔
3577

3578
        return this->scan_json(dst, li, sbr, sbc);
3,146✔
3579
    }
3,146✔
3580

3581
    scan_result_t retval = scan_no_match{"no patterns matched"};
195,840✔
3582
    auto found = false;
195,840✔
3583

3584
    for (auto pat_iter = this->elf_pattern_order.begin();
195,840✔
3585
         pat_iter != this->elf_pattern_order.end();
1,455,356✔
3586
         ++pat_iter)
1,259,516✔
3587
    {
3588
        auto& pat = *(*pat_iter);
1,259,516✔
3589

3590
        if (!pat.p_pcre.pp_value) {
1,259,516✔
3591
            continue;
1,063,678✔
3592
        }
3593

3594
        auto md = pat.p_pcre.pp_value->create_match_data();
1,259,516✔
3595
        auto match_res = pat.p_pcre.pp_value->capture_from(lines[0])
1,259,516✔
3596
                             .into(md)
1,259,516✔
3597
                             .matches(PCRE2_NO_UTF_CHECK)
2,519,032✔
3598
                             .ignore_error();
1,259,516✔
3599
        if (!match_res) {
1,259,516✔
3600
            continue;
1,063,678✔
3601
        }
3602
        retval = scan_match{1000};
195,838✔
3603
        found = true;
195,838✔
3604

3605
        sample.s_matched_regexes.insert(pat.p_name.to_string());
195,838✔
3606

3607
        const auto ts_cap = md[pat.p_timestamp_field_index];
195,838✔
3608
        const auto level_cap = md[pat.p_level_field_index];
195,838✔
3609
        const char* const* custom_formats = this->get_timestamp_formats();
195,838✔
3610
        date_time_scanner dts;
195,838✔
3611
        timeval tv;
3612
        exttm tm;
195,838✔
3613

3614
        if (ts_cap && ts_cap->sf_begin == 0) {
195,838✔
3615
            pat.p_timestamp_end = ts_cap->sf_end;
121,549✔
3616
        }
3617
        const char* dts_scan_res = nullptr;
195,838✔
3618

3619
        if (ts_cap) {
195,838✔
3620
            dts_scan_res = dts.scan(
195,836✔
3621
                ts_cap->data(), ts_cap->length(), custom_formats, &tm, tv);
195,836✔
3622
        }
3623
        if (dts_scan_res != nullptr) {
195,838✔
3624
            if (dts_scan_res != ts_cap->data() + ts_cap->length()) {
195,835✔
3625
                auto match_len = dts_scan_res - ts_cap->data();
×
3626
                auto notes = attr_line_t("the used timestamp format: ");
×
3627
                if (custom_formats == nullptr) {
×
3628
                    notes.append(PTIMEC_FORMATS[dts.dts_fmt_lock].pf_fmt);
×
3629
                } else {
3630
                    notes.append(custom_formats[dts.dts_fmt_lock]);
×
3631
                }
3632
                notes.append("\n  ")
×
3633
                    .append(ts_cap.value())
×
3634
                    .append("\n")
×
3635
                    .append(2 + match_len, ' ')
×
3636
                    .append("^ matched up to here"_snippet_border);
×
3637
                auto um = lnav::console::user_message::warning(
×
3638
                              attr_line_t("timestamp was not fully matched: ")
×
3639
                                  .append_quoted(ts_cap.value()))
×
3640
                              .with_snippet(sample.s_line.to_snippet())
×
3641
                              .with_note(notes)
×
3642
                              .move();
×
3643

3644
                msgs.emplace_back(um);
×
3645
            }
3646
        } else if (!ts_cap) {
3✔
3647
            msgs.emplace_back(
2✔
3648
                lnav::console::user_message::error(
×
3649
                    attr_line_t("invalid sample log message: ")
4✔
3650
                        .append(lnav::to_json(sample.s_line.pp_value)))
4✔
3651
                    .with_reason(attr_line_t("timestamp was not captured"))
4✔
3652
                    .with_snippet(sample.s_line.to_snippet())
4✔
3653
                    .with_help(attr_line_t(
4✔
3654
                        "A timestamp needs to be captured in order for a "
3655
                        "line to be recognized as a log message")));
3656
        } else {
3657
            attr_line_t notes;
1✔
3658

3659
            if (custom_formats == nullptr) {
1✔
3660
                notes.append("the following built-in formats were tried:");
×
3661
                for (int lpc = 0; PTIMEC_FORMATS[lpc].pf_fmt != nullptr; lpc++)
×
3662
                {
3663
                    off_t off = 0;
×
3664

3665
                    PTIMEC_FORMATS[lpc].pf_func(
×
3666
                        &tm, ts_cap->data(), off, ts_cap->length());
×
3667
                    notes.append("\n  ")
×
3668
                        .append(ts_cap.value())
×
3669
                        .append("\n")
×
3670
                        .append(2 + off, ' ')
×
3671
                        .append("^ "_snippet_border)
×
3672
                        .append_quoted(
×
3673
                            lnav::roles::symbol(PTIMEC_FORMATS[lpc].pf_fmt))
×
3674
                        .append(" matched up to here"_snippet_border);
×
3675
                }
3676
            } else {
3677
                notes.append("the following custom formats were tried:");
1✔
3678
                for (int lpc = 0; custom_formats[lpc] != nullptr; lpc++) {
2✔
3679
                    off_t off = 0;
1✔
3680

3681
                    ptime_fmt(custom_formats[lpc],
1✔
3682
                              &tm,
3683
                              ts_cap->data(),
3684
                              off,
3685
                              ts_cap->length());
1✔
3686
                    notes.append("\n  ")
1✔
3687
                        .append(ts_cap.value())
1✔
3688
                        .append("\n")
1✔
3689
                        .append(2 + off, ' ')
1✔
3690
                        .append("^ "_snippet_border)
1✔
3691
                        .append_quoted(lnav::roles::symbol(custom_formats[lpc]))
2✔
3692
                        .append(" matched up to here"_snippet_border);
1✔
3693
                }
3694
            }
3695

3696
            msgs.emplace_back(
1✔
3697
                lnav::console::user_message::error(
×
3698
                    attr_line_t("invalid sample log message: ")
1✔
3699
                        .append(lnav::to_json(sample.s_line.pp_value)))
2✔
3700
                    .with_reason(attr_line_t("unrecognized timestamp -- ")
2✔
3701
                                     .append(ts_cap.value()))
1✔
3702
                    .with_snippet(sample.s_line.to_snippet())
2✔
3703
                    .with_note(notes)
1✔
3704
                    .with_help(attr_line_t("If the timestamp format is not "
2✔
3705
                                           "supported by default, you can "
3706
                                           "add a custom format with the ")
3707
                                   .append_quoted("timestamp-format"_symbol)
1✔
3708
                                   .append(" property")));
1✔
3709
        }
1✔
3710

3711
        auto level = this->convert_level(
195,838✔
3712
            level_cap.value_or(string_fragment::invalid()), nullptr);
195,838✔
3713

3714
        if (sample.s_level != LEVEL_UNKNOWN && sample.s_level != level) {
195,838✔
3715
            attr_line_t note_al;
1✔
3716

3717
            note_al.append("matched regex = ")
1✔
3718
                .append(lnav::roles::symbol(pat.p_name.to_string()))
2✔
3719
                .append("\n")
1✔
3720
                .append("captured level = ")
1✔
3721
                .append_quoted(level_cap->to_string());
1✔
3722
            if (level_cap && !this->elf_level_patterns.empty()) {
1✔
3723
                thread_local auto md = lnav::pcre2pp::match_data::unitialized();
1✔
3724

3725
                note_al.append("\nlevel regular expression match results:");
1✔
3726
                for (const auto& level_pattern : this->elf_level_patterns) {
3✔
3727
                    attr_line_t regex_al
3728
                        = level_pattern.second.lp_pcre.pp_value->get_pattern();
2✔
3729
                    lnav::snippets::regex_highlighter(
2✔
3730
                        regex_al, -1, line_range{0, (int) regex_al.length()});
2✔
3731
                    note_al.append("\n  ")
2✔
3732
                        .append(lnav::roles::symbol(
4✔
3733
                            level_pattern.second.lp_pcre.pp_path.to_string()))
4✔
3734
                        .append(" = ")
2✔
3735
                        .append(regex_al)
2✔
3736
                        .append("\n    ");
2✔
3737
                    auto match_res = level_pattern.second.lp_pcre.pp_value
2✔
3738
                                         ->capture_from(level_cap.value())
2✔
3739
                                         .into(md)
2✔
3740
                                         .matches(PCRE2_NO_UTF_CHECK)
4✔
3741
                                         .ignore_error();
2✔
3742
                    if (!match_res) {
2✔
3743
                        note_al.append(lnav::roles::warning("no match"));
1✔
3744
                        continue;
1✔
3745
                    }
3746

3747
                    note_al.append(level_cap.value())
1✔
3748
                        .append("\n    ")
1✔
3749
                        .append(md.leading().length(), ' ')
1✔
3750
                        .append("^"_snippet_border);
1✔
3751
                    if (match_res->f_all.length() > 2) {
1✔
3752
                        note_al.append(lnav::roles::snippet_border(
1✔
3753
                            std::string(match_res->f_all.length() - 2, '-')));
3✔
3754
                    }
3755
                    if (match_res->f_all.length() > 1) {
1✔
3756
                        note_al.append("^"_snippet_border);
1✔
3757
                    }
3758
                }
2✔
3759
            }
3760
            auto um
3761
                = lnav::console::user_message::error(
×
3762
                      attr_line_t("invalid sample log message: ")
1✔
3763
                          .append(lnav::to_json(sample.s_line.pp_value)))
2✔
3764
                      .with_reason(attr_line_t()
2✔
3765
                                       .append_quoted(lnav::roles::symbol(
2✔
3766
                                           level_names[level]))
1✔
3767
                                       .append(" does not match the expected "
1✔
3768
                                               "level of ")
3769
                                       .append_quoted(lnav::roles::symbol(
2✔
3770
                                           level_names[sample.s_level])))
1✔
3771
                      .with_snippet(sample.s_line.to_snippet())
2✔
3772
                      .with_note(note_al)
1✔
3773
                      .move();
1✔
3774
            if (!this->elf_level_patterns.empty()) {
1✔
3775
                um.with_help(
1✔
3776
                    attr_line_t("Level regexes are not anchored to the "
2✔
3777
                                "start/end of the string.  Prepend ")
3778
                        .append_quoted("^"_symbol)
1✔
3779
                        .append(" to the expression to match from the "
1✔
3780
                                "start of the string and append ")
3781
                        .append_quoted("$"_symbol)
1✔
3782
                        .append(" to match up to the end of the string."));
1✔
3783
            }
3784
            msgs.emplace_back(um);
1✔
3785
        }
1✔
3786

3787
        {
3788
            auto full_match_res
3789
                = pat.p_pcre.pp_value->capture_from(sample.s_line.pp_value)
195,838✔
3790
                      .into(md)
195,838✔
3791
                      .matches()
391,676✔
3792
                      .ignore_error();
195,838✔
3793
            if (!full_match_res) {
195,838✔
3794
                attr_line_t regex_al = pat.p_pcre.pp_value->get_pattern();
1✔
3795
                lnav::snippets::regex_highlighter(
1✔
3796
                    regex_al, -1, line_range{0, (int) regex_al.length()});
1✔
3797
                msgs.emplace_back(
1✔
3798
                    lnav::console::user_message::error(
×
3799
                        attr_line_t("invalid pattern: ")
1✔
3800
                            .append_quoted(
1✔
3801
                                lnav::roles::symbol(pat.p_name.to_string())))
2✔
3802
                        .with_reason("pattern does not match entire "
2✔
3803
                                     "multiline sample message")
3804
                        .with_snippet(sample.s_line.to_snippet())
2✔
3805
                        .with_note(attr_line_t()
2✔
3806
                                       .append(lnav::roles::symbol(
1✔
3807
                                           pat.p_name.to_string()))
2✔
3808
                                       .append(" = ")
1✔
3809
                                       .append(regex_al))
1✔
3810
                        .with_help(
3811
                            attr_line_t("use ").append_quoted(".*").append(
2✔
3812
                                " to match new-lines")));
3813
            } else if (static_cast<size_t>(full_match_res->f_all.length())
195,838✔
3814
                       != sample.s_line.pp_value.length())
195,837✔
3815
            {
3816
                attr_line_t regex_al = pat.p_pcre.pp_value->get_pattern();
1✔
3817
                lnav::snippets::regex_highlighter(
1✔
3818
                    regex_al, -1, line_range{0, (int) regex_al.length()});
1✔
3819
                auto match_length
3820
                    = static_cast<size_t>(full_match_res->f_all.length());
1✔
3821
                attr_line_t sample_al = sample.s_line.pp_value;
1✔
3822
                sample_al.append("\n")
1✔
3823
                    .append(match_length, ' ')
1✔
3824
                    .append("^ matched up to here"_error)
1✔
3825
                    .with_attr_for_all(VC_ROLE.value(role_t::VCR_QUOTED_CODE));
1✔
3826
                auto sample_snippet = lnav::console::snippet::from(
3827
                    sample.s_line.pp_location, sample_al);
1✔
3828
                msgs.emplace_back(
1✔
3829
                    lnav::console::user_message::error(
×
3830
                        attr_line_t("invalid pattern: ")
1✔
3831
                            .append_quoted(
1✔
3832
                                lnav::roles::symbol(pat.p_name.to_string())))
2✔
3833
                        .with_reason("pattern does not match entire "
2✔
3834
                                     "message")
3835
                        .with_snippet(sample_snippet)
1✔
3836
                        .with_note(attr_line_t()
3✔
3837
                                       .append(lnav::roles::symbol(
2✔
3838
                                           pat.p_name.to_string()))
2✔
3839
                                       .append(" = ")
1✔
3840
                                       .append(regex_al))
1✔
3841
                        .with_help("update the regular expression to fully "
3842
                                   "capture the sample message"));
3843
            }
1✔
3844
        }
3845
    }
1,259,516✔
3846

3847
    if (!found && !this->elf_pattern_order.empty()) {
195,840✔
3848
        std::vector<std::pair<ssize_t, intern_string_t>> partial_indexes;
2✔
3849
        attr_line_t notes;
2✔
3850
        size_t max_name_width = 0;
2✔
3851

3852
        for (const auto& pat_iter : this->elf_pattern_order) {
10✔
3853
            auto& pat = *pat_iter;
8✔
3854

3855
            if (!pat.p_pcre.pp_value) {
8✔
3856
                continue;
×
3857
            }
3858

3859
            partial_indexes.emplace_back(
8✔
3860
                pat.p_pcre.pp_value->match_partial(lines[0]), pat.p_name);
8✔
3861
            max_name_width = std::max(max_name_width, pat.p_name.size());
8✔
3862
        }
3863
        for (const auto& line_frag : lines) {
4✔
3864
            auto src_line = attr_line_t(line_frag.to_string());
2✔
3865
            if (!line_frag.endswith("\n")) {
2✔
3866
                src_line.append("\n");
2✔
3867
            }
3868
            src_line.with_attr_for_all(VC_ROLE.value(role_t::VCR_QUOTED_CODE));
2✔
3869
            notes.append("   ").append(src_line);
2✔
3870
            for (auto& part_pair : partial_indexes) {
10✔
3871
                if (part_pair.first >= 0
16✔
3872
                    && part_pair.first < line_frag.length())
8✔
3873
                {
3874
                    notes.append("   ")
8✔
3875
                        .append(part_pair.first, ' ')
8✔
3876
                        .append("^ "_snippet_border)
8✔
3877
                        .append(
8✔
3878
                            lnav::roles::symbol(part_pair.second.to_string()))
16✔
3879
                        .append(" matched up to here"_snippet_border)
8✔
3880
                        .append("\n");
8✔
3881
                }
3882
                part_pair.first -= line_frag.length();
8✔
3883
            }
3884
        }
2✔
3885
        notes.add_header(
2✔
3886
            "the following shows how each pattern matched this sample:\n");
3887

3888
        attr_line_t regex_note;
2✔
3889
        for (const auto& pat_iter : this->elf_pattern_order) {
10✔
3890
            if (!pat_iter->p_pcre.pp_value) {
8✔
3891
                regex_note
3892
                    .append(lnav::roles::symbol(fmt::format(
×
3893
                        FMT_STRING("{:{}}"), pat_iter->p_name, max_name_width)))
×
3894
                    .append(" is invalid");
×
3895
                continue;
×
3896
            }
3897

3898
            attr_line_t regex_al = pat_iter->p_pcre.pp_value->get_pattern();
8✔
3899
            lnav::snippets::regex_highlighter(
8✔
3900
                regex_al, -1, line_range{0, (int) regex_al.length()});
8✔
3901

3902
            regex_note
3903
                .append(lnav::roles::symbol(fmt::format(
16✔
3904
                    FMT_STRING("{:{}}"), pat_iter->p_name, max_name_width)))
24✔
3905
                .append(" = ")
8✔
3906
                .append_quoted(regex_al)
16✔
3907
                .append("\n");
8✔
3908
        }
8✔
3909

3910
        msgs.emplace_back(
2✔
3911
            lnav::console::user_message::error(
×
3912
                attr_line_t("invalid sample log message: ")
2✔
3913
                    .append(lnav::to_json(sample.s_line.pp_value)))
4✔
3914
                .with_reason("sample does not match any patterns")
4✔
3915
                .with_snippet(sample.s_line.to_snippet())
4✔
3916
                .with_note(notes.rtrim())
4✔
3917
                .with_note(regex_note));
3918
    }
2✔
3919

3920
    return retval;
195,840✔
3921
}
198,986✔
3922

3923
void
3924
external_log_format::build(std::vector<lnav::console::user_message>& errors)
57,016✔
3925
{
3926
    auto& vc = view_colors::singleton();
57,016✔
3927

3928
    if (!this->lf_timestamp_field.empty()) {
57,016✔
3929
        auto& vd = this->elf_value_defs[this->lf_timestamp_field];
57,016✔
3930
        if (vd.get() == nullptr) {
57,016✔
3931
            vd = std::make_shared<value_def>(
41,982✔
3932
                this->lf_timestamp_field,
41,982✔
3933
                value_kind_t::VALUE_TEXT,
×
3934
                logline_value_meta::internal_column{},
×
3935
                this);
41,982✔
3936
            if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
41,982✔
3937
                this->elf_value_def_order.emplace_back(vd);
7,576✔
3938
            }
3939
        }
3940
        vd->vd_meta.lvm_name = this->lf_timestamp_field;
57,016✔
3941
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
57,016✔
3942
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
57,016✔
3943
        vd->vd_internal = true;
57,016✔
3944

3945
        this->elf_value_defs[LOG_TIME_STR] = vd;
57,016✔
3946
    }
3947

3948
    if (!this->lf_subsecond_field.empty()) {
57,016✔
3949
        if (!this->lf_subsecond_unit.has_value()) {
101✔
3950
            errors.emplace_back(
1✔
3951
                lnav::console::user_message::error(
×
3952
                    attr_line_t()
2✔
3953
                        .append_quoted(
1✔
3954
                            lnav::roles::symbol(this->elf_name.to_string()))
2✔
3955
                        .append(" is not a valid log format"))
1✔
3956
                    .with_reason(attr_line_t()
2✔
3957
                                     .append_quoted("subsecond-units"_symbol)
1✔
3958
                                     .append(" must be set when ")
1✔
3959
                                     .append_quoted("subsecond-field"_symbol)
1✔
3960
                                     .append(" is used"))
1✔
3961
                    .with_snippets(this->get_snippets()));
2✔
3962
        } else {
3963
            auto& vd = this->elf_value_defs[this->lf_subsecond_field];
100✔
3964
            if (vd.get() == nullptr) {
100✔
3965
                vd = std::make_shared<value_def>(
100✔
3966
                    this->lf_subsecond_field,
100✔
3967
                    value_kind_t::VALUE_INTEGER,
×
3968
                    logline_value_meta::internal_column{},
×
3969
                    this);
100✔
3970
                if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
100✔
3971
                    this->elf_value_def_order.emplace_back(vd);
100✔
3972
                }
3973
            }
3974
            vd->vd_meta.lvm_name = this->lf_subsecond_field;
100✔
3975
            vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
100✔
3976
            vd->vd_meta.lvm_hidden = true;
100✔
3977
            vd->vd_internal = true;
100✔
3978
        }
3979
    }
3980

3981
    if (startswith(this->elf_level_field.get(), "/")) {
57,016✔
3982
        this->elf_level_field
3983
            = intern_string::lookup(this->elf_level_field.get() + 1);
200✔
3984
    }
3985
    if (!this->elf_level_field.empty()) {
57,016✔
3986
        auto level_iter = this->elf_value_defs.find(this->elf_level_field);
57,016✔
3987
        if (level_iter == this->elf_value_defs.end()) {
57,016✔
3988
            auto& vd = this->elf_value_defs[this->elf_level_field];
26,947✔
3989
            vd = std::make_shared<value_def>(
26,947✔
3990
                this->elf_level_field,
26,947✔
3991
                value_kind_t::VALUE_TEXT,
×
3992
                logline_value_meta::internal_column{},
×
3993
                this);
26,947✔
3994
            if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
26,947✔
3995
                this->elf_value_def_order.emplace_back(vd);
2,760✔
3996
            }
3997
            vd->vd_meta.lvm_name = this->elf_level_field;
26,947✔
3998
            vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
26,947✔
3999
            vd->vd_internal = true;
26,947✔
4000

4001
            if (this->elf_level_field != this->elf_body_field) {
26,947✔
4002
                this->elf_value_defs[LOG_LEVEL_STR] = vd;
26,061✔
4003
            }
4004
        } else {
4005
            if (level_iter->second->vd_meta.lvm_kind
30,069✔
4006
                != value_kind_t::VALUE_TEXT)
30,069✔
4007
            {
4008
                this->lf_level_hideable = false;
5,602✔
4009
            }
4010
            this->elf_value_defs[LOG_LEVEL_STR] = level_iter->second;
30,069✔
4011
        }
4012
    }
4013

4014
    auto opid_field_iter = this->elf_value_defs.find(LOG_OPID_STR);
57,016✔
4015
    if (opid_field_iter == this->elf_value_defs.end()) {
57,016✔
4016
        auto vd
4017
            = std::make_shared<value_def>(this->elf_opid_field,
57,016✔
4018
                                          value_kind_t::VALUE_TEXT,
×
4019
                                          logline_value_meta::internal_column{},
×
4020
                                          this);
57,016✔
4021
        if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
57,016✔
4022
            this->elf_value_def_order.emplace_back(vd);
11,606✔
4023
        }
4024
        vd->vd_meta.lvm_name = LOG_OPID_STR;
57,016✔
4025
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
57,016✔
4026
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
57,016✔
4027
        vd->vd_internal = true;
57,016✔
4028

4029
        this->elf_value_defs[LOG_OPID_STR] = vd;
57,016✔
4030
    }
57,016✔
4031

4032
    if (!this->elf_body_field.empty()) {
57,016✔
4033
        auto& vd = this->elf_value_defs[this->elf_body_field];
57,016✔
4034
        if (vd.get() == nullptr) {
57,016✔
4035
            vd = std::make_shared<value_def>(
45,025✔
4036
                this->elf_body_field,
45,025✔
4037
                value_kind_t::VALUE_TEXT,
×
4038
                logline_value_meta::internal_column{},
×
4039
                this);
45,025✔
4040
            if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
45,025✔
4041
                this->elf_value_def_order.emplace_back(vd);
6,789✔
4042
            }
4043
        }
4044
        vd->vd_meta.lvm_name = this->elf_body_field;
57,016✔
4045
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
57,016✔
4046
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
57,016✔
4047
        vd->vd_internal = true;
57,016✔
4048
    }
4049

4050
    if (!this->elf_src_file_field.empty()) {
57,016✔
4051
        auto& vd = this->elf_value_defs[this->elf_src_file_field];
7,861✔
4052
        if (vd.get() == nullptr) {
7,861✔
4053
            vd = std::make_shared<value_def>(
1✔
4054
                this->elf_src_file_field,
1✔
4055
                value_kind_t::VALUE_TEXT,
×
4056
                logline_value_meta::internal_column{},
×
4057
                this);
2✔
4058
        }
4059
        vd->vd_meta.lvm_name = this->elf_src_file_field;
7,861✔
4060
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
7,861✔
4061
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
7,861✔
4062
    }
4063

4064
    if (!this->elf_src_line_field.empty()) {
57,016✔
4065
        auto& vd = this->elf_value_defs[this->elf_src_line_field];
7,861✔
4066
        if (vd.get() == nullptr) {
7,861✔
4067
            vd = std::make_shared<value_def>(
1✔
4068
                this->elf_src_line_field,
1✔
4069
                value_kind_t::VALUE_INTEGER,
×
4070
                logline_value_meta::internal_column{},
×
4071
                this);
2✔
4072
        }
4073
        vd->vd_meta.lvm_name = this->elf_src_line_field;
7,861✔
4074
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_INTEGER;
7,861✔
4075
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
7,861✔
4076
    }
4077

4078
    if (!this->elf_thread_id_field.empty()) {
57,016✔
4079
        auto& vd = this->elf_value_defs[this->elf_thread_id_field];
18,079✔
4080
        if (vd.get() == nullptr) {
18,079✔
4081
            vd = std::make_shared<value_def>(
1✔
4082
                this->elf_thread_id_field,
1✔
4083
                value_kind_t::VALUE_TEXT,
×
4084
                logline_value_meta::internal_column{},
×
4085
                this);
2✔
4086
        }
4087
        vd->vd_meta.lvm_name = this->elf_thread_id_field;
18,079✔
4088
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
18,079✔
4089
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
18,079✔
4090
    }
4091

4092
    if (!this->elf_duration_field.empty()) {
57,016✔
4093
        auto& vd = this->elf_value_defs[this->elf_duration_field];
2,358✔
4094
        if (vd.get() == nullptr) {
2,358✔
4095
            vd = std::make_shared<value_def>(
×
4096
                this->elf_duration_field,
×
4097
                value_kind_t::VALUE_FLOAT,
×
4098
                logline_value_meta::internal_column{},
×
4099
                this);
×
4100
        }
4101
        vd->vd_meta.lvm_name = this->elf_duration_field;
2,358✔
4102
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_FLOAT;
2,358✔
4103
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
2,358✔
4104
    }
4105

4106
    for (auto& od_pair : *this->lf_opid_description_def) {
80,598✔
4107
        od_pair.second.od_index = this->lf_opid_description_def_vec->size();
23,582✔
4108
        this->lf_opid_description_def_vec->emplace_back(&od_pair.second);
23,582✔
4109
    }
4110

4111
    for (auto& od_pair : *this->lf_subid_description_def) {
57,802✔
4112
        od_pair.second.od_index = this->lf_subid_description_def_vec->size();
786✔
4113
        this->lf_subid_description_def_vec->emplace_back(&od_pair.second);
786✔
4114
    }
4115

4116
    if (!this->lf_timestamp_format.empty()) {
57,016✔
4117
        this->lf_timestamp_format.push_back(nullptr);
7,178✔
4118
    }
4119
    auto src_file_found = 0;
57,016✔
4120
    auto src_line_found = 0;
57,016✔
4121
    auto thread_id_found = 0;
57,016✔
4122
    auto duration_found = 0;
57,016✔
4123
    for (auto& elf_pattern : this->elf_patterns) {
160,694✔
4124
        auto& pat = *elf_pattern.second;
103,678✔
4125

4126
        if (pat.p_pcre.pp_value == nullptr) {
103,678✔
4127
            continue;
1✔
4128
        }
4129

4130
        if (pat.p_opid_field_index == -1
207,354✔
4131
            && this->lf_opid_source.value_or(opid_source_t::from_description)
103,677✔
4132
                == opid_source_t::from_description
4133
            && this->lf_opid_description_def->size() == 1)
207,354✔
4134
        {
4135
            const auto& opid_def
4136
                = this->lf_opid_description_def->begin()->second;
25,938✔
4137
            for (const auto& desc : *opid_def.od_descriptors) {
58,164✔
4138
                for (auto named_cap : pat.p_pcre.pp_value->get_named_captures())
375,708✔
4139
                {
4140
                    const intern_string_t name
4141
                        = intern_string::lookup(named_cap.get_name());
343,482✔
4142

4143
                    if (name == desc.od_field.pp_value) {
343,482✔
4144
                        pat.p_opid_description_field_indexes.emplace_back(
59,736✔
4145
                            named_cap.get_index());
29,868✔
4146
                    }
4147
                }
4148
            }
4149
        }
4150

4151
        for (auto named_cap : pat.p_pcre.pp_value->get_named_captures()) {
892,986✔
4152
            const intern_string_t name
4153
                = intern_string::lookup(named_cap.get_name());
789,309✔
4154

4155
            if (name == this->lf_timestamp_field) {
789,309✔
4156
                pat.p_timestamp_field_index = named_cap.get_index();
103,675✔
4157
            }
4158
            if (name == this->lf_time_field) {
789,309✔
4159
                pat.p_time_field_index = named_cap.get_index();
786✔
4160
            }
4161
            if (name == this->elf_level_field) {
789,309✔
4162
                pat.p_level_field_index = named_cap.get_index();
79,102✔
4163
            }
4164
            if (name == this->elf_opid_field) {
789,309✔
4165
                pat.p_opid_field_index = named_cap.get_index();
21,222✔
4166
            }
4167
            if (name == this->elf_subid_field) {
789,309✔
4168
                pat.p_subid_field_index = named_cap.get_index();
11,790✔
4169
            }
4170
            if (name == this->elf_body_field) {
789,309✔
4171
                pat.p_body_field_index = named_cap.get_index();
89,527✔
4172
            }
4173
            if (name == this->elf_src_file_field) {
789,309✔
4174
                pat.p_src_file_field_index = named_cap.get_index();
12,576✔
4175
                src_file_found += 1;
12,576✔
4176
            }
4177
            if (name == this->elf_src_line_field) {
789,309✔
4178
                pat.p_src_line_field_index = named_cap.get_index();
14,148✔
4179
                src_line_found += 1;
14,148✔
4180
            }
4181
            if (name == this->elf_thread_id_field) {
789,309✔
4182
                pat.p_thread_id_field_index = named_cap.get_index();
44,016✔
4183
                thread_id_found += 1;
44,016✔
4184
            }
4185
            if (name == this->elf_duration_field) {
789,309✔
4186
                pat.p_duration_field_index = named_cap.get_index();
4,716✔
4187
                duration_found += 1;
4,716✔
4188
            }
4189

4190
            auto value_iter = this->elf_value_defs.find(name);
789,309✔
4191
            if (value_iter != this->elf_value_defs.end()) {
789,309✔
4192
                auto vd = value_iter->second;
777,417✔
4193
                indexed_value_def ivd;
777,417✔
4194

4195
                ivd.ivd_index = named_cap.get_index();
777,417✔
4196
                if (!vd->vd_unit_field.empty()) {
777,417✔
4197
                    ivd.ivd_unit_field_index = pat.p_pcre.pp_value->name_index(
1,572✔
4198
                        vd->vd_unit_field.get());
786✔
4199
                } else {
4200
                    ivd.ivd_unit_field_index = -1;
776,631✔
4201
                }
4202
                if (!vd->vd_internal
777,417✔
4203
                    && !vd->vd_meta.lvm_column
1,336,079✔
4204
                            .is<logline_value_meta::table_column>())
558,662✔
4205
                {
4206
                    vd->vd_meta.lvm_column = logline_value_meta::table_column{
313,430✔
4207
                        this->elf_column_count++};
313,430✔
4208
                }
4209
                ivd.ivd_value_def = vd;
777,417✔
4210
                pat.p_value_by_index.push_back(ivd);
777,417✔
4211
            }
777,417✔
4212
            pat.p_value_name_to_index[name] = named_cap.get_index();
789,309✔
4213
        }
4214

4215
        stable_sort(pat.p_value_by_index.begin(), pat.p_value_by_index.end());
103,677✔
4216

4217
        for (int lpc = 0; lpc < (int) pat.p_value_by_index.size(); lpc++) {
881,094✔
4218
            auto& ivd = pat.p_value_by_index[lpc];
777,417✔
4219
            auto vd = ivd.ivd_value_def;
777,417✔
4220

4221
            if (!vd->vd_meta.lvm_foreign_key && !vd->vd_meta.lvm_identifier) {
777,417✔
4222
                switch (vd->vd_meta.lvm_kind) {
395,906✔
4223
                    case value_kind_t::VALUE_INTEGER:
54,334✔
4224
                    case value_kind_t::VALUE_FLOAT:
4225
                        pat.p_numeric_value_indexes.push_back(lpc);
54,334✔
4226
                        break;
54,334✔
4227
                    default:
341,572✔
4228
                        break;
341,572✔
4229
                }
4230
            }
4231
        }
777,417✔
4232

4233
        if (pat.p_timestamp_field_index == -1) {
103,677✔
4234
            errors.emplace_back(
2✔
4235
                lnav::console::user_message::error(
×
4236
                    attr_line_t("invalid pattern: ")
4✔
4237
                        .append_quoted(lnav::roles::symbol(pat.p_config_path)))
4✔
4238
                    .with_reason("no timestamp capture found in the pattern")
4✔
4239
                    .with_snippets(this->get_snippets())
4✔
4240
                    .with_help("all log messages need a timestamp"));
4241
        }
4242

4243
        if (!this->elf_level_field.empty() && pat.p_level_field_index == -1) {
103,677✔
4244
            log_warning("%s:level field '%s' not found in pattern",
24,575✔
4245
                        pat.p_config_path.c_str(),
4246
                        this->elf_level_field.get());
4247
        }
4248
        if (!this->elf_body_field.empty() && pat.p_body_field_index == -1) {
103,677✔
4249
            log_warning("%s:body field '%s' not found in pattern",
14,150✔
4250
                        pat.p_config_path.c_str(),
4251
                        this->elf_body_field.get());
4252
        }
4253

4254
        this->elf_pattern_order.push_back(elf_pattern.second);
103,677✔
4255
    }
4256
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
114,032✔
4257
        && !this->elf_src_file_field.empty() && src_file_found == 0)
57,016✔
4258
    {
4259
        errors.emplace_back(
1✔
4260
            lnav::console::user_message::error(
×
4261
                attr_line_t("invalid pattern: ")
2✔
4262
                    .append_quoted(
1✔
4263
                        lnav::roles::symbol(this->elf_name.to_string())))
2✔
4264
                .with_reason("no source file capture found in the pattern")
2✔
4265
                .with_snippets(this->get_snippets())
2✔
4266
                .with_help(attr_line_t("at least one pattern needs a source "
2✔
4267
                                       "file capture named ")
4268
                               .append_quoted(this->elf_src_file_field.get())));
1✔
4269
    }
4270
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
114,032✔
4271
        && !this->elf_src_line_field.empty() && src_line_found == 0)
57,016✔
4272
    {
4273
        errors.emplace_back(
1✔
4274
            lnav::console::user_message::error(
×
4275
                attr_line_t("invalid pattern: ")
2✔
4276
                    .append_quoted(
1✔
4277
                        lnav::roles::symbol(this->elf_name.to_string())))
2✔
4278
                .with_reason("no source line capture found in the pattern")
2✔
4279
                .with_snippets(this->get_snippets())
2✔
4280
                .with_help(attr_line_t("at least one pattern needs a source "
2✔
4281
                                       "line capture named ")
4282
                               .append_quoted(this->elf_src_line_field.get())));
1✔
4283
    }
4284
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
114,032✔
4285
        && !this->elf_thread_id_field.empty() && thread_id_found == 0)
57,016✔
4286
    {
4287
        errors.emplace_back(
1✔
4288
            lnav::console::user_message::error(
×
4289
                attr_line_t("invalid pattern: ")
2✔
4290
                    .append_quoted(
1✔
4291
                        lnav::roles::symbol(this->elf_name.to_string())))
2✔
4292
                .with_reason("no thread ID capture found in the pattern")
2✔
4293
                .with_snippets(this->get_snippets())
2✔
4294
                .with_help(
4295
                    attr_line_t(
2✔
4296
                        "at least one pattern needs a thread ID capture named ")
4297
                        .append_quoted(this->elf_thread_id_field.get())));
1✔
4298
    }
4299
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
114,032✔
4300
        && !this->elf_duration_field.empty() && duration_found == 0)
57,016✔
4301
    {
4302
        errors.emplace_back(
×
4303
            lnav::console::user_message::error(
×
4304
                attr_line_t("invalid pattern: ")
×
4305
                    .append_quoted(
×
4306
                        lnav::roles::symbol(this->elf_name.to_string())))
×
4307
                .with_reason("no duration capture found in the pattern")
×
4308
                .with_snippets(this->get_snippets())
×
4309
                .with_help(
4310
                    attr_line_t(
×
4311
                        "at least one pattern needs a duration capture named ")
4312
                        .append_quoted(this->elf_duration_field.get())));
×
4313
    }
4314

4315
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
57,016✔
4316
        if (!this->elf_patterns.empty()) {
11,606✔
4317
            errors.emplace_back(
1✔
4318
                lnav::console::user_message::error(
×
4319
                    attr_line_t()
2✔
4320
                        .append_quoted(
1✔
4321
                            lnav::roles::symbol(this->elf_name.to_string()))
2✔
4322
                        .append(" is not a valid log format"))
1✔
4323
                    .with_reason("structured logs cannot have regexes")
2✔
4324
                    .with_snippets(this->get_snippets()));
2✔
4325
        }
4326
        if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
11,606✔
4327
            this->lf_multiline = true;
11,606✔
4328
            this->lf_structured = true;
11,606✔
4329
            this->lf_formatted_lines = true;
11,606✔
4330
            this->jlf_parse_context
4331
                = std::make_shared<yajlpp_parse_context>(this->elf_name);
11,606✔
4332
            this->jlf_yajl_handle.reset(
11,606✔
4333
                yajl_alloc(&this->jlf_parse_context->ypc_callbacks,
11,606✔
4334
                           nullptr,
4335
                           this->jlf_parse_context.get()),
11,606✔
4336
                yajl_handle_deleter());
4337
            yajl_config(
11,606✔
4338
                this->jlf_yajl_handle.get(), yajl_dont_validate_strings, 1);
4339
        }
4340
    } else {
4341
        if (this->elf_patterns.empty()) {
45,410✔
4342
            errors.emplace_back(lnav::console::user_message::error(
2✔
4343
                                    attr_line_t()
4✔
4344
                                        .append_quoted(lnav::roles::symbol(
4✔
4345
                                            this->elf_name.to_string()))
4✔
4346
                                        .append(" is not a valid log format"))
2✔
4347
                                    .with_reason("no regexes specified")
4✔
4348
                                    .with_snippets(this->get_snippets()));
4✔
4349
        }
4350
    }
4351

4352
    stable_sort(this->elf_level_pairs.begin(), this->elf_level_pairs.end());
57,016✔
4353

4354
    {
4355
        safe::WriteAccess<safe_format_header_expressions> hexprs(
4356
            format_header_exprs);
57,016✔
4357

4358
        if (hexprs->e_db.in() == nullptr) {
57,016✔
4359
            if (sqlite3_open(":memory:", hexprs->e_db.out()) != SQLITE_OK) {
786✔
4360
                log_error("unable to open memory DB");
×
4361
                return;
×
4362
            }
4363
            register_sqlite_funcs(hexprs->e_db.in(), sqlite_registration_funcs);
786✔
4364
        }
4365

4366
        for (const auto& hpair : this->elf_converter.c_header.h_exprs.he_exprs)
60,947✔
4367
        {
4368
            auto stmt_str
4369
                = fmt::format(FMT_STRING("SELECT 1 WHERE {}"), hpair.second);
11,793✔
4370
            compiled_header_expr che;
3,931✔
4371

4372
            log_info("preparing file-format header expression: %s",
3,931✔
4373
                     stmt_str.c_str());
4374
            auto retcode = sqlite3_prepare_v2(hexprs->e_db.in(),
7,862✔
4375
                                              stmt_str.c_str(),
4376
                                              stmt_str.size(),
3,931✔
4377
                                              che.che_stmt.out(),
4378
                                              nullptr);
4379
            if (retcode != SQLITE_OK) {
3,931✔
4380
                auto sql_al = attr_line_t(hpair.second)
2✔
4381
                                  .with_attr_for_all(SA_PREFORMATTED.value())
2✔
4382
                                  .with_attr_for_all(
1✔
4383
                                      VC_ROLE.value(role_t::VCR_QUOTED_CODE))
2✔
4384
                                  .move();
1✔
4385
                readline_sql_highlighter(
1✔
4386
                    sql_al, lnav::sql::dialect::sqlite, std::nullopt);
4387
                intern_string_t watch_expr_path = intern_string::lookup(
4388
                    fmt::format(FMT_STRING("/{}/converter/header/expr/{}"),
3✔
4389
                                this->elf_name,
1✔
4390
                                hpair.first));
2✔
4391
                auto snippet = lnav::console::snippet::from(
4392
                    source_location(watch_expr_path), sql_al);
1✔
4393

4394
                auto um = lnav::console::user_message::error(
2✔
4395
                              "SQL expression is invalid")
4396
                              .with_reason(sqlite3_errmsg(hexprs->e_db.in()))
2✔
4397
                              .with_snippet(snippet)
1✔
4398
                              .move();
1✔
4399

4400
                errors.emplace_back(um);
1✔
4401
                continue;
1✔
4402
            }
1✔
4403

4404
            hexprs->e_header_exprs[this->elf_name][hpair.first]
3,930✔
4405
                = std::move(che);
7,860✔
4406
        }
3,932✔
4407

4408
        if (!this->elf_converter.c_header.h_exprs.he_exprs.empty()
57,016✔
4409
            && this->elf_converter.c_command.pp_value.empty())
57,016✔
4410
        {
4411
            auto um = lnav::console::user_message::error(
2✔
4412
                          "A command is required when a converter is defined")
4413
                          .with_help(
2✔
4414
                              "The converter command transforms the file "
4415
                              "into a format that can be consumed by lnav")
4416
                          .with_snippets(this->get_snippets())
2✔
4417
                          .move();
1✔
4418
            errors.emplace_back(um);
1✔
4419
        }
1✔
4420
    }
57,016✔
4421

4422
    for (auto& vd : this->elf_value_def_order) {
576,273✔
4423
        std::vector<std::string>::iterator act_iter;
519,257✔
4424

4425
        if (!vd->vd_internal
519,257✔
4426
            && log_vtab_impl::RESERVED_COLUMNS.count(
983,544✔
4427
                vd->vd_meta.lvm_name.to_string_fragment()))
983,544✔
4428
        {
4429
            auto um = lnav::console::user_message::error(
×
4430
                          attr_line_t("value name ")
1✔
4431
                              .append_quoted(lnav::roles::symbol(
2✔
4432
                                  fmt::format(FMT_STRING("/{}/value/{}"),
4✔
4433
                                              this->elf_name,
1✔
4434
                                              vd->vd_meta.lvm_name)))
1✔
4435
                              .append(" is reserved and cannot be used"))
1✔
4436
                          .with_reason(
2✔
4437
                              "lnav automatically defines several columns in "
4438
                              "the log virtual table")
4439
                          .with_snippets(this->get_snippets())
2✔
4440
                          .with_help("Choose another name")
2✔
4441
                          .move();
1✔
4442
            errors.emplace_back(um);
1✔
4443
        }
1✔
4444

4445
        vd->vd_meta.lvm_format = this;
519,257✔
4446
        if (!vd->vd_internal
519,257✔
4447
            && !vd->vd_meta.lvm_column.is<logline_value_meta::table_column>())
519,257✔
4448
        {
4449
            vd->vd_meta.lvm_column
150,857✔
4450
                = logline_value_meta::table_column{this->elf_column_count++};
150,857✔
4451
        }
4452

4453
        if (vd->vd_meta.lvm_kind == value_kind_t::VALUE_UNKNOWN) {
519,257✔
4454
            log_warning("no kind set for %s, assuming text",
×
4455
                        vd->vd_meta.lvm_name.c_str());
4456
            vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
×
4457
        }
4458

4459
        if (this->elf_type == elf_type_t::ELF_TYPE_TEXT) {
519,257✔
4460
            std::set<std::string> available_captures;
330,724✔
4461

4462
            bool found_in_pattern = false;
330,724✔
4463
            for (const auto& pat : this->elf_patterns) {
556,310✔
4464
                if (pat.second->p_pcre.pp_value == nullptr) {
556,308✔
4465
                    continue;
×
4466
                }
4467

4468
                auto cap_index = pat.second->p_pcre.pp_value->name_index(
1,112,616✔
4469
                    vd->vd_meta.lvm_name.get());
556,308✔
4470
                if (cap_index >= 0) {
556,308✔
4471
                    found_in_pattern = true;
330,722✔
4472
                    break;
330,722✔
4473
                }
4474

4475
                for (auto named_cap :
225,586✔
4476
                     pat.second->p_pcre.pp_value->get_named_captures())
2,055,408✔
4477
                {
4478
                    available_captures.insert(named_cap.get_name().to_string());
1,604,236✔
4479
                }
4480
            }
4481
            if (!found_in_pattern) {
330,724✔
4482
                auto notes
4483
                    = attr_line_t("the following captures are available:\n  ")
2✔
4484
                          .join(available_captures,
2✔
4485
                                VC_ROLE.value(role_t::VCR_SYMBOL),
4✔
4486
                                ", ")
4487
                          .move();
2✔
4488
                errors.emplace_back(
2✔
4489
                    lnav::console::user_message::warning(
×
4490
                        attr_line_t("invalid value ")
2✔
4491
                            .append_quoted(lnav::roles::symbol(
4✔
4492
                                fmt::format(FMT_STRING("/{}/value/{}"),
8✔
4493
                                            this->elf_name,
2✔
4494
                                            vd->vd_meta.lvm_name.get()))))
4✔
4495
                        .with_reason(
4✔
4496
                            attr_line_t("no patterns have a capture named ")
4✔
4497
                                .append_quoted(vd->vd_meta.lvm_name.get()))
2✔
4498
                        .with_note(notes)
2✔
4499
                        .with_snippets(this->get_snippets())
4✔
4500
                        .with_help("values are populated from captures in "
4501
                                   "patterns, so at least one pattern must "
4502
                                   "have a capture with this value name"));
4503
            }
2✔
4504
        }
330,724✔
4505

4506
        for (act_iter = vd->vd_action_list.begin();
519,257✔
4507
             act_iter != vd->vd_action_list.end();
520,043✔
4508
             ++act_iter)
786✔
4509
        {
4510
            if (this->lf_action_defs.find(*act_iter)
786✔
4511
                == this->lf_action_defs.end())
1,572✔
4512
            {
4513
#if 0
4514
                errors.push_back("error:" + this->elf_name.to_string() + ":"
4515
                                 + vd->vd_meta.lvm_name.get()
4516
                                 + ": cannot find action -- " + (*act_iter));
4517
#endif
4518
            }
4519
        }
4520

4521
        vd->set_rewrite_src_name();
519,257✔
4522

4523
        for (auto& hd_pair : vd->vd_highlighter_patterns) {
521,715✔
4524
            auto& hd = hd_pair.second;
2,458✔
4525
            text_attrs attrs;
2,458✔
4526

4527
            if (hd.hd_pattern.pp_value == nullptr) {
2,458✔
4528
                hd.hd_pattern.pp_value
4529
                    = lnav::pcre2pp::code::from_const(".*").to_shared();
2,358✔
4530
            }
4531

4532
            if (!hd.hd_color.pp_value.empty()) {
2,458✔
4533
                attrs.ta_fg_color = vc.match_color(
2,458✔
4534
                    styling::color_unit::from_str(hd.hd_color.pp_value)
4,916✔
4535
                        .unwrapOrElse([&](const auto& msg) {
×
4536
                            errors.emplace_back(
×
4537
                                lnav::console::user_message::error(
4538
                                    attr_line_t()
×
4539
                                        .append_quoted(hd.hd_color.pp_value)
×
4540
                                        .append(
×
4541
                                            " is not a valid color value for "
4542
                                            "property ")
4543
                                        .append_quoted(lnav::roles::symbol(
×
4544
                                            hd.hd_color.pp_path.to_string())))
×
4545
                                    .with_reason(msg)
×
4546
                                    .with_snippet(hd.hd_color.to_snippet()));
×
4547
                            return styling::color_unit::EMPTY;
×
4548
                        }));
4549
            }
4550

4551
            if (!hd.hd_background_color.pp_value.empty()) {
2,458✔
4552
                attrs.ta_bg_color = vc.match_color(
×
4553
                    styling::color_unit::from_str(
×
4554
                        hd.hd_background_color.pp_value)
×
4555
                        .unwrapOrElse([&](const auto& msg) {
×
4556
                            errors.emplace_back(
×
4557
                                lnav::console::user_message::error(
4558
                                    attr_line_t()
×
4559
                                        .append_quoted(
×
4560
                                            hd.hd_background_color.pp_value)
×
4561
                                        .append(
×
4562
                                            " is not a valid color value for "
4563
                                            "property ")
4564
                                        .append_quoted(lnav::roles::symbol(
×
4565
                                            hd.hd_background_color.pp_path
×
4566
                                                .to_string())))
4567
                                    .with_reason(msg)
×
4568
                                    .with_snippet(
4569
                                        hd.hd_background_color.to_snippet()));
×
4570
                            return styling::color_unit::EMPTY;
×
4571
                        }));
4572
            }
4573

4574
            if (hd.hd_underline) {
2,458✔
4575
                attrs |= text_attrs::style::underline;
×
4576
            }
4577
            if (hd.hd_blink) {
2,458✔
4578
                attrs |= text_attrs::style::blink;
×
4579
            }
4580

4581
            if (hd.hd_pattern.pp_value != nullptr) {
2,458✔
4582
                this->lf_highlighters.emplace_back(hd.hd_pattern.pp_value);
2,458✔
4583
                this->lf_highlighters.back()
2,458✔
4584
                    .with_field(vd->vd_meta.lvm_name)
2,458✔
4585
                    .with_name(hd_pair.first.to_string())
4,916✔
4586
                    .with_attrs(attrs)
2,458✔
4587
                    .with_nestable(hd.hd_nestable);
2,458✔
4588
            }
4589
        }
4590
    }
4591

4592
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
57,016✔
4593
        for (const auto& vd : this->elf_value_def_order) {
200,139✔
4594
            this->elf_value_def_frag_map[vd->vd_meta.lvm_name
188,533✔
4595
                                             .to_string_fragment()] = vd.get();
188,533✔
4596
        }
4597
    }
4598

4599
    for (const auto& td_pair : this->lf_tag_defs) {
59,477✔
4600
        const auto& td = td_pair.second;
2,461✔
4601

4602
        if (td->ftd_pattern.pp_value == nullptr
2,461✔
4603
            || td->ftd_pattern.pp_value->get_pattern().empty())
2,461✔
4604
        {
4605
            errors.emplace_back(
3✔
4606
                lnav::console::user_message::error(
×
4607
                    attr_line_t("invalid tag definition ")
6✔
4608
                        .append_quoted(lnav::roles::symbol(
6✔
4609
                            fmt::format(FMT_STRING("/{}/tags/{}"),
12✔
4610
                                        this->elf_name,
3✔
4611
                                        td_pair.first))))
3✔
4612
                    .with_reason(
6✔
4613
                        "tag definitions must have a non-empty pattern")
4614
                    .with_snippets(this->get_snippets()));
6✔
4615
        }
4616
    }
4617

4618
    if (this->elf_opid_field.empty()
57,016✔
4619
        && this->lf_opid_description_def->size() > 1)
57,016✔
4620
    {
4621
        errors.emplace_back(
1✔
4622
            lnav::console::user_message::error(
×
4623
                attr_line_t("too many opid descriptions")
2✔
4624
                    .append_quoted(lnav::roles::symbol(fmt::format(
2✔
4625
                        FMT_STRING("/{}/opid/description"), this->elf_name))))
4✔
4626
                .with_reason(attr_line_t("when no ")
2✔
4627
                                 .append("opid-field"_symbol)
1✔
4628
                                 .append(" is specified, only a single "
1✔
4629
                                         "description is supported"))
4630
                .with_snippets(this->get_snippets()));
2✔
4631
    }
4632

4633
    for (const auto& opid_desc_pair : *this->lf_opid_description_def) {
80,598✔
4634
        for (const auto& opid_desc : *opid_desc_pair.second.od_descriptors) {
55,810✔
4635
            auto iter = this->elf_value_defs.find(opid_desc.od_field.pp_value);
32,228✔
4636
            if (iter == this->elf_value_defs.end()) {
32,228✔
4637
                errors.emplace_back(
2✔
4638
                    lnav::console::user_message::error(
×
4639
                        attr_line_t("invalid opid description field ")
4✔
4640
                            .append_quoted(lnav::roles::symbol(
4✔
4641
                                opid_desc.od_field.pp_path.to_string())))
4✔
4642
                        .with_reason(
4✔
4643
                            attr_line_t("unknown value name ")
4✔
4644
                                .append_quoted(opid_desc.od_field.pp_value))
2✔
4645
                        .with_snippets(this->get_snippets()));
4✔
4646
            } else {
4647
                this->lf_desc_fields.insert(iter->first);
32,226✔
4648
                iter->second->vd_is_desc_field = true;
32,226✔
4649
            }
4650
        }
4651
    }
4652

4653
    for (const auto& subid_desc_pair : *this->lf_subid_description_def) {
57,802✔
4654
        for (const auto& subid_desc : *subid_desc_pair.second.od_descriptors) {
1,572✔
4655
            auto iter = this->elf_value_defs.find(subid_desc.od_field.pp_value);
786✔
4656
            if (iter == this->elf_value_defs.end()) {
786✔
4657
                errors.emplace_back(
×
4658
                    lnav::console::user_message::error(
×
4659
                        attr_line_t("invalid subid description field ")
×
4660
                            .append_quoted(lnav::roles::symbol(
×
4661
                                subid_desc.od_field.pp_path.to_string())))
×
4662
                        .with_reason(
×
4663
                            attr_line_t("unknown value name ")
×
4664
                                .append_quoted(subid_desc.od_field.pp_value))
×
4665
                        .with_snippets(this->get_snippets()));
×
4666
            } else {
4667
                this->lf_desc_fields.insert(iter->first);
786✔
4668
                iter->second->vd_is_desc_field = true;
786✔
4669
            }
4670
        }
4671
    }
4672

4673
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
114,032✔
4674
        && this->elf_samples.empty())
57,016✔
4675
    {
4676
        errors.emplace_back(
3✔
4677
            lnav::console::user_message::error(
×
4678
                attr_line_t()
6✔
4679
                    .append_quoted(
3✔
4680
                        lnav::roles::symbol(this->elf_name.to_string()))
6✔
4681
                    .append(" is not a valid log format"))
3✔
4682
                .with_reason("log message samples must be included in a format "
6✔
4683
                             "definition")
4684
                .with_snippets(this->get_snippets()));
6✔
4685
    }
4686

4687
    for (const auto& pat : this->elf_pattern_order) {
160,693✔
4688
        if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
103,677✔
4689
            continue;
1✔
4690
        }
4691
        if (pat->p_pcre.pp_value->name_index(this->lf_timestamp_field.get())
103,676✔
4692
            < 0)
103,676✔
4693
        {
4694
            attr_line_t notes;
1✔
4695
            bool first_note = true;
1✔
4696

4697
            if (pat->p_pcre.pp_value->get_capture_count() > 0) {
1✔
4698
                notes.append("the following captures are available:\n  ");
1✔
4699
            }
4700
            for (auto named_cap : pat->p_pcre.pp_value->get_named_captures()) {
4✔
4701
                if (!first_note) {
3✔
4702
                    notes.append(", ");
2✔
4703
                }
4704
                notes.append(
3✔
4705
                    lnav::roles::symbol(named_cap.get_name().to_string()));
6✔
4706
                first_note = false;
3✔
4707
            }
4708
            errors.emplace_back(
1✔
4709
                lnav::console::user_message::error(
×
4710
                    attr_line_t("invalid value for property ")
1✔
4711
                        .append_quoted(lnav::roles::symbol(
2✔
4712
                            fmt::format(FMT_STRING("/{}/timestamp-field"),
4✔
4713
                                        this->elf_name))))
1✔
4714
                    .with_reason(
2✔
4715
                        attr_line_t()
2✔
4716
                            .append_quoted(this->lf_timestamp_field)
1✔
4717
                            .append(" was not found in the pattern at ")
1✔
4718
                            .append(lnav::roles::symbol(pat->p_config_path)))
2✔
4719
                    .with_note(notes)
1✔
4720
                    .with_snippets(this->get_snippets()));
2✔
4721
        }
1✔
4722
    }
4723

4724
    for (size_t sample_index = 0; sample_index < this->elf_samples.size();
255,998✔
4725
         sample_index += 1)
198,982✔
4726
    {
4727
        auto& elf_sample = this->elf_samples[sample_index];
198,982✔
4728
        auto sample_lines
4729
            = string_fragment(elf_sample.s_line.pp_value).split_lines();
198,982✔
4730

4731
        if (this->test_line(elf_sample, errors).is<scan_match>()) {
198,982✔
4732
            for (const auto& pat_name : elf_sample.s_matched_regexes) {
394,818✔
4733
                this->elf_patterns[pat_name]->p_matched_samples.emplace(
195,837✔
4734
                    sample_index);
4735
            }
4736
        }
4737
    }
198,982✔
4738

4739
    if (!this->elf_samples.empty()) {
57,016✔
4740
        for (const auto& elf_sample : this->elf_samples) {
245,961✔
4741
            if (elf_sample.s_matched_regexes.size() <= 1) {
198,982✔
4742
                continue;
198,982✔
4743
            }
4744

4745
            errors.emplace_back(
×
4746
                lnav::console::user_message::warning(
×
4747
                    attr_line_t("invalid log format: ")
×
4748
                        .append_quoted(
×
4749
                            lnav::roles::symbol(this->elf_name.to_string())))
×
4750
                    .with_reason(
×
4751
                        attr_line_t(
×
4752
                            "sample is matched by more than one regex: ")
4753
                            .join(elf_sample.s_matched_regexes,
×
4754
                                  VC_ROLE.value(role_t::VCR_SYMBOL),
×
4755
                                  ", "))
4756
                    .with_snippet(lnav::console::snippet::from(
×
4757
                        elf_sample.s_line.pp_location,
4758
                        attr_line_t().append(lnav::roles::quoted_code(
×
4759
                            elf_sample.s_line.pp_value))))
×
4760
                    .with_help("log format regexes must match a single type "
4761
                               "of log message"));
4762
        }
4763

4764
        for (const auto& pat : this->elf_pattern_order) {
150,653✔
4765
            if (pat->p_matched_samples.empty()) {
103,674✔
4766
                errors.emplace_back(
2✔
4767
                    lnav::console::user_message::warning(
×
4768
                        attr_line_t("invalid pattern: ")
4✔
4769
                            .append_quoted(
2✔
4770
                                lnav::roles::symbol(pat->p_config_path)))
4✔
4771
                        .with_reason("pattern does not match any samples")
4✔
4772
                        .with_snippet(lnav::console::snippet::from(
6✔
4773
                            pat->p_pcre.pp_location, ""))
2✔
4774
                        .with_help(
4775
                            "every pattern should have at least one sample "
4776
                            "that it matches"));
4777
            }
4778
        }
4779
    }
4780

4781
    size_t value_def_index = 0;
57,016✔
4782
    for (auto& elf_value_def : this->elf_value_def_order) {
576,273✔
4783
        elf_value_def->vd_meta.lvm_values_index
519,257✔
4784
            = std::make_optional(value_def_index++);
519,257✔
4785

4786
        if (elf_value_def->vd_meta.lvm_foreign_key
519,257✔
4787
            || elf_value_def->vd_meta.lvm_identifier)
519,257✔
4788
        {
4789
            continue;
271,785✔
4790
        }
4791

4792
        switch (elf_value_def->vd_meta.lvm_kind) {
247,472✔
4793
            case value_kind_t::VALUE_INTEGER:
58,564✔
4794
            case value_kind_t::VALUE_FLOAT:
4795
                this->elf_numeric_value_defs.push_back(elf_value_def);
58,564✔
4796
                break;
58,564✔
4797
            default:
188,908✔
4798
                break;
188,908✔
4799
        }
4800
    }
4801

4802
    int format_index = 0;
57,016✔
4803
    for (auto iter = this->jlf_line_format.begin();
57,016✔
4804
         iter != this->jlf_line_format.end();
196,411✔
4805
         ++iter, format_index++)
139,395✔
4806
    {
4807
        static const intern_string_t ts
4808
            = intern_string::lookup("__timestamp__");
140,967✔
4809
        static const intern_string_t level_field
4810
            = intern_string::lookup("__level__");
140,967✔
4811
        auto& jfe = *iter;
139,395✔
4812

4813
        if (startswith(jfe.jfe_value.pp_value.get(), "/")) {
139,395✔
4814
            jfe.jfe_value.pp_value
4815
                = intern_string::lookup(jfe.jfe_value.pp_value.get() + 1);
200✔
4816
        }
4817
        if (!jfe.jfe_ts_format.empty()) {
139,395✔
4818
            if (!jfe.jfe_value.pp_value.empty() && jfe.jfe_value.pp_value != ts)
886✔
4819
            {
4820
                log_warning(
100✔
4821
                    "%s:line-format[%d]:ignoring field '%s' since "
4822
                    "timestamp-format was used",
4823
                    this->elf_name.get(),
4824
                    format_index,
4825
                    jfe.jfe_value.pp_value.get());
4826
            }
4827
            jfe.jfe_value.pp_value = ts;
886✔
4828
        }
4829

4830
        switch (jfe.jfe_type) {
139,395✔
4831
            case json_log_field::VARIABLE: {
95,937✔
4832
                auto vd_iter
4833
                    = this->elf_value_defs.find(jfe.jfe_value.pp_value);
95,937✔
4834
                if (jfe.jfe_value.pp_value == ts) {
95,937✔
4835
                    this->elf_value_defs[this->lf_timestamp_field]
9,733✔
4836
                        ->vd_meta.lvm_hidden = true;
9,733✔
4837
                } else if (jfe.jfe_value.pp_value == level_field) {
86,204✔
4838
                    this->elf_value_defs[this->elf_level_field]
3,930✔
4839
                        ->vd_meta.lvm_hidden = true;
3,930✔
4840
                } else if (vd_iter == this->elf_value_defs.end()) {
82,274✔
4841
                    errors.emplace_back(
2✔
4842
                        lnav::console::user_message::error(
×
4843
                            attr_line_t("invalid line format element ")
4✔
4844
                                .append_quoted(lnav::roles::symbol(fmt::format(
4✔
4845
                                    FMT_STRING("/{}/line-format/{}/field"),
6✔
4846
                                    this->elf_name,
2✔
4847
                                    format_index))))
4848
                            .with_reason(
4✔
4849
                                attr_line_t()
4✔
4850
                                    .append_quoted(jfe.jfe_value.pp_value)
2✔
4851
                                    .append(" is not a defined value"))
2✔
4852
                            .with_snippet(jfe.jfe_value.to_snippet()));
4✔
4853
                } else {
4854
                    vd_iter->second->vd_line_format_index = format_index;
82,272✔
4855
                    switch (vd_iter->second->vd_meta.lvm_kind) {
82,272✔
4856
                        case value_kind_t::VALUE_INTEGER:
12,776✔
4857
                        case value_kind_t::VALUE_FLOAT:
4858
                            if (jfe.jfe_align
12,776✔
4859
                                == json_format_element::align_t::NONE)
4860
                            {
4861
                                jfe.jfe_align
4862
                                    = json_format_element::align_t::RIGHT;
11,990✔
4863
                            }
4864
                            break;
12,776✔
4865
                        default:
69,496✔
4866
                            break;
69,496✔
4867
                    }
4868
                }
4869
                break;
95,937✔
4870
            }
4871
            case json_log_field::CONSTANT:
43,458✔
4872
                this->jlf_line_format_init_count
43,458✔
4873
                    += std::count(jfe.jfe_default_value.begin(),
43,458✔
4874
                                  jfe.jfe_default_value.end(),
4875
                                  '\n');
43,458✔
4876
                break;
43,458✔
4877
            default:
×
4878
                break;
×
4879
        }
4880
    }
4881

4882
    for (auto& hd_pair : this->elf_highlighter_patterns) {
58,204✔
4883
        auto& hd = hd_pair.second;
1,188✔
4884
        text_attrs attrs;
1,188✔
4885

4886
        if (!hd.hd_color.pp_value.empty()) {
1,188✔
4887
            attrs.ta_fg_color = vc.match_color(
1,187✔
4888
                styling::color_unit::from_str(hd.hd_color.pp_value)
2,374✔
4889
                    .unwrapOrElse([&](const auto& msg) {
1✔
4890
                        errors.emplace_back(
1✔
4891
                            lnav::console::user_message::error(
4892
                                attr_line_t()
1✔
4893
                                    .append_quoted(hd.hd_color.pp_value)
2✔
4894
                                    .append(" is not a valid color value for "
1✔
4895
                                            "property ")
4896
                                    .append_quoted(lnav::roles::symbol(
2✔
4897
                                        hd.hd_color.pp_path.to_string())))
1✔
4898
                                .with_reason(msg)
2✔
4899
                                .with_snippet(hd.hd_color.to_snippet()));
1✔
4900
                        return styling::color_unit::EMPTY;
1✔
4901
                    }));
4902
        }
4903

4904
        if (!hd.hd_background_color.pp_value.empty()) {
1,188✔
4905
            attrs.ta_bg_color = vc.match_color(
1✔
4906
                styling::color_unit::from_str(hd.hd_background_color.pp_value)
2✔
4907
                    .unwrapOrElse([&](const auto& msg) {
1✔
4908
                        errors.emplace_back(
1✔
4909
                            lnav::console::user_message::error(
4910
                                attr_line_t()
1✔
4911
                                    .append_quoted(
2✔
4912
                                        hd.hd_background_color.pp_value)
1✔
4913
                                    .append(" is not a valid color value for "
1✔
4914
                                            "property ")
4915
                                    .append_quoted(lnav::roles::symbol(
2✔
4916
                                        hd.hd_background_color.pp_path
1✔
4917
                                            .to_string())))
4918
                                .with_reason(msg)
2✔
4919
                                .with_snippet(
4920
                                    hd.hd_background_color.to_snippet()));
1✔
4921
                        return styling::color_unit::EMPTY;
1✔
4922
                    }));
4923
        }
4924

4925
        if (hd.hd_underline) {
1,188✔
4926
            attrs |= text_attrs::style::underline;
100✔
4927
        }
4928
        if (hd.hd_blink) {
1,188✔
4929
            attrs |= text_attrs::style::blink;
×
4930
        }
4931

4932
        if (hd.hd_pattern.pp_value != nullptr) {
1,188✔
4933
            this->lf_highlighters.emplace_back(hd.hd_pattern.pp_value);
1,186✔
4934
            this->lf_highlighters.back()
1,186✔
4935
                .with_name(hd_pair.first.to_string())
2,372✔
4936
                .with_attrs(attrs)
1,186✔
4937
                .with_nestable(hd.hd_nestable);
1,186✔
4938
        }
4939
    }
4940
}
4941

4942
void
4943
external_log_format::register_vtabs(
48,287✔
4944
    log_vtab_manager* vtab_manager,
4945
    std::vector<lnav::console::user_message>& errors)
4946
{
4947
    for (auto& elf_search_table : this->elf_search_tables) {
57,682✔
4948
        if (elf_search_table.second.std_pattern.pp_value == nullptr) {
9,395✔
4949
            continue;
1✔
4950
        }
4951

4952
        auto lst = std::make_shared<log_search_table>(
4953
            elf_search_table.second.std_pattern.pp_value,
9,394✔
4954
            elf_search_table.first);
9,394✔
4955
        lst->lst_format = this;
9,394✔
4956
        lst->lst_log_path_glob = elf_search_table.second.std_glob;
9,394✔
4957
        if (elf_search_table.second.std_level != LEVEL_UNKNOWN) {
9,394✔
4958
            lst->lst_log_level = elf_search_table.second.std_level;
3,355✔
4959
        }
4960
        auto errmsg = vtab_manager->register_vtab(lst);
9,394✔
4961
        if (!errmsg.empty()) {
9,394✔
4962
#if 0
4963
            errors.push_back("error:" + this->elf_name.to_string() + ":"
4964
                             + search_iter->first.to_string()
4965
                             + ":unable to register table -- " + errmsg);
4966
#endif
4967
        }
4968
    }
9,394✔
4969
}
48,287✔
4970

4971
bool
4972
external_log_format::match_samples(const std::vector<sample_t>& samples) const
4,091,498✔
4973
{
4974
    for (const auto& sample_iter : samples) {
18,200,443✔
4975
        for (const auto& pat_iter : this->elf_pattern_order) {
38,254,513✔
4976
            auto& pat = *pat_iter;
24,145,568✔
4977

4978
            if (!pat.p_pcre.pp_value) {
24,145,568✔
4979
                continue;
×
4980
            }
4981

4982
            if (pat.p_pcre.pp_value
48,291,136✔
4983
                    ->find_in(sample_iter.s_line.pp_value, PCRE2_NO_UTF_CHECK)
48,291,136✔
4984
                    .ignore_error())
48,291,136✔
4985
            {
4986
                return true;
16,454✔
4987
            }
4988
        }
4989
    }
4990

4991
    return false;
4,075,044✔
4992
}
4993

4994
class external_log_table : public log_format_vtab_impl {
4995
public:
4996
    explicit external_log_table(std::shared_ptr<const log_format> elf)
48,287✔
4997
        : log_format_vtab_impl(elf),
48,287✔
4998
          elt_format(dynamic_cast<const external_log_format*>(elf.get()))
48,287✔
4999
    {
5000
    }
48,287✔
5001

5002
    void get_columns(std::vector<vtab_column>& cols) const override
48,684✔
5003
    {
5004
        const auto& elf = this->elt_format;
48,684✔
5005

5006
        cols.resize(elf->elf_column_count);
48,684✔
5007
        for (const auto& vd : elf->elf_value_def_order) {
494,289✔
5008
            auto type_pair = logline_value_to_sqlite_type(vd->vd_meta.lvm_kind);
445,605✔
5009

5010
            if (!vd->vd_meta.lvm_column.is<logline_value_meta::table_column>())
445,605✔
5011
            {
5012
                continue;
46,312✔
5013
            }
5014

5015
            auto col
5016
                = vd->vd_meta.lvm_column.get<logline_value_meta::table_column>()
399,293✔
5017
                      .value;
399,293✔
5018
            require(0 <= col && col < elf->elf_column_count);
399,293✔
5019

5020
            cols[col].vc_name = vd->vd_meta.lvm_name.get();
399,293✔
5021
            cols[col].vc_type = type_pair.first;
399,293✔
5022
            cols[col].vc_subtype = type_pair.second;
399,293✔
5023
            cols[col].vc_collator = vd->vd_collate;
399,293✔
5024
            cols[col].vc_comment = vd->vd_description;
399,293✔
5025
        }
5026
    }
48,684✔
5027

5028
    void get_foreign_keys(
37,414✔
5029
        std::unordered_set<std::string>& keys_inout) const override
5030
    {
5031
        log_vtab_impl::get_foreign_keys(keys_inout);
37,414✔
5032

5033
        for (const auto& elf_value_def : this->elt_format->elf_value_defs) {
546,622✔
5034
            if (elf_value_def.second->vd_meta.lvm_foreign_key
509,208✔
5035
                || elf_value_def.second->vd_meta.lvm_identifier)
509,208✔
5036
            {
5037
                keys_inout.emplace(elf_value_def.first.to_string());
185,774✔
5038
            }
5039
        }
5040
    }
37,414✔
5041

5042
    bool next(log_cursor& lc, logfile_sub_source& lss) override
3,488✔
5043
    {
5044
        if (lc.is_eof()) {
3,488✔
5045
            return true;
×
5046
        }
5047

5048
        content_line_t cl(lss.at(lc.lc_curr_line));
3,488✔
5049
        auto* lf = lss.find_file_ptr(cl);
3,488✔
5050
        auto lf_iter = lf->begin() + cl;
3,488✔
5051
        if (lf_iter->is_continued()) {
3,488✔
5052
            return false;
×
5053
        }
5054

5055
        if (lf->get_format_name() == this->lfvi_format->get_name()) {
3,488✔
5056
            return true;
3,482✔
5057
        }
5058

5059
        return false;
6✔
5060
    }
5061

5062
    void extract(logfile* lf,
3,404✔
5063
                 uint64_t line_number,
5064
                 string_attrs_t& sa,
5065
                 logline_value_vector& values) override
5066
    {
5067
        auto format = lf->get_format();
3,404✔
5068

5069
        sa.clear();
3,404✔
5070
        format->annotate(lf, line_number, sa, values);
3,404✔
5071
    }
3,404✔
5072

5073
    const external_log_format* elt_format;
5074
    line_range elt_container_body;
5075
};
5076

5077
std::shared_ptr<log_vtab_impl>
5078
external_log_format::get_vtab_impl() const
48,287✔
5079
{
5080
    return std::make_shared<external_log_table>(this->shared_from_this());
48,287✔
5081
}
5082

5083
std::shared_ptr<log_format>
5084
external_log_format::specialized(int fmt_lock)
535✔
5085
{
5086
    auto retval = std::make_shared<external_log_format>(*this);
535✔
5087

5088
    retval->lf_specialized = true;
535✔
5089
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
535✔
5090
        this->jlf_parse_context
5091
            = std::make_shared<yajlpp_parse_context>(this->elf_name);
51✔
5092
        this->jlf_yajl_handle.reset(
51✔
5093
            yajl_alloc(&this->jlf_parse_context->ypc_callbacks,
51✔
5094
                       nullptr,
5095
                       this->jlf_parse_context.get()),
51✔
5096
            yajl_handle_deleter());
5097
        yajl_config(this->jlf_yajl_handle.get(), yajl_dont_validate_strings, 1);
51✔
5098
        this->jlf_attr_line.al_string.reserve(16 * 1024);
51✔
5099
    }
5100

5101
    this->elf_specialized_value_defs_state = *this->elf_value_defs_state;
535✔
5102

5103
    return retval;
1,070✔
5104
}
535✔
5105

5106
log_format::match_name_result
5107
external_log_format::match_name(const std::string& filename)
891,829✔
5108
{
5109
    if (this->elf_filename_pcre.pp_value == nullptr) {
891,829✔
5110
        return name_matched{};
890,378✔
5111
    }
5112

5113
    if (this->elf_filename_pcre.pp_value->find_in(filename)
2,902✔
5114
            .ignore_error()
2,902✔
5115
            .has_value())
1,451✔
5116
    {
5117
        return name_matched{};
247✔
5118
    }
5119

5120
    return name_mismatched{
2,408✔
5121
        this->elf_filename_pcre.pp_value->match_partial(filename),
2,408✔
5122
        this->elf_filename_pcre.pp_value->get_pattern(),
1,204✔
5123
    };
1,204✔
5124
}
5125

5126
auto
5127
external_log_format::value_line_count(scan_batch_context& sbc,
326,145✔
5128
                                      const value_def* vd,
5129
                                      bool top_level,
5130
                                      std::optional<double> val,
5131
                                      const unsigned char* str,
5132
                                      ssize_t len,
5133
                                      yajl_string_props_t* props)
5134
    -> value_line_count_result
5135
{
5136
    value_line_count_result retval;
326,145✔
5137

5138
    if (vd == nullptr) {
326,145✔
5139
        if (this->jlf_hide_extra || !top_level) {
302,324✔
5140
            retval.vlcr_count = 0;
282,849✔
5141
        }
5142

5143
        return retval;
302,324✔
5144
    }
5145

5146
    if (str != nullptr && props != nullptr && !val) {
23,821✔
5147
        auto frag = string_fragment::from_bytes(str, len);
20,983✔
5148
        while (frag.endswith("\n")) {
21,244✔
5149
            frag.pop_back();
261✔
5150
            props->line_feeds -= 1;
261✔
5151
        }
5152
        retval.vlcr_has_ansi |= props->has_ansi;
20,983✔
5153
        retval.vlcr_count += props->line_feeds;
20,983✔
5154
    }
5155

5156
    if (vd->vd_meta.lvm_values_index) {
23,821✔
5157
        auto& lvs = sbc.sbc_value_stats[vd->vd_meta.lvm_values_index.value()];
8,101✔
5158
        if (len > lvs.lvs_width) {
8,101✔
5159
            lvs.lvs_width = len;
4,289✔
5160
        }
5161
        if (val) {
8,101✔
5162
            lvs.add_value(val.value());
182✔
5163
        }
5164
    }
5165

5166
    if (vd->vd_line_format_index) {
23,821✔
5167
        retval.vlcr_line_format_count += 1;
3,989✔
5168
        retval.vlcr_count -= 1;
3,989✔
5169
        retval.vlcr_line_format_index = vd->vd_line_format_index;
3,989✔
5170
    }
5171
    if (vd->vd_meta.is_hidden()) {
23,821✔
5172
        retval.vlcr_count = 0;
3,771✔
5173
        return retval;
3,771✔
5174
    }
5175

5176
    return retval;
20,050✔
5177
}
5178

5179
log_level_t
5180
external_log_format::convert_level(string_fragment sf,
206,491✔
5181
                                   scan_batch_context* sbc) const
5182
{
5183
    auto retval = LEVEL_INFO;
206,491✔
5184

5185
    if (sf.is_valid()) {
206,491✔
5186
        if (sbc != nullptr) {
162,842✔
5187
            auto ssm_res = sbc->sbc_level_cache.lookup(sf);
10,439✔
5188
            if (ssm_res.has_value()) {
10,439✔
5189
                return static_cast<log_level_t>(ssm_res.value());
4,154✔
5190
            }
5191
        }
5192

5193
        if (this->elf_level_patterns.empty()) {
158,688✔
5194
            retval = string2level(sf.data(), sf.length());
34,306✔
5195
        } else {
5196
            for (const auto& elf_level_pattern : this->elf_level_patterns) {
335,175✔
5197
                if (elf_level_pattern.second.lp_pcre.pp_value
615,586✔
5198
                        ->find_in(sf, PCRE2_NO_UTF_CHECK)
615,586✔
5199
                        .ignore_error()
615,586✔
5200
                        .has_value())
307,793✔
5201
                {
5202
                    retval = elf_level_pattern.first;
97,000✔
5203
                    break;
97,000✔
5204
                }
5205
            }
5206
        }
5207

5208
        if (sbc != nullptr
158,688✔
5209
            && sf.length() <= lnav::small_string_map::MAX_KEY_SIZE)
158,688✔
5210
        {
5211
            sbc->sbc_level_cache.insert(sf, retval);
5,582✔
5212
        }
5213
    }
5214

5215
    return retval;
202,337✔
5216
}
5217

5218
logline_value_meta
5219
external_log_format::get_value_meta(intern_string_t field_name,
4,630✔
5220
                                    value_kind_t kind)
5221
{
5222
    const auto iter = this->elf_value_defs.find(field_name);
4,630✔
5223
    if (iter == this->elf_value_defs.end()) {
4,630✔
5224
        auto retval = logline_value_meta(
5225
            field_name, kind, logline_value_meta::external_column{}, this);
390✔
5226

5227
        retval.lvm_hidden = this->jlf_hide_extra;
390✔
5228
        return retval;
390✔
5229
    }
390✔
5230

5231
    auto lvm = iter->second->vd_meta;
4,240✔
5232

5233
    lvm.lvm_kind = kind;
4,240✔
5234
    return lvm;
4,240✔
5235
}
4,240✔
5236

5237
logline_value_meta
5238
external_log_format::get_value_meta(yajlpp_parse_context* ypc,
10,142✔
5239
                                    const value_def* vd,
5240
                                    value_kind_t kind)
5241
{
5242
    if (vd == nullptr) {
10,142✔
5243
        auto retval = logline_value_meta(
5244
            ypc->get_path(), kind, logline_value_meta::external_column{}, this);
683✔
5245

5246
        retval.lvm_hidden = this->jlf_hide_extra;
683✔
5247
        return retval;
683✔
5248
    }
683✔
5249

5250
    auto lvm = vd->vd_meta;
9,459✔
5251

5252
    switch (vd->vd_meta.lvm_kind) {
9,459✔
5253
        case value_kind_t::VALUE_TIMESTAMP:
285✔
5254
            break;
285✔
5255
        default:
9,174✔
5256
            lvm.lvm_kind = kind;
9,174✔
5257
            break;
9,174✔
5258
    }
5259
    return lvm;
9,459✔
5260
}
9,459✔
5261

5262
void
5263
external_log_format::json_append(const log_format_file_state& lffs,
7,600✔
5264
                                 const json_format_element& jfe,
5265
                                 const value_def* vd,
5266
                                 const string_fragment& sf)
5267
{
5268
    if (jfe.jfe_align == json_format_element::align_t::RIGHT) {
7,600✔
5269
        auto sf_width = sf.column_width();
263✔
5270
        if (sf_width < jfe.jfe_min_width) {
263✔
5271
            this->json_append_to_cache(jfe.jfe_min_width - sf_width);
6✔
5272
        } else if (jfe.jfe_auto_width && vd != nullptr
24✔
5273
                   && sf_width
281✔
5274
                       < lffs.lffs_value_stats[vd->vd_meta.lvm_values_index
24✔
5275
                                                   .value()]
24✔
5276
                             .lvs_width)
24✔
5277
        {
5278
            this->json_append_to_cache(
8✔
5279
                lffs.lffs_value_stats[vd->vd_meta.lvm_values_index.value()]
8✔
5280
                    .lvs_width
8✔
5281
                - sf_width);
8✔
5282
        }
5283
    }
5284
    this->json_append_to_cache(sf.data(), sf.length());
7,600✔
5285
    if ((jfe.jfe_align == json_format_element::align_t::LEFT
7,600✔
5286
         || jfe.jfe_align == json_format_element::align_t::NONE)
7,546✔
5287
        && (jfe.jfe_min_width > 0 || jfe.jfe_auto_width))
7,337✔
5288
    {
5289
        auto sf_width = sf.column_width();
1,309✔
5290
        if (sf_width < jfe.jfe_min_width) {
1,309✔
5291
            this->json_append_to_cache(jfe.jfe_min_width - sf_width);
382✔
5292
        } else if (jfe.jfe_auto_width && vd != nullptr
793✔
5293
                   && sf_width
1,720✔
5294
                       < lffs.lffs_value_stats[vd->vd_meta.lvm_values_index
688✔
5295
                                                   .value()]
688✔
5296
                             .lvs_width)
688✔
5297
        {
5298
            this->json_append_to_cache(
276✔
5299
                lffs.lffs_value_stats[vd->vd_meta.lvm_values_index.value()]
276✔
5300
                    .lvs_width
276✔
5301
                - sf_width);
276✔
5302
        }
5303
    }
5304
}
7,600✔
5305

5306
intern_string_t
5307
external_log_format::get_pattern_name(const pattern_locks& pl,
59✔
5308
                                      uint64_t line_number) const
5309
{
5310
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
59✔
5311
        static auto structured = intern_string::lookup("structured");
5312

5313
        return structured;
×
5314
    }
5315
    auto pat_index = pl.pattern_index_for_line(line_number);
59✔
5316
    return this->elf_pattern_order[pat_index]->p_name;
59✔
5317
}
5318

5319
std::string
5320
log_format::get_pattern_path(const pattern_locks& pl,
×
5321
                             uint64_t line_number) const
5322
{
5323
    auto pat_index = pl.pattern_index_for_line(line_number);
×
5324
    return fmt::format(FMT_STRING("builtin ({})"), pat_index);
×
5325
}
5326

5327
intern_string_t
5328
log_format::get_pattern_name(const pattern_locks& pl,
6✔
5329
                             uint64_t line_number) const
5330
{
5331
    char pat_str[128];
5332

5333
    auto pat_index = pl.pattern_index_for_line(line_number);
6✔
5334
    auto to_n_res = fmt::format_to_n(
×
5335
        pat_str, sizeof(pat_str) - 1, FMT_STRING("builtin ({})"), pat_index);
18✔
5336
    pat_str[to_n_res.size] = '\0';
6✔
5337
    return intern_string::lookup(pat_str);
12✔
5338
}
5339

5340
std::shared_ptr<log_format>
5341
log_format::find_root_format(const char* name)
1,352✔
5342
{
5343
    auto& fmts = get_root_formats();
1,352✔
5344
    for (auto& lf : fmts) {
54,489✔
5345
        if (lf->get_name() == name) {
54,489✔
5346
            return lf;
1,352✔
5347
        }
5348
    }
5349
    return nullptr;
×
5350
}
5351

5352
exttm
5353
log_format::tm_for_display(logfile::iterator ll, string_fragment sf)
986✔
5354
{
5355
    auto adjusted_time = ll->get_timeval();
986✔
5356
    exttm retval;
986✔
5357

5358
    retval.et_nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(
986✔
5359
                         std::chrono::microseconds{adjusted_time.tv_usec})
×
5360
                         .count();
986✔
5361
    if (this->lf_timestamp_flags & ETF_NANOS_SET) {
986✔
5362
        timeval actual_tv;
5363
        exttm tm;
5✔
5364
        if (this->lf_date_time.scan(sf.data(),
10✔
5365
                                    sf.length(),
5✔
5366
                                    this->get_timestamp_formats(),
5367
                                    &tm,
5368
                                    actual_tv,
5369
                                    false))
5370
        {
5371
            adjusted_time.tv_usec = actual_tv.tv_usec;
5✔
5372
            retval.et_nsec = tm.et_nsec;
5✔
5373
        }
5374
    }
5375
    gmtime_r(&adjusted_time.tv_sec, &retval.et_tm);
986✔
5376
    retval.et_flags = this->lf_timestamp_flags;
986✔
5377
    if (this->lf_timestamp_flags & ETF_ZONE_SET
986✔
5378
        && this->lf_date_time.dts_zoned_to_local)
896✔
5379
    {
5380
        retval.et_flags &= ~ETF_Z_IS_UTC;
896✔
5381
    }
5382
    retval.et_gmtoff = this->lf_date_time.dts_local_offset_cache;
986✔
5383

5384
    return retval;
1,972✔
5385
}
5386

5387
pattern_for_lines::pattern_for_lines(uint32_t pfl_line, uint32_t pfl_pat_index)
2,985✔
5388
    : pfl_line(pfl_line), pfl_pat_index(pfl_pat_index)
2,985✔
5389
{
5390
}
2,985✔
5391

5392
void
5393
logline_value_stats::merge(const logline_value_stats& other)
15,957✔
5394
{
5395
    if (other.lvs_width > this->lvs_width) {
15,957✔
5396
        this->lvs_width = other.lvs_width;
4,002✔
5397
    }
5398

5399
    if (other.lvs_count == 0) {
15,957✔
5400
        return;
14,807✔
5401
    }
5402

5403
    require(other.lvs_min_value <= other.lvs_max_value);
1,150✔
5404

5405
    if (other.lvs_min_value < this->lvs_min_value) {
1,150✔
5406
        this->lvs_min_value = other.lvs_min_value;
782✔
5407
    }
5408
    if (other.lvs_max_value > this->lvs_max_value) {
1,150✔
5409
        this->lvs_max_value = other.lvs_max_value;
1,078✔
5410
    }
5411
    this->lvs_count += other.lvs_count;
1,150✔
5412
    this->lvs_total += other.lvs_total;
1,150✔
5413
    this->lvs_tdigest.insert(other.lvs_tdigest);
1,150✔
5414
    ensure(this->lvs_count >= 0);
1,150✔
5415
    ensure(this->lvs_min_value <= this->lvs_max_value);
1,150✔
5416
}
5417

5418
void
5419
logline_value_stats::add_value(double value)
31,471✔
5420
{
5421
    if (value < this->lvs_min_value) {
31,471✔
5422
        this->lvs_min_value = value;
1,671✔
5423
    }
5424
    if (value > this->lvs_max_value) {
31,471✔
5425
        this->lvs_max_value = value;
2,389✔
5426
    }
5427
    this->lvs_count += 1;
31,471✔
5428
    this->lvs_total += value;
31,471✔
5429
    this->lvs_tdigest.insert(value);
31,471✔
5430
}
31,471✔
5431

5432
std::vector<logline_value_meta>
5433
external_log_format::get_value_metadata() const
9,394✔
5434
{
5435
    std::vector<logline_value_meta> retval;
9,394✔
5436

5437
    for (const auto& vd : this->elf_value_def_order) {
98,637✔
5438
        retval.emplace_back(vd->vd_meta);
89,243✔
5439
    }
5440

5441
    return retval;
9,394✔
5442
}
×
5443

5444
std::optional<size_t>
5445
external_log_format::stats_index_for_value(const intern_string_t& name) const
73✔
5446
{
5447
    const auto iter = this->elf_value_defs.find(name);
73✔
5448
    if (iter != this->elf_value_defs.end()
73✔
5449
        && iter->second->vd_meta.lvm_values_index)
73✔
5450
    {
5451
        return iter->second->vd_meta.lvm_values_index.value();
73✔
5452
    }
5453

5454
    return std::nullopt;
×
5455
}
5456

5457
std::string
5458
external_log_format::get_pattern_regex(const pattern_locks& pl,
17✔
5459
                                       uint64_t line_number) const
5460
{
5461
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
17✔
5462
        return "";
2✔
5463
    }
5464
    auto pat_index = pl.pattern_index_for_line(line_number);
16✔
5465
    return this->elf_pattern_order[pat_index]->p_pcre.pp_value->get_pattern();
16✔
5466
}
5467

5468
bool
5469
external_log_format::hide_field(const intern_string_t field_name, bool val)
12✔
5470
{
5471
    const auto vd_iter = this->elf_value_defs.find(field_name);
12✔
5472
    if (vd_iter == this->elf_value_defs.end()) {
12✔
5473
        log_warning("field to hide not found: %s.%s",
1✔
5474
                    this->elf_name.c_str(),
5475
                    field_name.c_str());
5476
        return false;
1✔
5477
    }
5478

5479
    vd_iter->second->vd_meta.lvm_user_hidden = val;
11✔
5480
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
11✔
5481
        bool found = false;
2✔
5482

5483
        if (!field_name.to_string_fragment().find('#')) {
2✔
5484
            for (const auto& jfe : this->jlf_line_format) {
18✔
5485
                if (jfe.jfe_value.pp_value == field_name) {
17✔
5486
                    log_debug(
×
5487
                        "hide-field not triggering rebuild since it is in "
5488
                        "line-format: %s.%s",
5489
                        this->elf_name.c_str(),
5490
                        field_name.c_str());
5491
                    found = true;
×
5492
                    break;
×
5493
                }
5494
            }
5495
        }
5496
        if (!found) {
2✔
5497
            log_info("format field %s.%s changed, rebuilding",
2✔
5498
                     this->elf_name.get(),
5499
                     field_name.get());
5500
            this->elf_value_defs_state->vds_generation += 1;
2✔
5501
        }
5502
    }
5503
    return true;
11✔
5504
}
5505

5506
bool
5507
external_log_format::format_changed()
2,776✔
5508
{
5509
    if (this->elf_specialized_value_defs_state.vds_generation
5,552✔
5510
        != this->elf_value_defs_state->vds_generation)
2,776✔
5511
    {
5512
        this->elf_specialized_value_defs_state = *this->elf_value_defs_state;
2✔
5513
        this->jlf_cached_offset = -1;
2✔
5514
        return true;
2✔
5515
    }
5516

5517
    return false;
2,774✔
5518
}
5519

5520
bool
5521
format_tag_def::path_restriction::matches(const char* fn) const
5✔
5522
{
5523
    return fnmatch(this->p_glob.c_str(), fn, 0) == 0;
5✔
5524
}
5525

5526
bool
5527
format_partition_def::path_restriction::matches(const char* fn) const
5✔
5528
{
5529
    return fnmatch(this->p_glob.c_str(), fn, 0) == 0;
5✔
5530
}
5531

5532
int
5533
pattern_locks::pattern_index_for_line(uint64_t line_number) const
6,968✔
5534
{
5535
    if (this->pl_lines.empty()) {
6,968✔
5536
        return -1;
×
5537
    }
5538

5539
    auto iter
5540
        = std::lower_bound(this->pl_lines.cbegin(),
6,968✔
5541
                           this->pl_lines.cend(),
5542
                           line_number,
5543
                           [](const pattern_for_lines& pfl, uint32_t line) {
7,027✔
5544
                               return pfl.pfl_line < line;
7,027✔
5545
                           });
5546

5547
    if (iter == this->pl_lines.end() || iter->pfl_line != line_number) {
6,968✔
5548
        --iter;
6,280✔
5549
    }
5550

5551
    return iter->pfl_pat_index;
6,968✔
5552
}
5553

5554
/* XXX */
5555
#include "log_format_impls.cc"
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc