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

tstack / lnav / 19870100498-2728

02 Dec 2025 06:56PM UTC coverage: 68.872% (+0.04%) from 68.835%
19870100498-2728

push

github

tstack
[timeline] add files and threads

118 of 126 new or added lines in 9 files covered. (93.65%)

458 existing lines in 5 files now uncovered.

51405 of 74639 relevant lines covered (68.87%)

435136.79 hits per line

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

85.36
/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

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

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

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

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

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

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

103
    return *this;
836✔
104
}
105

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

116
    return *this;
362✔
117
}
118

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

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

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

148
    return *this;
362✔
149
}
150

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

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

164
    return *this;
474✔
165
}
166

167
void
168
log_level_stats::update_msg_count(log_level_t lvl, int32_t amount)
37,119✔
169
{
170
    switch (lvl) {
37,119✔
171
        case LEVEL_FATAL:
3,082✔
172
        case LEVEL_CRITICAL:
173
        case LEVEL_ERROR:
174
            this->lls_error_count += amount;
3,082✔
175
            break;
3,082✔
176
        case LEVEL_WARNING:
196✔
177
            this->lls_warning_count += amount;
196✔
178
            break;
196✔
179
        default:
33,841✔
180
            break;
33,841✔
181
    }
182
    this->lls_total_count += amount;
37,119✔
183
}
37,119✔
184

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

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

210
    return retval;
11,470✔
211
}
212

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

242
    return retval;
12,163✔
243
}
244

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

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

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

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

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

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

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

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

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

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

327
    return retval;
1,023✔
328
}
×
329

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

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

371
    return retval;
38✔
372
}
373

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

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

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

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

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

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

400
        last = next + 1;
×
401
    }
402

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

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

413
    return retval;
×
414
}
415

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

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

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

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

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

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

476
        case value_kind_t::VALUE_UNKNOWN:
×
477
        case value_kind_t::VALUE__MAX:
478
            ensure(0);
×
479
            break;
480
    }
481
}
640,936✔
482

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

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

505
    switch (this->lv_meta.lvm_kind) {
9,985✔
506
        case value_kind_t::VALUE_NULL:
15✔
507
            return "null";
30✔
508

509
        case value_kind_t::VALUE_JSON:
9,419✔
510
        case value_kind_t::VALUE_XML:
511
        case value_kind_t::VALUE_STRUCT:
512
        case value_kind_t::VALUE_TEXT:
513
        case value_kind_t::VALUE_TIMESTAMP:
514
            if (this->lv_str) {
9,419✔
515
                return this->lv_str.value();
1,418✔
516
            }
517
            if (this->lv_frag.empty()) {
8,001✔
518
                return this->lv_intern_string.to_string();
47✔
519
            }
520
            return this->lv_frag.to_string();
7,954✔
521

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

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

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

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

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

571
    return {buffer};
1,076✔
572
}
573

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

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

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

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

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

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

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

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

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

651
const char*
652
logline_value::text_value() const
68,530✔
653
{
654
    if (this->lv_str) {
68,530✔
655
        return this->lv_str->c_str();
159✔
656
    }
657
    if (this->lv_frag.empty()) {
68,371✔
658
        if (this->lv_intern_string.empty()) {
15✔
659
            return "";
15✔
660
        }
661
        return this->lv_intern_string.get();
×
662
    }
663
    return this->lv_frag.data();
68,356✔
664
}
665

666
size_t
667
logline_value::text_length() const
68,563✔
668
{
669
    if (this->lv_str) {
68,563✔
670
        return this->lv_str->size();
159✔
671
    }
672
    if (this->lv_frag.empty()) {
68,404✔
673
        return this->lv_intern_string.size();
15✔
674
    }
675
    return this->lv_frag.length();
68,389✔
676
}
677

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

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

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

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

711
    return *this;
406✔
712
}
713

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

716
std::vector<std::shared_ptr<log_format>>&
717
log_format::get_root_formats()
17,423✔
718
{
719
    return lf_root_formats;
17,423✔
720
}
721

722
void
723
external_log_format::update_op_description(
4,919✔
724
    const std::vector<opid_descriptors*>& desc_defs_vec,
725
    log_op_description& lod,
726
    const pattern* fpat,
727
    const lnav::pcre2pp::match_data& md)
728
{
729
    std::optional<std::string> desc_elem_str;
4,919✔
730
    if (!lod.lod_index) {
4,919✔
731
        for (const auto& desc_defs : desc_defs_vec) {
2,959✔
732
            if (lod.lod_index) {
1,238✔
733
                break;
26✔
734
            }
735
            for (const auto& desc_def : *desc_defs->od_descriptors) {
1,520✔
736
                auto desc_field_index_iter = fpat->p_value_name_to_index.find(
1,310✔
737
                    desc_def.od_field.pp_value);
1,310✔
738

739
                if (desc_field_index_iter == fpat->p_value_name_to_index.end())
1,310✔
740
                {
741
                    continue;
43✔
742
                }
743

744
                auto desc_cap_opt = md[desc_field_index_iter->second];
1,306✔
745
                if (!desc_cap_opt) {
1,306✔
746
                    continue;
39✔
747
                }
748

749
                desc_elem_str = desc_def.matches(desc_cap_opt.value());
1,267✔
750
                if (desc_elem_str) {
1,267✔
751
                    lod.lod_index = desc_defs->od_index;
1,002✔
752
                    break;
1,002✔
753
                }
754
            }
755
        }
756
    }
757
    if (lod.lod_index) {
4,919✔
758
        const auto& desc_def_v
759
            = *desc_defs_vec[lod.lod_index.value()]->od_descriptors;
4,174✔
760
        auto& desc_v = lod.lod_elements;
4,174✔
761

762
        if (desc_def_v.size() == desc_v.size()
4,174✔
763
            || (this->elf_opid_field.empty() && !desc_v.empty()))
4,174✔
764
        {
765
            return;
3,172✔
766
        }
767
        for (size_t desc_def_index = 0; desc_def_index < desc_def_v.size();
2,857✔
768
             desc_def_index++)
769
        {
770
            const auto& desc_def = desc_def_v[desc_def_index];
1,855✔
771
            auto found_desc = desc_v.value_for(desc_def_index);
1,855✔
772
            auto desc_field_index_iter
773
                = fpat->p_value_name_to_index.find(desc_def.od_field.pp_value);
1,855✔
774

775
            if (desc_field_index_iter == fpat->p_value_name_to_index.end()) {
1,855✔
776
                continue;
35✔
777
            }
778
            auto desc_cap_opt = md[desc_field_index_iter->second];
1,855✔
779
            if (!desc_cap_opt) {
1,855✔
780
                continue;
35✔
781
            }
782

783
            if (!desc_elem_str) {
1,820✔
784
                desc_elem_str = desc_def.matches(desc_cap_opt.value());
818✔
785
            }
786
            if (desc_elem_str) {
1,820✔
787
                if (!found_desc) {
1,817✔
788
                    desc_v.insert(desc_def_index, desc_elem_str.value());
1,817✔
789
                } else if (!desc_elem_str->empty()) {
×
790
                    found_desc.value()->append(desc_def.od_joiner);
×
791
                    found_desc.value()->append(desc_elem_str.value());
×
792
                }
793
            }
794
            desc_elem_str = std::nullopt;
1,820✔
795
        }
796
    }
797
}
4,919✔
798

799
void
800
external_log_format::update_op_description(
2,438✔
801
    const std::vector<opid_descriptors*>& desc_defs_vec,
802
    log_op_description& lod)
803
{
804
    std::optional<std::string> desc_elem_str;
2,438✔
805
    if (!lod.lod_index) {
2,438✔
806
        for (const auto& desc_defs : desc_defs_vec) {
2,447✔
807
            if (lod.lod_index) {
15✔
808
                break;
×
809
            }
810
            for (const auto& desc_def : *desc_defs->od_descriptors) {
15✔
811
                auto desc_cap_iter
812
                    = this->lf_desc_captures.find(desc_def.od_field.pp_value);
15✔
813

814
                if (desc_cap_iter == this->lf_desc_captures.end()) {
15✔
815
                    continue;
×
816
                }
817
                desc_elem_str = desc_def.matches(desc_cap_iter->second);
15✔
818
                if (desc_elem_str) {
15✔
819
                    lod.lod_index = desc_defs->od_index;
15✔
820
                    break;
15✔
821
                }
822
            }
823
        }
824
    }
825
    if (lod.lod_index) {
2,438✔
826
        const auto& desc_def_v
827
            = *desc_defs_vec[lod.lod_index.value()]->od_descriptors;
21✔
828
        auto& desc_v = lod.lod_elements;
21✔
829

830
        if (desc_def_v.size() == desc_v.size()
21✔
831
            || (this->elf_opid_field.empty() && !desc_v.empty()))
21✔
832
        {
833
            return;
6✔
834
        }
835
        for (size_t desc_def_index = 0; desc_def_index < desc_def_v.size();
45✔
836
             desc_def_index++)
837
        {
838
            const auto& desc_def = desc_def_v[desc_def_index];
30✔
839
            auto found_desc = desc_v.value_for(desc_def_index);
30✔
840
            auto desc_cap_iter
841
                = this->lf_desc_captures.find(desc_def.od_field.pp_value);
30✔
842
            if (desc_cap_iter == this->lf_desc_captures.end()) {
30✔
843
                continue;
×
844
            }
845

846
            if (!desc_elem_str) {
30✔
847
                desc_elem_str = desc_def.matches(desc_cap_iter->second);
15✔
848
            }
849
            if (desc_elem_str) {
30✔
850
                if (!found_desc) {
30✔
851
                    desc_v.insert(desc_def_index, desc_elem_str.value());
30✔
852
                } else if (!desc_elem_str->empty()) {
×
853
                    found_desc.value()->append(desc_def.od_joiner);
×
854
                    found_desc.value()->append(desc_elem_str.value());
×
855
                }
856
            }
857
            desc_elem_str = std::nullopt;
30✔
858
        }
859
    }
860
}
2,438✔
861

862
static bool
863
next_format(
2,300,366✔
864
    const std::vector<std::shared_ptr<external_log_format::pattern>>& patterns,
865
    int& index,
866
    int& locked_index)
867
{
868
    bool retval = true;
2,300,366✔
869

870
    if (locked_index == -1) {
2,300,366✔
871
        index += 1;
2,293,112✔
872
        if (index >= (int) patterns.size()) {
2,293,112✔
873
            retval = false;
694,658✔
874
        }
875
    } else if (index == locked_index) {
7,254✔
876
        retval = false;
1✔
877
    } else {
878
        index = locked_index;
7,253✔
879
    }
880

881
    return retval;
2,300,366✔
882
}
883

884
bool
885
log_format::next_format(const pcre_format* fmt, int& index, int& locked_index)
179,634✔
886
{
887
    bool retval = true;
179,634✔
888

889
    if (locked_index == -1) {
179,634✔
890
        index += 1;
179,463✔
891
        if (fmt[index].name == nullptr) {
179,463✔
892
            retval = false;
10,113✔
893
        }
894
    } else if (index == locked_index) {
171✔
895
        retval = false;
31✔
896
    } else {
897
        index = locked_index;
140✔
898
    }
899

900
    return retval;
179,634✔
901
}
902

903
const char*
904
log_format::log_scanf(scan_batch_context& sbc,
12,525✔
905
                      uint32_t line_number,
906
                      string_fragment line,
907
                      const pcre_format* fmt,
908
                      const char* time_fmt[],
909
                      exttm* tm_out,
910
                      timeval* tv_out,
911

912
                      string_fragment* ts_out,
913
                      std::optional<string_fragment>* level_out)
914
{
915
    int curr_fmt = -1;
12,525✔
916
    const char* retval = nullptr;
12,525✔
917
    bool done = false;
12,525✔
918
    int pat_index = sbc.sbc_pattern_locks.last_pattern_index();
12,525✔
919

920
    while (!done && next_format(fmt, curr_fmt, pat_index)) {
182,015✔
921
        thread_local auto md = lnav::pcre2pp::match_data::unitialized();
169,490✔
922

923
        auto match_res = fmt[curr_fmt]
169,490✔
924
                             .pcre->capture_from(line)
169,490✔
925
                             .into(md)
169,490✔
926
                             .matches(PCRE2_NO_UTF_CHECK)
338,980✔
927
                             .ignore_error();
169,490✔
928
        if (!match_res) {
169,490✔
929
            retval = nullptr;
145,768✔
930
        } else {
931
            auto ts = md[fmt[curr_fmt].pf_timestamp_index];
23,722✔
932

933
            retval = this->lf_date_time.scan(
23,722✔
934
                ts->data(), ts->length(), nullptr, tm_out, *tv_out);
23,722✔
935

936
            if (retval == nullptr) {
23,722✔
937
                auto ls = this->lf_date_time.unlock();
21,341✔
938
                retval = this->lf_date_time.scan(
21,341✔
939
                    ts->data(), ts->length(), nullptr, tm_out, *tv_out);
21,341✔
940
                if (retval != nullptr) {
21,341✔
941
                    auto old_flags
×
942
                        = this->lf_timestamp_flags & DATE_TIME_SET_FLAGS;
×
943
                    auto new_flags = tm_out->et_flags & DATE_TIME_SET_FLAGS;
×
944

945
                    // It is unlikely a valid timestamp would lose much
946
                    // precision.
947
                    if (new_flags != old_flags) {
×
948
                        retval = nullptr;
×
949
                    }
950
                }
951
                if (retval == nullptr) {
21,341✔
952
                    this->lf_date_time.relock(ls);
21,341✔
953
                } else {
954
                    log_debug(
×
955
                        "%d: changed time format to '%s' due to %.*s",
956
                        line_number,
957
                        PTIMEC_FORMAT_STR[this->lf_date_time.dts_fmt_lock],
958
                        ts->length(),
959
                        ts->data());
960
                }
961
            }
962

963
            if (retval) {
23,722✔
964
                *ts_out = ts.value();
2,381✔
965
                if (md[2]) {
2,381✔
966
                    *level_out = md[2];
246✔
967
                } else {
968
                    *level_out = line.substr(md[0]->sf_end);
2,135✔
969
                }
970
                if (curr_fmt != pat_index) {
2,381✔
971
                    uint32_t lock_line;
972

973
                    if (sbc.sbc_pattern_locks.empty()) {
2,272✔
974
                        lock_line = 0;
2,272✔
975
                    } else {
976
                        lock_line = line_number;
×
977
                    }
978

979
                    sbc.sbc_pattern_locks.pl_lines.emplace_back(lock_line,
2,272✔
980
                                                                curr_fmt);
981
                }
982
                this->lf_timestamp_flags = tm_out->et_flags;
2,381✔
983
                done = true;
2,381✔
984
            }
985
        }
986
    }
987

988
    return retval;
12,525✔
989
}
990

991
void
992
log_format::annotate(logfile* lf,
37,510✔
993
                     uint64_t line_number,
994
                     string_attrs_t& sa,
995
                     logline_value_vector& values) const
996
{
997
    if (lf != nullptr && !values.lvv_opid_value) {
37,510✔
998
        const auto& bm = lf->get_bookmark_metadata();
2,896✔
999
        auto bm_iter = bm.find(line_number);
2,896✔
1000
        if (bm_iter != bm.end() && !bm_iter->second.bm_opid.empty()) {
2,896✔
1001
            values.lvv_opid_value = bm_iter->second.bm_opid;
6✔
1002
            values.lvv_opid_provenance
1003
                = logline_value_vector::opid_provenance::user;
6✔
1004
        }
1005
    }
1006
}
37,510✔
1007

1008
void
1009
log_format::check_for_new_year(std::vector<logline>& dst,
1,466✔
1010
                               exttm etm,
1011
                               timeval log_tv) const
1012
{
1013
    if (dst.empty()) {
1,466✔
1014
        return;
213✔
1015
    }
1016

1017
    time_t diff
1018
        = dst.back().get_time<std::chrono::seconds>().count() - log_tv.tv_sec;
1,253✔
1019
    int off_year = 0, off_month = 0, off_day = 0, off_hour = 0;
1,253✔
1020
    bool do_change = true;
1,253✔
1021

1022
    if (diff <= 0) {
1,253✔
1023
        return;
1,194✔
1024
    }
1025
    if ((etm.et_flags & ETF_MONTH_SET) && diff >= (24 * 60 * 60)) {
59✔
1026
        off_year = 1;
10✔
1027
    } else if (diff >= (24 * 60 * 60)) {
49✔
1028
        off_month = 1;
2✔
1029
    } else if (!(etm.et_flags & ETF_DAY_SET) && (diff >= (60 * 60))) {
47✔
1030
        off_day = 1;
1✔
1031
    } else if (!(etm.et_flags & ETF_HOUR_SET) && (diff >= 60)) {
46✔
1032
        off_hour = 1;
4✔
1033
    } else {
1034
        do_change = false;
42✔
1035
    }
1036

1037
    if (!do_change) {
59✔
1038
        return;
42✔
1039
    }
1040
    log_debug("%zu:detected time rollover; offsets=%d %d %d %d",
17✔
1041
              dst.size(),
1042
              off_year,
1043
              off_month,
1044
              off_day,
1045
              off_hour);
1046
    for (auto& ll : dst) {
66✔
1047
        time_t ot = ll.get_time<std::chrono::seconds>().count();
49✔
1048
        struct tm otm;
1049

1050
        gmtime_r(&ot, &otm);
49✔
1051
        otm.tm_yday = -1;
49✔
1052
        if (otm.tm_year < off_year) {
49✔
1053
            otm.tm_year = 0;
×
1054
        } else {
1055
            otm.tm_year -= off_year;
49✔
1056
        }
1057
        otm.tm_mon -= off_month;
49✔
1058
        if (otm.tm_mon < 0) {
49✔
1059
            otm.tm_mon += 12;
2✔
1060
        }
1061
        auto new_time = tm2sec(&otm);
49✔
1062
        if (new_time == -1) {
49✔
1063
            continue;
×
1064
        }
1065
        new_time -= (off_day * 24 * 60 * 60) + (off_hour * 60 * 60);
49✔
1066
        auto old_sub = ll.get_subsecond_time<std::chrono::microseconds>();
49✔
1067
        ll.set_time(std::chrono::seconds{new_time});
49✔
1068
        ll.set_subsecond_time(old_sub);
49✔
1069
    }
1070
}
1071

1072
/*
1073
 * XXX This needs some cleanup.
1074
 */
1075
struct json_log_userdata {
1076
    json_log_userdata(shared_buffer_ref& sbr, scan_batch_context* sbc)
12,147✔
1077
        : jlu_shared_buffer(sbr), jlu_batch_context(sbc)
24,294✔
1078
    {
1079
    }
12,147✔
1080

1081
    const external_log_format::value_def* get_field_def(
314,692✔
1082
        yajlpp_parse_context* ypc)
1083
    {
1084
        const auto field_frag = ypc->get_path_as_string_fragment();
314,692✔
1085
        auto* format = this->jlu_format;
314,692✔
1086

1087
        if (this->jlu_read_order_index < format->elf_value_def_read_order.size()
314,692✔
1088
            && format->elf_value_def_read_order[this->jlu_read_order_index]
423,753✔
1089
                    .first
1090
                == field_frag)
109,061✔
1091
        {
1092
            return format
1093
                ->elf_value_def_read_order[this->jlu_read_order_index++]
104,336✔
1094
                .second;
104,336✔
1095
        }
1096

1097
        format->elf_value_def_read_order.resize(this->jlu_read_order_index);
210,356✔
1098
        auto vd_iter = format->elf_value_def_frag_map.find(field_frag);
210,356✔
1099
        if (vd_iter != format->elf_value_def_frag_map.end()) {
210,356✔
1100
            format->elf_value_def_read_order.emplace_back(vd_iter->first,
182,012✔
1101
                                                          vd_iter->second);
182,012✔
1102
            this->jlu_read_order_index += 1;
182,012✔
1103
            return vd_iter->second;
182,012✔
1104
        }
1105

1106
        auto owned_frag = field_frag.to_owned(format->elf_allocator);
28,344✔
1107
        format->elf_value_def_frag_map[owned_frag] = nullptr;
28,344✔
1108
        format->elf_value_def_read_order.emplace_back(owned_frag, nullptr);
28,344✔
1109
        this->jlu_read_order_index += 1;
28,344✔
1110
        return nullptr;
28,344✔
1111
    }
1112

1113
    void add_sub_lines_for(const external_log_format::value_def* vd,
223,576✔
1114
                           bool top_level,
1115
                           std::optional<double> val,
1116
                           const unsigned char* str,
1117
                           ssize_t len,
1118
                           yajl_string_props_t* props)
1119
    {
1120
        auto res = this->jlu_format->value_line_count(
223,576✔
1121
            *this->jlu_batch_context, vd, top_level, val, str, len, props);
223,576✔
1122
        this->jlu_has_ansi |= res.vlcr_has_ansi;
223,576✔
1123
        if (!res.vlcr_valid_utf) {
223,576✔
1124
            this->jlu_valid_utf = false;
×
1125
        }
1126
        this->jlu_sub_line_count += res.vlcr_count;
223,576✔
1127
        this->jlu_quality += res.vlcr_line_format_count;
223,576✔
1128
        if (res.vlcr_line_format_index) {
223,576✔
1129
            this->jlu_format_hits[res.vlcr_line_format_index.value()] = true;
3,205✔
1130
        }
1131
    }
223,576✔
1132

1133
    external_log_format* jlu_format{nullptr};
1134
    const logline* jlu_line{nullptr};
1135
    logline* jlu_base_line{nullptr};
1136
    int jlu_sub_line_count{1};
1137
    bool jlu_has_ansi{false};
1138
    bool jlu_valid_utf{true};
1139
    yajl_handle jlu_handle{nullptr};
1140
    const char* jlu_line_value{nullptr};
1141
    size_t jlu_line_size{0};
1142
    size_t jlu_sub_start{0};
1143
    uint32_t jlu_quality{0};
1144
    uint32_t jlu_strikes{0};
1145
    std::vector<bool> jlu_format_hits;
1146
    shared_buffer_ref& jlu_shared_buffer;
1147
    scan_batch_context* jlu_batch_context;
1148
    std::optional<string_fragment> jlu_opid_frag;
1149
    std::optional<string_fragment> jlu_opid_desc_frag;
1150
    std::optional<string_fragment> jlu_tid_frag;
1151
    std::optional<int64_t> jlu_tid_number;
1152
    std::optional<std::string> jlu_subid;
1153
    hasher jlu_opid_hasher;
1154
    std::chrono::microseconds jlu_duration{0};
12,147✔
1155
    exttm jlu_exttm;
1156
    size_t jlu_read_order_index{0};
1157
    subline_options jlu_subline_opts;
1158
};
1159

1160
static int read_json_field(yajlpp_parse_context* ypc,
1161
                           const unsigned char* str,
1162
                           size_t len,
1163
                           yajl_string_props_t*);
1164

1165
static int
1166
read_json_null(yajlpp_parse_context* ypc)
3,264✔
1167
{
1168
    json_log_userdata* jlu = (json_log_userdata*) ypc->ypc_userdata;
3,264✔
1169
    const auto* vd = jlu->get_field_def(ypc);
3,264✔
1170

1171
    jlu->add_sub_lines_for(
6,528✔
1172
        vd, ypc->is_level(1), std::nullopt, nullptr, -1, nullptr);
3,264✔
1173

1174
    return 1;
3,264✔
1175
}
1176

1177
static int
1178
read_json_bool(yajlpp_parse_context* ypc, int val)
15,538✔
1179
{
1180
    json_log_userdata* jlu = (json_log_userdata*) ypc->ypc_userdata;
15,538✔
1181
    const auto* vd = jlu->get_field_def(ypc);
15,538✔
1182

1183
    jlu->add_sub_lines_for(
31,076✔
1184
        vd, ypc->is_level(1), std::nullopt, nullptr, -1, nullptr);
15,538✔
1185

1186
    return 1;
15,538✔
1187
}
1188

1189
static int
1190
read_json_number(yajlpp_parse_context* ypc,
25,000✔
1191
                 const char* numberVal,
1192
                 size_t numberLen)
1193
{
1194
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
25,000✔
1195
    auto number_frag = string_fragment::from_bytes(numberVal, numberLen);
25,000✔
1196
    std::optional<double> val;
25,000✔
1197

1198
    intern_string_t field_name;
25,000✔
1199
    const auto* vd = jlu->get_field_def(ypc);
25,000✔
1200
    if (vd != nullptr) {
25,000✔
1201
        field_name = vd->vd_meta.lvm_name;
868✔
1202
    }
1203

1204
    if (field_name.empty()) {
25,000✔
1205
    } else if (jlu->jlu_format->lf_timestamp_field == field_name) {
868✔
1206
        long long divisor = jlu->jlu_format->elf_timestamp_divisor;
113✔
1207
        auto scan_res = scn::scan_value<double>(number_frag.to_string_view());
113✔
1208
        if (!scan_res) {
113✔
1209
            log_error("invalid number %.*s", (int) numberLen, numberVal);
×
1210
            return 0;
×
1211
        }
1212
        auto ts_val = scan_res.value().value();
113✔
1213
        timeval tv;
1214
        tv.tv_sec = ts_val / divisor;
113✔
1215
        tv.tv_usec = fmod(ts_val, divisor) * (1000000.0 / divisor);
113✔
1216
        jlu->jlu_format->lf_date_time.to_localtime(tv.tv_sec, jlu->jlu_exttm);
113✔
1217
        tv.tv_sec = tm2sec(&jlu->jlu_exttm.et_tm);
113✔
1218
        jlu->jlu_exttm.et_gmtoff
1219
            = jlu->jlu_format->lf_date_time.dts_local_offset_cache;
113✔
1220
        jlu->jlu_exttm.et_flags
113✔
1221
            |= ETF_MACHINE_ORIENTED | ETF_SUB_NOT_IN_FORMAT | ETF_ZONE_SET;
113✔
1222
        if (divisor == 1000) {
113✔
1223
            jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
17✔
1224
        } else {
1225
            jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
96✔
1226
        }
1227
        jlu->jlu_exttm.et_nsec = tv.tv_usec * 1000;
113✔
1228
        jlu->jlu_base_line->set_time(tv);
113✔
1229
    } else if (jlu->jlu_format->lf_subsecond_field == field_name) {
755✔
1230
        auto scan_res = scn::scan_value<double>(number_frag.to_string_view());
3✔
1231
        if (!scan_res) {
3✔
1232
            log_error("invalid number %.*s", (int) numberLen, numberVal);
×
1233
            return 0;
×
1234
        }
1235
        auto ts_val = scan_res.value().value();
3✔
1236

1237
        uint64_t millis = 0;
3✔
1238
        jlu->jlu_exttm.et_flags &= ~(ETF_MICROS_SET | ETF_MILLIS_SET);
3✔
1239
        switch (jlu->jlu_format->lf_subsecond_unit.value()) {
3✔
1240
            case log_format::subsecond_unit::milli:
×
1241
                millis = ts_val;
×
1242
                jlu->jlu_exttm.et_nsec = ts_val * 1000000;
×
1243
                jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
×
1244
                break;
×
1245
            case log_format::subsecond_unit::micro:
×
1246
                millis = std::chrono::duration_cast<std::chrono::milliseconds>(
×
1247
                             std::chrono::microseconds((int64_t) ts_val))
×
1248
                             .count();
×
1249
                jlu->jlu_exttm.et_nsec = ts_val * 1000;
×
1250
                jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
×
1251
                break;
×
1252
            case log_format::subsecond_unit::nano:
3✔
1253
                millis = std::chrono::duration_cast<std::chrono::milliseconds>(
3✔
1254
                             std::chrono::nanoseconds((int64_t) ts_val))
3✔
1255
                             .count();
3✔
1256
                jlu->jlu_exttm.et_nsec = ts_val;
3✔
1257
                jlu->jlu_exttm.et_flags |= ETF_NANOS_SET;
3✔
1258
                break;
3✔
1259
        }
1260
        jlu->jlu_exttm.et_flags |= ETF_SUB_NOT_IN_FORMAT;
3✔
1261
        jlu->jlu_base_line->set_subsecond_time(
3✔
1262
            std::chrono::milliseconds(millis));
1263
    } else if (jlu->jlu_format->elf_level_field == field_name) {
752✔
1264
        if (jlu->jlu_format->elf_level_pairs.empty()) {
428✔
1265
            jlu->jlu_base_line->set_level(jlu->jlu_format->convert_level(
266✔
1266
                number_frag, jlu->jlu_batch_context));
1267
        } else {
1268
            auto scan_res
1269
                = scn::scan_int<int64_t>(number_frag.to_string_view());
162✔
1270
            if (!scan_res) {
162✔
1271
                log_error("invalid number %.*s", (int) numberLen, numberVal);
×
1272
                return 0;
×
1273
            }
1274
            auto level_int = scan_res.value().value();
162✔
1275

1276
            for (const auto& pair : jlu->jlu_format->elf_level_pairs) {
593✔
1277
                if (pair.first == level_int) {
531✔
1278
                    jlu->jlu_base_line->set_level(pair.second);
100✔
1279
                    break;
100✔
1280
                }
1281
            }
1282
        }
1283
    } else if (vd != nullptr) {
324✔
1284
        if (jlu->jlu_format->elf_thread_id_field == field_name) {
324✔
1285
            auto& sbc = *jlu->jlu_batch_context;
102✔
1286
            auto tid_iter = sbc.sbc_tids.ltis_tid_ranges.find(number_frag);
102✔
1287
            if (tid_iter == sbc.sbc_tids.ltis_tid_ranges.end()) {
102✔
1288
                jlu->jlu_tid_frag = number_frag.to_owned(sbc.sbc_allocator);
58✔
1289
            } else {
1290
                jlu->jlu_tid_frag = tid_iter->first;
44✔
1291
            }
1292
        }
1293
        if ((vd->vd_meta.lvm_kind == value_kind_t::VALUE_INTEGER
324✔
1294
             || vd->vd_meta.lvm_kind == value_kind_t::VALUE_FLOAT)
126✔
1295
            && !vd->vd_meta.lvm_foreign_key && !vd->vd_meta.lvm_identifier)
216✔
1296
        {
1297
            auto scan_res
1298
                = scn::scan_value<double>(number_frag.to_string_view());
168✔
1299
            if (!scan_res) {
168✔
1300
                log_error("invalid number %.*s", (int) numberLen, numberVal);
×
1301
                return 0;
×
1302
            }
1303
            val = scan_res.value().value();
168✔
1304
            if (jlu->jlu_format->elf_duration_field == field_name) {
168✔
1305
                jlu->jlu_duration = std::chrono::microseconds(
×
1306
                    static_cast<int64_t>(val.value() * 1000000));
18✔
1307
            }
1308
        }
1309
    }
1310

1311
    jlu->add_sub_lines_for(vd,
25,000✔
1312
                           ypc->is_level(1),
25,000✔
1313
                           val,
1314
                           (const unsigned char*) numberVal,
1315
                           numberLen,
1316
                           nullptr);
1317

1318
    return 1;
25,000✔
1319
}
1320

1321
static int
1322
json_array_start(void* ctx)
49,630✔
1323
{
1324
    auto* ypc = (yajlpp_parse_context*) ctx;
49,630✔
1325
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
49,630✔
1326

1327
    if (ypc->ypc_path_index_stack.size() == 2) {
49,630✔
1328
        const auto* vd = jlu->get_field_def(ypc);
15,726✔
1329

1330
        jlu->add_sub_lines_for(vd, true, std::nullopt, nullptr, -1, nullptr);
15,726✔
1331
        jlu->jlu_sub_start = yajl_get_bytes_consumed(jlu->jlu_handle) - 1;
15,726✔
1332
    }
1333

1334
    return 1;
49,630✔
1335
}
1336

1337
static int
1338
json_array_start_const(void* ctx)
13,373✔
1339
{
1340
    auto* ypc = (yajlpp_parse_context*) ctx;
13,373✔
1341
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
13,373✔
1342

1343
    if (ypc->ypc_path_index_stack.size() == 2) {
13,373✔
1344
        jlu->jlu_sub_start = yajl_get_bytes_consumed(jlu->jlu_handle) - 1;
3,633✔
1345
    }
1346

1347
    return 1;
13,373✔
1348
}
1349

1350
static int
1351
json_array_end(void* ctx)
13,353✔
1352
{
1353
    auto* ypc = (yajlpp_parse_context*) ctx;
13,353✔
1354
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
13,353✔
1355

1356
    if (ypc->ypc_path_index_stack.size() == 1) {
13,353✔
1357
        const intern_string_t field_name = ypc->get_path_fragment_i(0);
3,627✔
1358
        size_t sub_end = yajl_get_bytes_consumed(jlu->jlu_handle);
3,627✔
1359
        auto json_frag = string_fragment::from_byte_range(
3,627✔
1360
            jlu->jlu_shared_buffer.get_data(), jlu->jlu_sub_start, sub_end);
3,627✔
1361
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
3,627✔
1362
            jlu->jlu_format->get_value_meta(field_name,
7,254✔
1363
                                            value_kind_t::VALUE_JSON),
1364
            json_frag);
1365
        if (field_name == jlu->jlu_format->elf_opid_field) {
3,627✔
1366
            jlu->jlu_opid_desc_frag = json_frag;
32✔
1367
        }
1368
    }
1369

1370
    return 1;
13,353✔
1371
}
1372

1373
static int
1374
read_array_end(void* ctx)
49,420✔
1375
{
1376
    auto* ypc = (yajlpp_parse_context*) ctx;
49,420✔
1377
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
49,420✔
1378

1379
    if (ypc->ypc_path_index_stack.size() == 1) {
49,420✔
1380
        const intern_string_t field_name = ypc->get_path_fragment_i(0);
15,699✔
1381
        size_t sub_end = yajl_get_bytes_consumed(jlu->jlu_handle);
15,699✔
1382
        auto json_frag = string_fragment::from_byte_range(
15,699✔
1383
            jlu->jlu_shared_buffer.get_data(), jlu->jlu_sub_start, sub_end);
15,699✔
1384
        if (field_name == jlu->jlu_format->elf_opid_field) {
15,699✔
1385
            jlu->jlu_opid_desc_frag = json_frag;
2,253✔
1386
        }
1387
    }
1388

1389
    return 1;
49,420✔
1390
}
1391

1392
static const json_path_container json_log_handlers = {
1393
    yajlpp::pattern_property_handler("\\w+")
1394
        .add_cb(read_json_null)
1395
        .add_cb(read_json_bool)
1396
        .add_cb(read_json_number)
1397
        .add_cb(read_json_field),
1398
};
1399

1400
static int rewrite_json_field(yajlpp_parse_context* ypc,
1401
                              const unsigned char* str,
1402
                              size_t len,
1403
                              yajl_string_props_t*);
1404

1405
static int
1406
rewrite_json_null(yajlpp_parse_context* ypc)
1,957✔
1407
{
1408
    auto jlu = (json_log_userdata*) ypc->ypc_userdata;
1,957✔
1409
    const auto* vd = jlu->get_field_def(ypc);
1,957✔
1410

1411
    if (!ypc->is_level(1) && vd == nullptr) {
1,957✔
1412
        return 1;
1,957✔
1413
    }
1414
    jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
×
1415
        jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_NULL));
×
1416

1417
    return 1;
×
1418
}
1419

1420
static int
1421
rewrite_json_bool(yajlpp_parse_context* ypc, int val)
8,809✔
1422
{
1423
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
8,809✔
1424
    const auto* vd = jlu->get_field_def(ypc);
8,809✔
1425

1426
    if (!ypc->is_level(1) && vd == nullptr) {
8,809✔
1427
        return 1;
7,861✔
1428
    }
1429
    jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
948✔
1430
        jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_BOOLEAN),
948✔
1431
        (bool) val);
948✔
1432
    return 1;
948✔
1433
}
1434

1435
static int
1436
rewrite_json_int(yajlpp_parse_context* ypc, long long val)
10,848✔
1437
{
1438
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
10,848✔
1439
    const auto* vd = jlu->get_field_def(ypc);
10,848✔
1440

1441
    if (vd != nullptr) {
10,848✔
1442
        const intern_string_t field_name = vd->vd_meta.lvm_name;
816✔
1443
        if (jlu->jlu_format->lf_timestamp_field == field_name) {
816✔
1444
            long long divisor = jlu->jlu_format->elf_timestamp_divisor;
25✔
1445
            timeval tv;
1446

1447
            tv.tv_sec = val / divisor;
25✔
1448
            tv.tv_usec = fmod(val, divisor) * (1000000.0 / divisor);
25✔
1449
            jlu->jlu_format->lf_date_time.to_localtime(tv.tv_sec,
25✔
1450
                                                       jlu->jlu_exttm);
25✔
1451
            jlu->jlu_exttm.et_gmtoff
1452
                = jlu->jlu_format->lf_date_time.dts_local_offset_cache;
25✔
1453
            jlu->jlu_exttm.et_flags |= ETF_MACHINE_ORIENTED
25✔
1454
                | ETF_SUB_NOT_IN_FORMAT | ETF_ZONE_SET | ETF_Z_FOR_UTC;
1455
            if (divisor == 1) {
25✔
1456
                jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
4✔
1457
            } else {
1458
                jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
21✔
1459
            }
1460
            jlu->jlu_exttm.et_nsec = tv.tv_usec * 1000;
25✔
1461
        } else if (jlu->jlu_format->lf_subsecond_field == field_name) {
791✔
1462
            jlu->jlu_exttm.et_flags &= ~(ETF_MICROS_SET | ETF_MILLIS_SET);
4✔
1463
            switch (jlu->jlu_format->lf_subsecond_unit.value()) {
4✔
1464
                case log_format::subsecond_unit::milli:
×
1465
                    jlu->jlu_exttm.et_nsec = val * 1000000;
×
1466
                    jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
×
1467
                    break;
×
1468
                case log_format::subsecond_unit::micro:
×
1469
                    jlu->jlu_exttm.et_nsec = val * 1000;
×
1470
                    jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
×
1471
                    break;
×
1472
                case log_format::subsecond_unit::nano:
4✔
1473
                    jlu->jlu_exttm.et_nsec = val;
4✔
1474
                    jlu->jlu_exttm.et_flags |= ETF_NANOS_SET;
4✔
1475
                    break;
4✔
1476
            }
1477
            jlu->jlu_exttm.et_flags |= ETF_SUB_NOT_IN_FORMAT;
4✔
1478
        }
1479
    }
1480

1481
    if (!ypc->is_level(1) && vd == nullptr) {
10,848✔
1482
        return 1;
9,985✔
1483
    }
1484
    if (vd != nullptr
863✔
1485
        && vd->vd_meta.lvm_name == jlu->jlu_format->elf_thread_id_field)
863✔
1486
    {
1487
        jlu->jlu_tid_number = val;
147✔
1488
    }
1489
    jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
863✔
1490
        jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_INTEGER),
863✔
1491
        (int64_t) val);
863✔
1492
    return 1;
863✔
1493
}
1494

1495
static int
1496
rewrite_json_double(yajlpp_parse_context* ypc, double val)
146✔
1497
{
1498
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
146✔
1499
    const auto* vd = jlu->get_field_def(ypc);
146✔
1500

1501
    if (vd != nullptr) {
146✔
1502
        const intern_string_t field_name = vd->vd_meta.lvm_name;
142✔
1503
        if (jlu->jlu_format->lf_timestamp_field == field_name) {
142✔
1504
            long long divisor = jlu->jlu_format->elf_timestamp_divisor;
122✔
1505
            timeval tv;
1506

1507
            tv.tv_sec = val / divisor;
122✔
1508
            tv.tv_usec = fmod(val, divisor) * (1000000.0 / divisor);
122✔
1509
            jlu->jlu_format->lf_date_time.to_localtime(tv.tv_sec,
122✔
1510
                                                       jlu->jlu_exttm);
122✔
1511
            jlu->jlu_exttm.et_gmtoff
1512
                = jlu->jlu_format->lf_date_time.dts_local_offset_cache;
122✔
1513
            jlu->jlu_exttm.et_flags |= ETF_MACHINE_ORIENTED
122✔
1514
                | ETF_SUB_NOT_IN_FORMAT | ETF_ZONE_SET | ETF_Z_FOR_UTC;
1515
            if (divisor == 1) {
122✔
1516
                jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
110✔
1517
            } else {
1518
                jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
12✔
1519
            }
1520
            jlu->jlu_exttm.et_nsec = tv.tv_usec * 1000;
122✔
1521
        } else if (jlu->jlu_format->lf_subsecond_field == field_name) {
20✔
1522
            jlu->jlu_exttm.et_flags &= ~(ETF_MICROS_SET | ETF_MILLIS_SET);
×
1523
            switch (jlu->jlu_format->lf_subsecond_unit.value()) {
×
1524
                case log_format::subsecond_unit::milli:
×
1525
                    jlu->jlu_exttm.et_nsec = val * 1000000;
×
1526
                    jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
×
1527
                    break;
×
1528
                case log_format::subsecond_unit::micro:
×
1529
                    jlu->jlu_exttm.et_nsec = val * 1000;
×
1530
                    jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
×
1531
                    break;
×
1532
                case log_format::subsecond_unit::nano:
×
1533
                    jlu->jlu_exttm.et_nsec = val;
×
1534
                    jlu->jlu_exttm.et_flags |= ETF_NANOS_SET;
×
1535
                    break;
×
1536
            }
1537
            jlu->jlu_exttm.et_flags |= ETF_SUB_NOT_IN_FORMAT;
×
1538
        } else if (jlu->jlu_format->elf_duration_field == field_name) {
20✔
1539
            jlu->jlu_duration = std::chrono::microseconds(
40✔
1540
                static_cast<int64_t>(val * 1000000.0));
20✔
1541
        }
1542
    }
1543

1544
    if (!ypc->is_level(1) && vd == nullptr) {
146✔
1545
        return 1;
×
1546
    }
1547
    jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
146✔
1548
        jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_FLOAT),
292✔
1549
        val);
1550

1551
    return 1;
146✔
1552
}
1553

1554
static const json_path_container json_log_rewrite_handlers = {
1555
    yajlpp::pattern_property_handler("\\w+")
1556
        .add_cb(rewrite_json_null)
1557
        .add_cb(rewrite_json_bool)
1558
        .add_cb(rewrite_json_int)
1559
        .add_cb(rewrite_json_double)
1560
        .add_cb(rewrite_json_field),
1561
};
1562

1563
bool
1564
external_log_format::scan_for_partial(const log_format_file_state& lffs,
1✔
1565
                                      shared_buffer_ref& sbr,
1566
                                      size_t& len_out) const
1567
{
1568
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
1✔
1569
        return false;
×
1570
    }
1571

1572
    const auto& pat
1573
        = this->elf_pattern_order[lffs.lffs_pattern_locks.last_pattern_index()];
1✔
1574
    if (!this->lf_multiline) {
1✔
1575
        len_out = pat->p_pcre.pp_value->match_partial(sbr.to_string_fragment());
1✔
1576
        return true;
1✔
1577
    }
1578

1579
    if (pat->p_timestamp_end == -1 || pat->p_timestamp_end > (int) sbr.length())
×
1580
    {
1581
        len_out = 0;
×
1582
        return false;
×
1583
    }
1584

1585
    len_out = pat->p_pcre.pp_value->match_partial(sbr.to_string_fragment());
×
1586
    return (int) len_out > pat->p_timestamp_end;
×
1587
}
1588

1589
std::vector<lnav::console::snippet>
1590
external_log_format::get_snippets() const
23✔
1591
{
1592
    std::vector<lnav::console::snippet> retval;
23✔
1593

1594
    for (const auto& src_pair : this->elf_format_sources) {
46✔
1595
        retval.emplace_back(lnav::console::snippet::from(src_pair.first, "")
46✔
1596
                                .with_line(src_pair.second));
23✔
1597
    }
1598

1599
    return retval;
23✔
1600
}
×
1601

1602
log_format::scan_result_t
1603
external_log_format::scan_json(std::vector<logline>& dst,
153,224✔
1604
                               const line_info& li,
1605
                               shared_buffer_ref& sbr,
1606
                               scan_batch_context& sbc)
1607
{
1608
    logline ll(
1609
        li.li_file_range.fr_offset, std::chrono::microseconds{0}, LEVEL_INFO);
153,224✔
1610
    auto line_frag = sbr.to_string_fragment();
153,224✔
1611

1612
    if (!line_frag.startswith("{")) {
153,224✔
1613
        if (!this->lf_specialized) {
143,525✔
1614
            return scan_no_match{"line is not a JSON object"};
143,520✔
1615
        }
1616

1617
        ll.set_time(dst.back().get_time<std::chrono::microseconds>());
5✔
1618
        ll.set_level(LEVEL_INVALID);
5✔
1619
        dst.emplace_back(ll);
5✔
1620
        return scan_match{0};
5✔
1621
    }
1622

1623
    auto& ypc = *(this->jlf_parse_context);
9,699✔
1624
    yajl_handle handle = this->jlf_yajl_handle.get();
9,699✔
1625
    json_log_userdata jlu(sbr, &sbc);
9,699✔
1626

1627
    if (li.li_partial) {
9,699✔
1628
        log_debug("skipping partial line at offset %lld",
×
1629
                  li.li_file_range.fr_offset);
1630
        if (this->lf_specialized) {
×
1631
            if (!dst.empty()) {
×
1632
                ll.set_time(dst.back().get_time<std::chrono::microseconds>());
×
1633
            }
1634
            ll.set_level(LEVEL_INVALID);
×
1635
            dst.emplace_back(ll);
×
1636
        }
1637
        return scan_incomplete{};
×
1638
    }
1639

1640
    const auto* line_data = (const unsigned char*) sbr.get_data();
9,699✔
1641

1642
    this->lf_desc_captures.clear();
9,699✔
1643
    this->lf_desc_allocator.reset();
9,699✔
1644

1645
    yajl_reset(handle);
9,699✔
1646
    ypc.set_static_handler(json_log_handlers.jpc_children[0]);
9,699✔
1647
    ypc.ypc_userdata = &jlu;
9,699✔
1648
    ypc.ypc_ignore_unused = true;
9,699✔
1649
    ypc.ypc_alt_callbacks.yajl_start_array = json_array_start;
9,699✔
1650
    ypc.ypc_alt_callbacks.yajl_start_map = json_array_start;
9,699✔
1651
    ypc.ypc_alt_callbacks.yajl_end_array = read_array_end;
9,699✔
1652
    ypc.ypc_alt_callbacks.yajl_end_map = read_array_end;
9,699✔
1653
    jlu.jlu_format = this;
9,699✔
1654
    jlu.jlu_base_line = &ll;
9,699✔
1655
    jlu.jlu_line_value = sbr.get_data();
9,699✔
1656
    jlu.jlu_line_size = sbr.length();
9,699✔
1657
    jlu.jlu_handle = handle;
9,699✔
1658
    jlu.jlu_format_hits.resize(this->jlf_line_format.size());
9,699✔
1659
    if (yajl_parse(handle, line_data, sbr.length()) == yajl_status_ok
9,699✔
1660
        && yajl_complete_parse(handle) == yajl_status_ok)
9,699✔
1661
    {
1662
        if (ll.get_time<std::chrono::microseconds>().count() == 0) {
9,516✔
1663
            if (this->lf_specialized) {
6,294✔
1664
                if (!dst.empty()) {
×
1665
                    ll.set_time(
×
1666
                        dst.back().get_time<std::chrono::microseconds>());
×
1667
                }
1668
                ll.set_ignore(true);
×
1669
                dst.emplace_back(ll);
×
1670
                return scan_match{0};
×
1671
            }
1672

1673
            return scan_no_match{
6,294✔
1674
                "JSON message does not have expected timestamp property"};
6,294✔
1675
        }
1676

1677
        if (jlu.jlu_tid_frag) {
3,222✔
1678
            this->jlf_line_values.lvv_thread_id_value
1679
                = jlu.jlu_tid_frag->to_string();
102✔
1680
            auto tid_iter = sbc.sbc_tids.insert_tid(
204✔
1681
                sbc.sbc_allocator,
1682
                jlu.jlu_tid_frag.value(),
102✔
1683
                ll.get_time<std::chrono::microseconds>());
102✔
1684
            tid_iter->second.titr_level_stats.update_msg_count(
102✔
1685
                ll.get_msg_level());
1686
            ll.merge_bloom_bits(jlu.jlu_tid_frag->bloom_bits());
102✔
1687
        } else {
1688
            auto tid_iter = sbc.sbc_tids.insert_tid(
3,120✔
1689
                sbc.sbc_allocator,
1690
                string_fragment{},
×
1691
                ll.get_time<std::chrono::microseconds>());
3,120✔
1692
            tid_iter->second.titr_level_stats.update_msg_count(
3,120✔
1693
                ll.get_msg_level());
1694
        }
1695

1696
        auto found_opid_desc = false;
3,222✔
1697
        if (this->elf_opid_field.empty()
3,222✔
1698
            && this->lf_opid_source.value_or(opid_source_t::from_description)
760✔
1699
                == opid_source_t::from_description
1700
            && this->lf_opid_description_def->size() == 1)
3,982✔
1701
        {
1702
            const auto& od = this->lf_opid_description_def->begin()->second;
322✔
1703
            for (const auto& desc : *od.od_descriptors) {
966✔
1704
                auto desc_iter
1705
                    = this->lf_desc_captures.find(desc.od_field.pp_value);
644✔
1706
                if (desc_iter == this->lf_desc_captures.end()) {
644✔
1707
                    continue;
602✔
1708
                }
1709
                jlu.jlu_opid_hasher.update(desc_iter->second);
42✔
1710
                found_opid_desc = true;
42✔
1711
            }
1712

1713
        } else if (!jlu.jlu_opid_desc_frag && !jlu.jlu_opid_frag
3,547✔
1714
                   && jlu.jlu_duration > 0us)
3,547✔
1715
        {
1716
            jlu.jlu_opid_hasher.update(sbr.to_string_fragment());
×
1717
        }
1718

1719
        if (jlu.jlu_opid_desc_frag || jlu.jlu_duration > 0us
4,191✔
1720
            || (found_opid_desc && this->lf_opid_description_def->size() == 1))
4,191✔
1721
        {
1722
            char buf[hasher::STRING_SIZE];
1723
            jlu.jlu_opid_hasher.to_string(buf);
2,274✔
1724
            auto opid_frag = string_fragment::from_bytes(buf, sizeof(buf) - 1);
2,274✔
1725
            auto opid_iter = sbc.sbc_opids.los_opid_ranges.find(opid_frag);
2,274✔
1726
            if (opid_iter == sbc.sbc_opids.los_opid_ranges.end()) {
2,274✔
1727
                jlu.jlu_opid_frag = opid_frag.to_owned(sbc.sbc_allocator);
2,262✔
1728
            } else {
1729
                jlu.jlu_opid_frag = opid_iter->first;
12✔
1730
            }
1731
        }
1732

1733
        if (jlu.jlu_opid_frag) {
3,222✔
1734
            ll.merge_bloom_bits(jlu.jlu_opid_frag->bloom_bits());
2,438✔
1735
            this->jlf_line_values.lvv_opid_value
1736
                = jlu.jlu_opid_frag->to_string();
2,438✔
1737
            this->jlf_line_values.lvv_opid_provenance
1738
                = logline_value_vector::opid_provenance::file;
2,438✔
1739
            auto opid_iter = sbc.sbc_opids.insert_op(
4,876✔
1740
                sbc.sbc_allocator,
1741
                jlu.jlu_opid_frag.value(),
2,438✔
1742
                ll.get_time<std::chrono::microseconds>(),
2,438✔
1743
                this->lf_timestamp_point_of_reference,
1744
                jlu.jlu_duration);
1745
            opid_iter->second.otr_level_stats.update_msg_count(
2,438✔
1746
                ll.get_msg_level());
1747
            auto& elems = opid_iter->second.otr_description.lod_elements;
2,438✔
1748
            if (jlu.jlu_opid_desc_frag && elems.empty()) {
2,438✔
1749
                elems.insert(0,
×
1750
                             fmt::format(FMT_STRING(" {}"),
8,988✔
1751
                                         jlu.jlu_opid_desc_frag.value()));
1752
            }
1753

1754
            if (jlu.jlu_subid) {
2,438✔
1755
                auto subid_frag
1756
                    = string_fragment::from_str(jlu.jlu_subid.value());
×
1757

1758
                auto* ostr = sbc.sbc_opids.sub_op_in_use(
×
1759
                    sbc.sbc_allocator,
1760
                    opid_iter,
1761
                    subid_frag,
1762
                    ll.get_time<std::chrono::microseconds>(),
×
1763
                    ll.get_msg_level());
1764
                if (ostr != nullptr && ostr->ostr_description.empty()) {
×
1765
                    log_op_description sub_desc;
×
1766
                    this->update_op_description(
×
1767
                        *this->lf_subid_description_def_vec, sub_desc);
×
1768
                    if (!sub_desc.lod_elements.empty()) {
×
1769
                        auto& sub_desc_def
1770
                            = this->lf_subid_description_def_vec->at(
×
1771
                                sub_desc.lod_index.value());
×
1772
                        ostr->ostr_description
1773
                            = sub_desc_def->to_string(sub_desc.lod_elements);
×
1774
                    }
1775
                }
1776
            }
1777

1778
            auto& otr = opid_iter->second;
2,438✔
1779
            this->update_op_description(*this->lf_opid_description_def_vec,
2,438✔
1780
                                        otr.otr_description);
2,438✔
1781
        } else {
1782
            this->jlf_line_values.lvv_opid_value = std::nullopt;
784✔
1783
        }
1784

1785
        jlu.jlu_sub_line_count += this->jlf_line_format_init_count;
3,222✔
1786
        ll.set_has_ansi(jlu.jlu_has_ansi);
3,222✔
1787
        ll.set_valid_utf(jlu.jlu_valid_utf);
3,222✔
1788
        for (int lpc = 0; lpc < jlu.jlu_sub_line_count; lpc++) {
16,965✔
1789
            ll.set_sub_offset(lpc);
13,743✔
1790
            ll.set_continued(lpc > 0);
13,743✔
1791
            dst.emplace_back(ll);
13,743✔
1792
        }
1793
        this->lf_timestamp_flags = jlu.jlu_exttm.et_flags;
3,222✔
1794

1795
        if (!this->lf_specialized) {
3,222✔
1796
            static const intern_string_t ts_field
1797
                = intern_string::lookup("__timestamp__", -1);
2,689✔
1798
            static const intern_string_t level_field
1799
                = intern_string::lookup("__level__");
4,183✔
1800
            for (const auto& [index, jfe] :
25,254✔
1801
                 lnav::itertools::enumerate(this->jlf_line_format))
27,943✔
1802
            {
1803
                if (jfe.jfe_type != json_log_field::VARIABLE
59,751✔
1804
                    || jfe.jfe_value.pp_value == ts_field
14,794✔
1805
                    || jfe.jfe_value.pp_value == level_field
12,175✔
1806
                    || jfe.jfe_default_value != "-")
37,359✔
1807
                {
1808
                    continue;
14,621✔
1809
                }
1810
                if (!jlu.jlu_format_hits[index]) {
7,944✔
1811
                    jlu.jlu_strikes += 1;
7,461✔
1812
                }
1813
            }
1814
        }
1815
    } else {
1816
        unsigned char* msg;
1817
        int line_count = 2;
183✔
1818

1819
        msg = yajl_get_error(
366✔
1820
            handle, 1, (const unsigned char*) sbr.get_data(), sbr.length());
183✔
1821
        if (msg != nullptr) {
183✔
1822
            auto msg_frag = string_fragment::from_c_str(msg);
183✔
1823
            log_debug("Unable to parse line at offset %lld: %.*s",
183✔
1824
                      li.li_file_range.fr_offset,
1825
                      msg_frag.length(),
1826
                      msg_frag.data());
1827
            line_count = msg_frag.count('\n') + 1;
183✔
1828
            yajl_free_error(handle, msg);
183✔
1829
        }
1830
        if (!this->lf_specialized) {
183✔
1831
            return scan_no_match{"JSON parsing failed"};
180✔
1832
        }
1833
        for (int lpc = 0; lpc < line_count; lpc++) {
15✔
1834
            log_level_t level = LEVEL_INVALID;
12✔
1835

1836
            ll.set_time(dst.back().get_timeval());
12✔
1837
            ll.set_continued(lpc > 0);
12✔
1838
            ll.set_level(level);
12✔
1839
            ll.set_sub_offset(lpc);
12✔
1840
            dst.emplace_back(ll);
12✔
1841
        }
1842
    }
1843

1844
    if (jlu.jlu_quality > 0) {
3,225✔
1845
        jlu.jlu_quality += 3000;
834✔
1846
    }
1847
    return scan_match{jlu.jlu_quality, jlu.jlu_strikes};
3,225✔
1848
}
9,699✔
1849

1850
log_format::scan_result_t
1851
external_log_format::scan(logfile& lf,
851,507✔
1852
                          std::vector<logline>& dst,
1853
                          const line_info& li,
1854
                          shared_buffer_ref& sbr,
1855
                          scan_batch_context& sbc)
1856
{
1857
    if (dst.empty()) {
851,507✔
1858
        auto file_options = lf.get_file_options();
33,120✔
1859

1860
        if (file_options) {
33,120✔
1861
            this->lf_date_time.dts_default_zone
1862
                = file_options->second.fo_default_zone.pp_value;
2,292✔
1863
        } else {
1864
            this->lf_date_time.dts_default_zone = nullptr;
30,828✔
1865
        }
1866
    }
33,120✔
1867

1868
    sbc.sbc_value_stats.resize(this->elf_value_defs.size());
851,507✔
1869
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
851,507✔
1870
        return this->scan_json(dst, li, sbr, sbc);
150,981✔
1871
    }
1872

1873
    int curr_fmt = -1, orig_lock = sbc.sbc_pattern_locks.last_pattern_index();
700,526✔
1874
    int pat_index = orig_lock;
700,526✔
1875
    auto line_sf = sbr.to_string_fragment();
700,526✔
1876
    thread_local auto md = lnav::pcre2pp::match_data::unitialized();
700,526✔
1877
    char tmp_opid_buf[hasher::STRING_SIZE];
1878

1879
    while (::next_format(this->elf_pattern_order, curr_fmt, pat_index)) {
2,300,366✔
1880
        auto* fpat = this->elf_pattern_order[curr_fmt].get();
1,605,707✔
1881
        auto* pat = fpat->p_pcre.pp_value.get();
1,605,707✔
1882

1883
        auto found_match
1884
            = pat->capture_from(line_sf).into(md).found_p(PCRE2_NO_UTF_CHECK);
1,605,707✔
1885
        if (!found_match) {
1,605,707✔
1886
            if (!sbc.sbc_pattern_locks.empty() && pat_index != -1) {
1,599,837✔
1887
                curr_fmt = -1;
2,001✔
1888
                pat_index = -1;
2,001✔
1889
            }
1890
            continue;
1,599,840✔
1891
        }
1892

1893
        auto ts = md[fpat->p_timestamp_field_index];
5,870✔
1894
        auto level_cap = md[fpat->p_level_field_index];
5,870✔
1895
        auto opid_cap = md[fpat->p_opid_field_index];
5,870✔
1896
        const char* last;
1897
        exttm log_time_tm;
5,870✔
1898
        timeval log_tv;
1899
        uint64_t opid_bloom = 0;
5,870✔
1900
        char combined_datetime_buf[512];
1901

1902
        if (fpat->p_time_field_index != -1) {
5,870✔
1903
            auto time_cap = md[fpat->p_time_field_index];
×
1904
            if (ts && time_cap) {
×
1905
                auto ts_str_len = snprintf(combined_datetime_buf,
×
1906
                                           sizeof(combined_datetime_buf),
1907
                                           "%.*sT%.*s",
1908
                                           ts->length(),
1909
                                           ts->data(),
1910
                                           time_cap->length(),
1911
                                           time_cap->data());
1912
                ts = string_fragment::from_bytes(combined_datetime_buf,
×
1913
                                                 ts_str_len);
×
1914
            }
1915
        }
1916

1917
        auto level = this->convert_level(
5,870✔
1918
            level_cap.value_or(string_fragment::invalid()), &sbc);
5,870✔
1919

1920
        if (!ts) {
5,870✔
1921
            level = log_level_t::LEVEL_INVALID;
×
1922
        } else if ((last
5,870✔
1923
                    = this->lf_date_time.scan(ts->data(),
11,740✔
1924
                                              ts->length(),
5,870✔
1925
                                              this->get_timestamp_formats(),
1926
                                              &log_time_tm,
1927
                                              log_tv))
1928
                   == nullptr)
5,870✔
1929
        {
1930
            auto ls = this->lf_date_time.unlock();
13✔
1931
            if ((last = this->lf_date_time.scan(ts->data(),
26✔
1932
                                                ts->length(),
13✔
1933
                                                this->get_timestamp_formats(),
1934
                                                &log_time_tm,
1935
                                                log_tv))
1936
                == nullptr)
13✔
1937
            {
1938
                this->lf_date_time.relock(ls);
2✔
1939
                continue;
3✔
1940
            }
1941
            if (last != nullptr) {
11✔
1942
                auto old_flags = this->lf_timestamp_flags & DATE_TIME_SET_FLAGS;
11✔
1943
                auto new_flags = log_time_tm.et_flags & DATE_TIME_SET_FLAGS;
11✔
1944

1945
                // It is unlikely a valid timestamp would lose much
1946
                // precision.
1947
                if (new_flags != old_flags) {
11✔
1948
                    continue;
1✔
1949
                }
1950
            }
1951

1952
            log_debug("%s:%zu: date-time re-locked to %d",
10✔
1953
                      lf.get_unique_path().c_str(),
1954
                      dst.size(),
1955
                      this->lf_date_time.dts_fmt_lock);
1956
        }
1957

1958
        this->lf_timestamp_flags = log_time_tm.et_flags;
5,867✔
1959

1960
        if (!(this->lf_timestamp_flags
11,734✔
1961
              & (ETF_MILLIS_SET | ETF_MICROS_SET | ETF_NANOS_SET))
5,867✔
1962
            && !dst.empty()
5,279✔
1963
            && dst.back().get_time<std::chrono::seconds>().count()
4,544✔
1964
                == log_tv.tv_sec
4,544✔
1965
            && dst.back()
14,578✔
1966
                    .get_subsecond_time<std::chrono::milliseconds>()
9,299✔
1967
                    .count()
3,432✔
1968
                != 0)
1969
        {
1970
            auto log_ms
1971
                = dst.back().get_subsecond_time<std::chrono::microseconds>();
×
1972

1973
            log_time_tm.et_nsec
1974
                = std::chrono::duration_cast<std::chrono::nanoseconds>(log_ms)
×
1975
                      .count();
×
1976
            log_tv.tv_usec
1977
                = std::chrono::duration_cast<std::chrono::microseconds>(log_ms)
×
1978
                      .count();
×
1979
        }
1980

1981
        if (!((log_time_tm.et_flags & ETF_DAY_SET)
5,867✔
1982
              && (log_time_tm.et_flags & ETF_MONTH_SET)
5,826✔
1983
              && (log_time_tm.et_flags & ETF_YEAR_SET)))
5,826✔
1984
        {
1985
            this->check_for_new_year(dst, log_time_tm, log_tv);
786✔
1986
        }
1987

1988
        auto log_us = to_us(log_tv);
5,867✔
1989
        if (this->elf_opid_field.empty()
5,867✔
1990
            && !fpat->p_opid_description_field_indexes.empty())
5,867✔
1991
        {
1992
            auto empty_desc = true;
4,001✔
1993
            hasher h;
4,001✔
1994
            for (const auto& fidx : fpat->p_opid_description_field_indexes) {
12,003✔
1995
                auto desc_cap = md[fidx];
8,002✔
1996
                if (desc_cap) {
8,002✔
1997
                    h.update(desc_cap.value());
7,955✔
1998
                    empty_desc = false;
7,955✔
1999
                }
2000
            }
2001
            if (!empty_desc) {
4,001✔
2002
                h.to_string(tmp_opid_buf);
4,001✔
2003
                opid_cap = string_fragment::from_bytes(
8,002✔
2004
                    tmp_opid_buf, sizeof(tmp_opid_buf) - 1);
4,001✔
2005
            }
2006
        }
2007

2008
        auto duration_cap = md[fpat->p_duration_field_index];
5,867✔
2009
        if (duration_cap && !opid_cap) {
5,867✔
2010
            hasher h;
86✔
2011
            h.update(line_sf);
86✔
2012
            h.to_string(tmp_opid_buf);
86✔
2013
            opid_cap = string_fragment::from_bytes(tmp_opid_buf,
172✔
2014
                                                   sizeof(tmp_opid_buf) - 1);
86✔
2015
        }
2016
        if (opid_cap && !opid_cap->empty()) {
5,867✔
2017
            auto duration = std::chrono::microseconds{0};
4,878✔
2018
            if (duration_cap) {
4,878✔
2019
                auto from_res
2020
                    = humanize::try_from<double>(duration_cap.value());
86✔
2021
                if (from_res) {
86✔
2022
                    duration = std::chrono::microseconds(
×
2023
                        static_cast<int64_t>(from_res.value() * 1000000));
86✔
2024
                }
2025
            }
2026
            auto opid_iter
2027
                = sbc.sbc_opids.insert_op(sbc.sbc_allocator,
9,756✔
2028
                                          opid_cap.value(),
4,878✔
2029
                                          log_us,
2030
                                          this->lf_timestamp_point_of_reference,
2031
                                          duration);
2032
            auto& otr = opid_iter->second;
4,878✔
2033

2034
            otr.otr_level_stats.update_msg_count(level);
4,878✔
2035
            if (fpat->p_subid_field_index != -1) {
4,878✔
2036
                auto subid_cap = md[fpat->p_subid_field_index];
62✔
2037
                if (subid_cap && !subid_cap->empty()) {
62✔
2038
                    auto* ostr = sbc.sbc_opids.sub_op_in_use(sbc.sbc_allocator,
186✔
2039
                                                             opid_iter,
2040
                                                             subid_cap.value(),
62✔
2041
                                                             log_us,
2042
                                                             level);
2043
                    if (ostr != nullptr && ostr->ostr_description.empty()) {
62✔
2044
                        log_op_description sub_desc;
41✔
2045
                        this->update_op_description(
41✔
2046
                            *this->lf_subid_description_def_vec,
41✔
2047
                            sub_desc,
2048
                            fpat,
2049
                            md);
2050
                        if (!sub_desc.lod_elements.empty()) {
41✔
2051
                            auto& sub_desc_def
2052
                                = this->lf_subid_description_def_vec->at(
39✔
2053
                                    sub_desc.lod_index.value());
39✔
2054
                            ostr->ostr_description = sub_desc_def->to_string(
78✔
2055
                                sub_desc.lod_elements);
39✔
2056
                        }
2057
                    }
41✔
2058
                }
2059
            }
2060
            this->update_op_description(*this->lf_opid_description_def_vec,
4,878✔
2061
                                        otr.otr_description,
4,878✔
2062
                                        fpat,
2063
                                        md);
2064
            opid_bloom = opid_cap->bloom_bits();
4,878✔
2065
        }
2066

2067
        for (const auto& ivd : fpat->p_value_by_index) {
66,297✔
2068
            if (!ivd.ivd_value_def->vd_meta.lvm_values_index) {
60,430✔
2069
                continue;
11,032✔
2070
            }
2071

2072
            ssize_t cap_size = md.capture_size(ivd.ivd_index);
49,398✔
2073
            auto& lvs = sbc.sbc_value_stats[ivd.ivd_value_def->vd_meta
49,398✔
2074
                                                .lvm_values_index.value()];
49,398✔
2075

2076
            if (cap_size > lvs.lvs_width) {
49,398✔
2077
                lvs.lvs_width = cap_size;
6,297✔
2078
            }
2079
        }
2080

2081
        for (auto value_index : fpat->p_numeric_value_indexes) {
10,708✔
2082
            const indexed_value_def& ivd = fpat->p_value_by_index[value_index];
4,841✔
2083
            const value_def& vd = *ivd.ivd_value_def;
4,841✔
2084
            auto num_cap = md[ivd.ivd_index];
4,841✔
2085

2086
            if (num_cap && num_cap->is_valid()) {
4,841✔
2087
                const struct scaling_factor* scaling = nullptr;
4,775✔
2088

2089
                if (ivd.ivd_unit_field_index >= 0) {
4,775✔
2090
                    auto unit_cap = md[ivd.ivd_unit_field_index];
80✔
2091

2092
                    if (unit_cap && unit_cap->is_valid()) {
80✔
2093
                        intern_string_t unit_val
2094
                            = intern_string::lookup(unit_cap.value());
80✔
2095

2096
                        auto unit_iter = vd.vd_unit_scaling.find(unit_val);
80✔
2097
                        if (unit_iter != vd.vd_unit_scaling.end()) {
80✔
2098
                            const auto& sf = unit_iter->second;
80✔
2099

2100
                            scaling = &sf;
80✔
2101
                        }
2102
                    }
2103
                }
2104

2105
                std::optional<double> dvalue_opt;
4,775✔
2106
                switch (vd.vd_meta.lvm_kind) {
4,775✔
2107
                    case value_kind_t::VALUE_INTEGER: {
4,609✔
2108
                        auto scan_res
2109
                            = scn::scan_int<int64_t>(num_cap->to_string_view());
4,609✔
2110
                        if (scan_res) {
4,609✔
2111
                            dvalue_opt = scan_res->value();
4,609✔
2112
                        }
2113
                        break;
4,609✔
2114
                    }
2115
                    case value_kind_t::VALUE_FLOAT: {
166✔
2116
                        auto scan_res = scn::scan_value<double>(
2117
                            num_cap->to_string_view());
166✔
2118
                        if (scan_res) {
166✔
2119
                            dvalue_opt = scan_res->value();
166✔
2120
                        }
2121
                        break;
166✔
2122
                    }
2123
                    default:
×
2124
                        break;
×
2125
                }
2126
                if (dvalue_opt) {
4,775✔
2127
                    auto dvalue = dvalue_opt.value();
4,775✔
2128
                    if (scaling != nullptr) {
4,775✔
2129
                        scaling->scale(dvalue);
80✔
2130
                    }
2131
                    sbc.sbc_value_stats[vd.vd_meta.lvm_values_index.value()]
4,775✔
2132
                        .add_value(dvalue);
4,775✔
2133
                }
2134
            }
2135
        }
2136

2137
        dst.emplace_back(li.li_file_range.fr_offset, log_us, level);
5,867✔
2138
        auto& new_line = dst.back();
5,867✔
2139
        new_line.merge_bloom_bits(opid_bloom);
5,867✔
2140

2141
        auto src_file_cap = md[fpat->p_src_file_field_index];
5,867✔
2142
        auto src_line_cap = md[fpat->p_src_line_field_index];
5,867✔
2143
        if (src_file_cap && src_line_cap) {
5,867✔
2144
            auto h = hasher();
94✔
2145
            h.update(this->get_name().c_str());
94✔
2146
            h.update(src_file_cap.value());
94✔
2147
            h.update(src_line_cap.value());
94✔
2148
            new_line.merge_bloom_bits(h.to_bloom_bits());
94✔
2149
            new_line.set_schema_computed(true);
94✔
2150
        }
2151
        auto thread_id_cap = md[fpat->p_thread_id_field_index];
5,867✔
2152
        if (thread_id_cap) {
5,867✔
2153
            auto tid_iter = sbc.sbc_tids.insert_tid(
2,074✔
2154
                sbc.sbc_allocator, thread_id_cap.value(), log_us);
1,037✔
2155
            tid_iter->second.titr_level_stats.update_msg_count(level);
1,037✔
2156
            new_line.merge_bloom_bits(thread_id_cap->bloom_bits());
1,037✔
2157
        } else {
2158
            auto tid_iter = sbc.sbc_tids.insert_tid(
4,830✔
2159
                sbc.sbc_allocator, string_fragment{}, log_us);
×
2160
            tid_iter->second.titr_level_stats.update_msg_count(level);
4,830✔
2161
        }
2162

2163
        if (orig_lock != curr_fmt) {
5,867✔
2164
            uint32_t lock_line;
2165

2166
            if (!this->lf_specialized && orig_lock != -1) {
616✔
2167
                log_debug("%s:%zu: changing pattern lock %d -> (%d)%s",
×
2168
                          lf.get_unique_path().c_str(),
2169
                          dst.size() - 1,
2170
                          orig_lock,
2171
                          curr_fmt,
2172
                          this->elf_pattern_order[curr_fmt]->p_name.c_str());
2173
            }
2174
            if (sbc.sbc_pattern_locks.empty()) {
616✔
2175
                lock_line = 0;
590✔
2176
            } else {
2177
                lock_line = dst.size() - 1;
26✔
2178
            }
2179
            sbc.sbc_pattern_locks.pl_lines.emplace_back(lock_line, curr_fmt);
616✔
2180
        }
2181
        return scan_match{1000};
5,867✔
2182
    }
2183

2184
    if (this->lf_specialized && !this->lf_multiline && !dst.empty()) {
694,659✔
2185
        const auto& last_line = dst.back();
1✔
2186

2187
        log_debug("%s: invalid line %zu file_offset=%" PRIu64,
1✔
2188
                  lf.get_filename().c_str(),
2189
                  dst.size(),
2190
                  li.li_file_range.fr_offset);
2191
        dst.emplace_back(li.li_file_range.fr_offset,
1✔
2192
                         last_line.get_time<std::chrono::microseconds>(),
×
2193
                         log_level_t::LEVEL_INVALID);
1✔
2194

2195
        return scan_match{0};
1✔
2196
    }
2197

2198
    return scan_no_match{"no patterns matched"};
694,658✔
2199
}
2200

2201
void
2202
external_log_format::annotate(logfile* lf,
7,385✔
2203
                              uint64_t line_number,
2204
                              string_attrs_t& sa,
2205
                              logline_value_vector& values) const
2206
{
2207
    thread_local auto md = lnav::pcre2pp::match_data::unitialized();
7,385✔
2208

2209
    auto& line = values.lvv_sbr;
7,385✔
2210
    line_range lr;
7,385✔
2211

2212
    line.erase_ansi();
7,385✔
2213
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
7,385✔
2214
        if (this->jlf_cached_opts.full_message) {
749✔
2215
            values = this->jlf_line_values;
318✔
2216
            sa = this->jlf_line_attrs;
318✔
2217
        } else {
2218
            values.lvv_sbr = this->jlf_line_values.lvv_sbr.clone();
431✔
2219
            for (const auto& llv : this->jlf_line_values.lvv_values) {
4,274✔
2220
                if (this->jlf_cached_sub_range.contains(llv.lv_origin)) {
3,843✔
2221
                    values.lvv_values.emplace_back(llv);
911✔
2222
                    values.lvv_values.back().lv_origin.shift(
911✔
2223
                        this->jlf_cached_sub_range.lr_start,
911✔
2224
                        -this->jlf_cached_sub_range.lr_start);
911✔
2225
                }
2226
            }
2227
            for (const auto& attr : this->jlf_line_attrs) {
2,436✔
2228
                if (this->jlf_cached_sub_range.contains(attr.sa_range)) {
2,005✔
2229
                    sa.emplace_back(attr);
702✔
2230
                    sa.back().sa_range.shift(
702✔
2231
                        this->jlf_cached_sub_range.lr_start,
702✔
2232
                        -this->jlf_cached_sub_range.lr_start);
702✔
2233
                }
2234
            }
2235
            values.lvv_opid_value = this->jlf_line_values.lvv_opid_value;
431✔
2236
            values.lvv_opid_provenance
2237
                = this->jlf_line_values.lvv_opid_provenance;
431✔
2238
            values.lvv_thread_id_value
2239
                = this->jlf_line_values.lvv_thread_id_value;
431✔
2240
        }
2241
        log_format::annotate(lf, line_number, sa, values);
749✔
2242
        return;
2,372✔
2243
    }
2244

2245
    if (line.empty()) {
6,636✔
2246
        return;
5✔
2247
    }
2248

2249
    values.lvv_values.reserve(this->elf_value_defs.size());
6,631✔
2250

2251
    auto lffs = lf->get_format_file_state();
6,631✔
2252
    int pat_index = lffs.lffs_pattern_locks.pattern_index_for_line(line_number);
6,631✔
2253
    const auto& pat = *this->elf_pattern_order[pat_index];
6,631✔
2254
    char tmp_opid_buf[hasher::STRING_SIZE];
2255

2256
    sa.reserve(pat.p_pcre.pp_value->get_capture_count());
6,631✔
2257
    auto match_res
2258
        = pat.p_pcre.pp_value->capture_from(line.to_string_fragment())
6,631✔
2259
              .into(md)
6,631✔
2260
              .matches(PCRE2_NO_UTF_CHECK)
13,262✔
2261
              .ignore_error();
6,631✔
2262
    if (!match_res) {
6,631✔
2263
        // A continued line still needs a body.
2264
        lr.lr_start = 0;
1,618✔
2265
        lr.lr_end = line.length();
1,618✔
2266
        sa.emplace_back(lr, SA_BODY.value());
1,618✔
2267
        if (!this->lf_multiline) {
1,618✔
2268
            auto len
2269
                = pat.p_pcre.pp_value->match_partial(line.to_string_fragment());
×
2270
            sa.emplace_back(
×
2271
                line_range{(int) len, -1},
×
2272
                SA_INVALID.value("Log line does not match any pattern"));
×
2273
        }
2274
        return;
1,618✔
2275
    }
2276

2277
    auto duration_cap = md[pat.p_duration_field_index];
5,013✔
2278

2279
    auto ts_cap = md[pat.p_timestamp_field_index];
5,013✔
2280
    if (ts_cap) {
5,013✔
2281
        sa.emplace_back(to_line_range(ts_cap.value()), L_TIMESTAMP.value());
5,013✔
2282
    }
2283

2284
    auto opid_cap = md[pat.p_opid_field_index];
5,013✔
2285

2286
    if (this->elf_opid_field.empty()
5,013✔
2287
        && !pat.p_opid_description_field_indexes.empty())
5,013✔
2288
    {
2289
        auto empty_desc = true;
3,763✔
2290
        hasher h;
3,763✔
2291
        for (const auto& fidx : pat.p_opid_description_field_indexes) {
11,289✔
2292
            auto desc_cap = md[fidx];
7,526✔
2293
            if (desc_cap) {
7,526✔
2294
                h.update(desc_cap.value());
7,498✔
2295
                empty_desc = false;
7,498✔
2296
            }
2297
        }
2298
        if (!empty_desc) {
3,763✔
2299
            h.to_string(tmp_opid_buf);
3,763✔
2300
            opid_cap = string_fragment::from_bytes(tmp_opid_buf,
7,526✔
2301
                                                   sizeof(tmp_opid_buf) - 1);
3,763✔
2302
        }
2303
    } else if (duration_cap && !opid_cap) {
1,250✔
2304
        hasher h;
3✔
2305
        h.update(line.to_string_fragment());
3✔
2306
        h.to_string(tmp_opid_buf);
3✔
2307
        opid_cap = string_fragment::from_bytes(tmp_opid_buf,
6✔
2308
                                               sizeof(tmp_opid_buf) - 1);
3✔
2309
    }
2310
    if (opid_cap && !opid_cap->empty()) {
5,013✔
2311
        sa.emplace_back(to_line_range(opid_cap.value()), L_OPID.value());
4,207✔
2312
        values.lvv_opid_value = opid_cap->to_string();
4,207✔
2313
        values.lvv_opid_provenance
2314
            = logline_value_vector::opid_provenance::file;
4,207✔
2315
    }
2316

2317
    auto body_cap = md[pat.p_body_field_index];
5,013✔
2318
    auto level_cap = md[pat.p_level_field_index];
5,013✔
2319
    auto src_file_cap = md[pat.p_src_file_field_index];
5,013✔
2320
    auto src_line_cap = md[pat.p_src_line_field_index];
5,013✔
2321
    auto thread_id_cap = md[pat.p_thread_id_field_index];
5,013✔
2322

2323
    if (level_cap
5,013✔
2324
        && (!body_cap
9,980✔
2325
            || (body_cap && level_cap->sf_begin != body_cap->sf_begin)))
9,980✔
2326
    {
2327
        sa.emplace_back(to_line_range(level_cap.value()), L_LEVEL.value());
4,578✔
2328
    }
2329

2330
    if (src_file_cap) {
5,013✔
2331
        sa.emplace_back(to_line_range(src_file_cap.value()),
97✔
2332
                        SA_SRC_FILE.value());
194✔
2333
    }
2334
    if (src_line_cap) {
5,013✔
2335
        sa.emplace_back(to_line_range(src_line_cap.value()),
97✔
2336
                        SA_SRC_LINE.value());
194✔
2337
    }
2338
    if (thread_id_cap) {
5,013✔
2339
        sa.emplace_back(to_line_range(thread_id_cap.value()),
603✔
2340
                        SA_THREAD_ID.value());
1,206✔
2341
        values.lvv_thread_id_value = thread_id_cap->to_string();
603✔
2342
    }
2343
    if (duration_cap) {
5,013✔
2344
        sa.emplace_back(to_line_range(duration_cap.value()),
3✔
2345
                        SA_DURATION.value());
6✔
2346
    }
2347

2348
    for (size_t lpc = 0; lpc < pat.p_value_by_index.size(); lpc++) {
57,462✔
2349
        const auto& ivd = pat.p_value_by_index[lpc];
52,449✔
2350
        const scaling_factor* scaling = nullptr;
52,449✔
2351
        auto cap = md[ivd.ivd_index];
52,449✔
2352
        const auto& vd = *ivd.ivd_value_def;
52,449✔
2353

2354
        if (ivd.ivd_unit_field_index >= 0) {
52,449✔
2355
            auto unit_cap = md[ivd.ivd_unit_field_index];
10✔
2356

2357
            if (unit_cap) {
10✔
2358
                intern_string_t unit_val
2359
                    = intern_string::lookup(unit_cap.value());
10✔
2360
                auto unit_iter = vd.vd_unit_scaling.find(unit_val);
10✔
2361
                if (unit_iter != vd.vd_unit_scaling.end()) {
10✔
2362
                    const auto& sf = unit_iter->second;
10✔
2363

2364
                    scaling = &sf;
10✔
2365
                }
2366
            }
2367
        }
2368

2369
        if (cap) {
52,449✔
2370
            values.lvv_values.emplace_back(
85,586✔
2371
                vd.vd_meta, line, to_line_range(cap.value()));
42,793✔
2372
            values.lvv_values.back().apply_scaling(scaling);
42,793✔
2373
        } else {
2374
            values.lvv_values.emplace_back(vd.vd_meta);
9,656✔
2375
        }
2376
    }
2377

2378
    if (body_cap && body_cap->is_valid()) {
5,013✔
2379
        lr = to_line_range(body_cap.value());
5,001✔
2380
    } else {
2381
        lr.lr_start = line.length();
12✔
2382
        lr.lr_end = line.length();
12✔
2383
    }
2384
    sa.emplace_back(lr, SA_BODY.value());
5,013✔
2385

2386
    log_format::annotate(lf, line_number, sa, values);
5,013✔
2387
}
2388

2389
void
2390
external_log_format::rewrite(exec_context& ec,
43✔
2391
                             shared_buffer_ref& line,
2392
                             string_attrs_t& sa,
2393
                             std::string& value_out)
2394
{
2395
    auto& values = *ec.ec_line_values;
43✔
2396

2397
    value_out.assign(line.get_data(), line.length());
43✔
2398

2399
    for (auto iter = values.lvv_values.begin(); iter != values.lvv_values.end();
259✔
2400
         ++iter)
216✔
2401
    {
2402
        if (!iter->lv_origin.is_valid()) {
216✔
2403
            log_debug("%d: not rewriting value with invalid origin -- %s",
24✔
2404
                      (int) ec.ec_top_line,
2405
                      iter->lv_meta.lvm_name.get());
2406
            continue;
184✔
2407
        }
2408

2409
        auto vd_iter = this->elf_value_defs.find(iter->lv_meta.lvm_name);
192✔
2410
        if (vd_iter == this->elf_value_defs.end()) {
192✔
2411
            log_debug("%d: not rewriting undefined value -- %s",
×
2412
                      (int) ec.ec_top_line,
2413
                      iter->lv_meta.lvm_name.get());
2414
            continue;
×
2415
        }
2416

2417
        const auto& vd = *vd_iter->second;
192✔
2418

2419
        if (vd.vd_rewriter.empty()) {
192✔
2420
            continue;
160✔
2421
        }
2422

2423
        auto _sg = ec.enter_source(
2424
            vd_iter->second->vd_rewrite_src_name, 1, vd.vd_rewriter);
32✔
2425
        std::string field_value;
32✔
2426

2427
        auto_mem<FILE> tmpout(fclose);
32✔
2428

2429
        tmpout = std::tmpfile();
32✔
2430
        if (!tmpout) {
32✔
2431
            log_error("unable to create temporary file");
×
2432
            return;
×
2433
        }
2434
        fcntl(fileno(tmpout), F_SETFD, FD_CLOEXEC);
32✔
2435
        auto fd_copy = auto_fd::dup_of(fileno(tmpout));
32✔
2436
        fd_copy.close_on_exec();
32✔
2437
        auto ec_out = std::make_pair(tmpout.release(), fclose);
32✔
2438
        {
2439
            exec_context::output_guard og(ec, "tmp", ec_out);
64✔
2440

2441
            auto exec_res = execute_any(ec, vd.vd_rewriter);
32✔
2442
            if (exec_res.isOk()) {
32✔
2443
                field_value = exec_res.unwrap();
32✔
2444
            } else {
2445
                field_value = exec_res.unwrapErr().to_attr_line().get_string();
×
2446
            }
2447
        }
32✔
2448
        struct stat st;
2449
        fstat(fd_copy.get(), &st);
32✔
2450
        if (st.st_size > 0) {
32✔
2451
            auto buf = auto_buffer::alloc(st.st_size);
2✔
2452

2453
            buf.resize(st.st_size);
2✔
2454
            pread(fd_copy.get(), buf.in(), st.st_size, 0);
2✔
2455
            field_value = buf.to_string();
2✔
2456
        }
2✔
2457
        value_out.erase(iter->lv_origin.lr_start, iter->lv_origin.length());
32✔
2458

2459
        int32_t shift_amount
2460
            = ((int32_t) field_value.length()) - iter->lv_origin.length();
32✔
2461
        auto orig_lr = iter->lv_origin;
32✔
2462
        value_out.insert(iter->lv_origin.lr_start, field_value);
32✔
2463
        for (auto shift_iter = values.lvv_values.begin();
32✔
2464
             shift_iter != values.lvv_values.end();
180✔
2465
             ++shift_iter)
148✔
2466
        {
2467
            shift_iter->lv_origin.shift_range(orig_lr, shift_amount);
148✔
2468
        }
2469
        shift_string_attrs(sa, orig_lr, shift_amount);
32✔
2470
    }
32✔
2471
}
2472

2473
static int
2474
read_json_field(yajlpp_parse_context* ypc,
164,048✔
2475
                const unsigned char* str,
2476
                size_t len,
2477
                yajl_string_props_t* props)
2478
{
2479
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
164,048✔
2480
    timeval tv_out;
2481
    const auto frag = string_fragment::from_bytes(str, len);
164,048✔
2482
    intern_string_t field_name;
164,048✔
2483
    const auto* vd = jlu->get_field_def(ypc);
164,048✔
2484

2485
    if (vd != nullptr) {
164,048✔
2486
        field_name = vd->vd_meta.lvm_name;
13,845✔
2487
    }
2488

2489
    if (field_name.empty()) {
164,048✔
2490
        if (!jlu->jlu_format->elf_opid_field.empty()) {
150,203✔
2491
            auto path_sf = ypc->get_path_as_string_fragment();
46,466✔
2492
            if (path_sf.startswith(jlu->jlu_format->elf_opid_field.c_str())) {
46,466✔
2493
                jlu->jlu_opid_hasher.update(path_sf);
8,985✔
2494
                jlu->jlu_opid_hasher.update(frag);
8,985✔
2495
            }
2496
        }
2497
    } else if (jlu->jlu_format->lf_timestamp_field == field_name) {
13,845✔
2498
        const auto* last = jlu->jlu_format->lf_date_time.scan(
3,115✔
2499
            (const char*) str,
2500
            len,
2501
            jlu->jlu_format->get_timestamp_formats(),
3,115✔
2502
            &jlu->jlu_exttm,
2503
            tv_out);
2504
        if (last == nullptr) {
3,115✔
2505
            auto ls = jlu->jlu_format->lf_date_time.unlock();
22✔
2506
            if ((last = jlu->jlu_format->lf_date_time.scan(
22✔
2507
                     (const char*) str,
2508
                     len,
2509
                     jlu->jlu_format->get_timestamp_formats(),
22✔
2510
                     &jlu->jlu_exttm,
2511
                     tv_out))
2512
                == nullptr)
22✔
2513
            {
2514
                jlu->jlu_format->lf_date_time.relock(ls);
×
2515
            }
2516
            if (last != nullptr) {
22✔
2517
                auto old_flags
22✔
2518
                    = jlu->jlu_format->lf_timestamp_flags & DATE_TIME_SET_FLAGS;
22✔
2519
                auto new_flags = jlu->jlu_exttm.et_flags & DATE_TIME_SET_FLAGS;
22✔
2520

2521
                // It is unlikely a valid timestamp would lose much
2522
                // precision.
2523
                if (new_flags != old_flags) {
22✔
2524
                    last = nullptr;
×
2525
                }
2526
            }
2527
        }
2528
        if (last != nullptr) {
3,115✔
2529
            jlu->jlu_format->lf_timestamp_flags = jlu->jlu_exttm.et_flags;
3,115✔
2530
            jlu->jlu_base_line->set_time(tv_out);
3,115✔
2531
        }
2532
    } else if (jlu->jlu_format->elf_level_pointer.pp_value != nullptr) {
10,730✔
2533
        if (jlu->jlu_format->elf_level_pointer.pp_value
230✔
2534
                ->find_in(field_name.to_string_fragment(), PCRE2_NO_UTF_CHECK)
230✔
2535
                .ignore_error()
230✔
2536
                .has_value())
115✔
2537
        {
2538
            jlu->jlu_base_line->set_level(
×
2539
                jlu->jlu_format->convert_level(frag, jlu->jlu_batch_context));
×
2540
        }
2541
    }
2542
    if (!field_name.empty() && jlu->jlu_format->elf_level_field == field_name) {
164,048✔
2543
        jlu->jlu_base_line->set_level(
3,375✔
2544
            jlu->jlu_format->convert_level(frag, jlu->jlu_batch_context));
3,375✔
2545
    }
2546
    if (!field_name.empty() && jlu->jlu_format->elf_opid_field == field_name) {
164,048✔
2547
        jlu->jlu_base_line->merge_bloom_bits(frag.bloom_bits());
164✔
2548

2549
        auto& sbc = *jlu->jlu_batch_context;
164✔
2550
        auto opid_iter = sbc.sbc_opids.los_opid_ranges.find(frag);
164✔
2551
        if (opid_iter == sbc.sbc_opids.los_opid_ranges.end()) {
164✔
2552
            jlu->jlu_opid_frag = frag.to_owned(sbc.sbc_allocator);
141✔
2553
        } else {
2554
            jlu->jlu_opid_frag = opid_iter->first;
23✔
2555
        }
2556
    }
2557
    if (!field_name.empty()
164,048✔
2558
        && jlu->jlu_format->elf_thread_id_field == field_name)
164,048✔
2559
    {
2560
        auto& sbc = *jlu->jlu_batch_context;
×
2561
        auto tid_iter = sbc.sbc_tids.ltis_tid_ranges.find(frag);
×
2562
        if (tid_iter == sbc.sbc_tids.ltis_tid_ranges.end()) {
×
2563
            jlu->jlu_tid_frag = frag.to_owned(sbc.sbc_allocator);
×
2564
        } else {
2565
            jlu->jlu_tid_frag = tid_iter->first;
×
2566
        }
2567
    }
2568
    if (!jlu->jlu_format->elf_subid_field.empty()
164,048✔
2569
        && jlu->jlu_format->elf_subid_field == field_name)
164,048✔
2570
    {
2571
        jlu->jlu_subid = frag.to_string();
×
2572
    }
2573
    if (!field_name.empty()
164,048✔
2574
        && jlu->jlu_format->elf_duration_field == field_name)
164,048✔
2575
    {
2576
        auto from_res = humanize::try_from<double>(frag);
×
2577
        if (from_res) {
×
2578
            jlu->jlu_duration = std::chrono::microseconds(
×
2579
                static_cast<int64_t>(from_res.value() * 1000000));
2580
        }
2581
    }
2582

2583
    if (vd != nullptr && vd->vd_is_desc_field) {
164,048✔
2584
        auto frag_copy = frag.to_owned(jlu->jlu_format->lf_desc_allocator);
42✔
2585

2586
        jlu->jlu_format->lf_desc_captures.emplace(field_name, frag_copy);
42✔
2587
    }
2588

2589
    jlu->add_sub_lines_for(vd, ypc->is_level(1), std::nullopt, str, len, props);
164,048✔
2590

2591
    return 1;
164,048✔
2592
}
2593

2594
static int
2595
rewrite_json_field(yajlpp_parse_context* ypc,
69,356✔
2596
                   const unsigned char* str,
2597
                   size_t len,
2598
                   yajl_string_props_t* props)
2599
{
2600
    static const intern_string_t body_name = intern_string::lookup("body", -1);
69,356✔
2601
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
69,356✔
2602
    intern_string_t field_name;
69,356✔
2603
    const auto* vd = jlu->get_field_def(ypc);
69,356✔
2604
    auto frag = string_fragment::from_bytes(str, len);
69,356✔
2605

2606
    if (!ypc->is_level(1) && vd == nullptr) {
69,356✔
2607
        if (!jlu->jlu_format->elf_opid_field.empty()) {
57,395✔
2608
            auto path_sf = ypc->get_path_as_string_fragment();
56,737✔
2609
            if (path_sf.startswith(jlu->jlu_format->elf_opid_field.c_str())) {
56,737✔
2610
                jlu->jlu_opid_hasher.update(path_sf);
51✔
2611
                jlu->jlu_opid_hasher.update(frag);
51✔
2612
            }
2613
        }
2614
        return 1;
57,395✔
2615
    }
2616
    if (vd != nullptr) {
11,961✔
2617
        field_name = vd->vd_meta.lvm_name;
11,401✔
2618
    } else {
2619
        field_name = ypc->get_path();
560✔
2620
    }
2621

2622
    if (jlu->jlu_format->elf_opid_field == field_name) {
11,961✔
2623
        jlu->jlu_format->jlf_line_values.lvv_opid_value = frag.to_string();
967✔
2624
        jlu->jlu_format->jlf_line_values.lvv_opid_provenance
967✔
2625
            = logline_value_vector::opid_provenance::file;
967✔
2626
    }
2627
    if (jlu->jlu_format->elf_thread_id_field == field_name) {
11,961✔
NEW
2628
        jlu->jlu_format->jlf_line_values.lvv_thread_id_value = frag.to_string();
×
2629
    }
2630
    if (jlu->jlu_format->lf_timestamp_field == field_name) {
11,961✔
2631
        char time_buf[64];
2632

2633
        // TODO add a timeval kind to logline_value
2634
        if (jlu->jlu_line->is_time_skewed()
2,229✔
2635
            || (jlu->jlu_format->lf_timestamp_flags
4,458✔
2636
                & (ETF_MICROS_SET | ETF_NANOS_SET | ETF_ZONE_SET)))
2,229✔
2637
        {
2638
            timeval tv;
2639

2640
            const auto* last = jlu->jlu_format->lf_date_time.scan(
2,229✔
2641
                (const char*) str,
2642
                len,
2643
                jlu->jlu_format->get_timestamp_formats(),
2,229✔
2644
                &jlu->jlu_exttm,
2645
                tv);
2646
            if (last == nullptr) {
2,229✔
2647
                auto ls = jlu->jlu_format->lf_date_time.unlock();
58✔
2648
                if ((last = jlu->jlu_format->lf_date_time.scan(
58✔
2649
                         (const char*) str,
2650
                         len,
2651
                         jlu->jlu_format->get_timestamp_formats(),
58✔
2652
                         &jlu->jlu_exttm,
2653
                         tv))
2654
                    == nullptr)
58✔
2655
                {
2656
                    jlu->jlu_format->lf_date_time.relock(ls);
×
2657
                }
2658
            }
2659
            if (!jlu->jlu_subline_opts.hash_hack) {
2,229✔
2660
                if (jlu->jlu_exttm.et_flags & ETF_ZONE_SET
2,229✔
2661
                    && jlu->jlu_format->lf_date_time.dts_zoned_to_local)
2,229✔
2662
                {
2663
                    jlu->jlu_exttm.et_flags &= ~ETF_Z_IS_UTC;
2,229✔
2664
                }
2665
                jlu->jlu_exttm.et_gmtoff
2666
                    = jlu->jlu_format->lf_date_time.dts_local_offset_cache;
2,229✔
2667
            }
2668
            jlu->jlu_format->lf_date_time.ftime(
2,229✔
2669
                time_buf,
2670
                sizeof(time_buf),
2671
                jlu->jlu_format->get_timestamp_formats(),
2,229✔
2672
                jlu->jlu_exttm);
2,229✔
2673
        } else {
2674
            sql_strftime(
×
2675
                time_buf, sizeof(time_buf), jlu->jlu_line->get_timeval(), 'T');
×
2676
        }
2677
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
4,458✔
2678
            jlu->jlu_format->get_value_meta(field_name,
4,458✔
2679
                                            value_kind_t::VALUE_TEXT),
2680
            std::string{time_buf});
6,687✔
2681
    } else if (jlu->jlu_shared_buffer.contains((const char*) str)) {
9,732✔
2682
        auto str_offset = (int) ((const char*) str - jlu->jlu_line_value);
9,326✔
2683
        if (field_name == jlu->jlu_format->elf_body_field) {
9,326✔
2684
            jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
853✔
2685
                logline_value_meta(body_name,
1,706✔
2686
                                   value_kind_t::VALUE_TEXT,
2687
                                   logline_value_meta::internal_column{},
×
2688
                                   jlu->jlu_format),
853✔
2689
                string_fragment::from_byte_range(
1,706✔
2690
                    jlu->jlu_shared_buffer.get_data(),
853✔
2691
                    str_offset,
2692
                    str_offset + len));
853✔
2693
        }
2694

2695
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
9,326✔
2696
            jlu->jlu_format->get_value_meta(field_name,
18,652✔
2697
                                            value_kind_t::VALUE_TEXT),
2698
            string_fragment::from_byte_range(jlu->jlu_shared_buffer.get_data(),
18,652✔
2699
                                             str_offset,
2700
                                             str_offset + len));
9,326✔
2701
    } else {
2702
        if (field_name == jlu->jlu_format->elf_body_field) {
406✔
2703
            jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
315✔
2704
                logline_value_meta(body_name,
630✔
2705
                                   value_kind_t::VALUE_TEXT,
2706
                                   logline_value_meta::internal_column{},
×
2707
                                   jlu->jlu_format),
315✔
2708
                std::string{(const char*) str, len});
1,260✔
2709
        }
2710

2711
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
406✔
2712
            jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_TEXT),
812✔
2713
            std::string{(const char*) str, len});
1,624✔
2714
    }
2715
    if (vd != nullptr && vd->vd_is_desc_field
11,401✔
2716
        && jlu->jlu_format->elf_opid_field.empty())
23,362✔
2717
    {
2718
        auto frag_copy = frag.to_owned(jlu->jlu_format->lf_desc_allocator);
46✔
2719

2720
        jlu->jlu_format->lf_desc_captures.emplace(field_name, frag_copy);
46✔
2721
    }
2722

2723
    return 1;
11,961✔
2724
}
2725

2726
void
2727
external_log_format::get_subline(const log_format_file_state& lffs,
23,783✔
2728
                                 const logline& ll,
2729
                                 shared_buffer_ref& sbr,
2730
                                 subline_options opts)
2731
{
2732
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT) {
23,783✔
2733
        return;
19,134✔
2734
    }
2735

2736
    if (this->jlf_cached_offset != ll.get_offset()
4,649✔
2737
        || this->jlf_cached_opts != opts)
4,649✔
2738
    {
2739
        auto& ypc = *(this->jlf_parse_context);
2,448✔
2740
        yajl_handle handle = this->jlf_yajl_handle.get();
2,448✔
2741
        json_log_userdata jlu(sbr, nullptr);
2,448✔
2742

2743
        jlu.jlu_subline_opts = opts;
2,448✔
2744

2745
        this->lf_desc_captures.clear();
2,448✔
2746
        this->lf_desc_allocator.reset();
2,448✔
2747
        this->jlf_share_manager.invalidate_refs();
2,448✔
2748
        this->jlf_cached_line.clear();
2,448✔
2749
        this->jlf_line_values.clear();
2,448✔
2750
        this->jlf_line_offsets.clear();
2,448✔
2751
        this->jlf_line_attrs.clear();
2,448✔
2752

2753
        auto line_frag = sbr.to_string_fragment();
2,448✔
2754

2755
        if (!line_frag.startswith("{")) {
2,448✔
2756
            this->jlf_cached_line.resize(line_frag.length());
72✔
2757
            memcpy(this->jlf_cached_line.data(),
72✔
2758
                   line_frag.data(),
72✔
2759
                   line_frag.length());
72✔
2760
            this->jlf_line_values.clear();
72✔
2761
            sbr.share(this->jlf_share_manager,
144✔
2762
                      &this->jlf_cached_line[0],
72✔
2763
                      this->jlf_cached_line.size());
2764
            this->jlf_line_values.lvv_sbr = sbr.clone();
72✔
2765
            this->jlf_line_attrs.emplace_back(
72✔
2766
                line_range{0, -1},
×
2767
                SA_INVALID.value(fmt::format(
144✔
2768
                    FMT_STRING("line at offset {} is not a JSON-line"),
144✔
2769
                    ll.get_offset())));
72✔
2770
            return;
72✔
2771
        }
2772

2773
        yajl_reset(handle);
2,376✔
2774
        ypc.set_static_handler(json_log_rewrite_handlers.jpc_children[0]);
2,376✔
2775
        ypc.ypc_userdata = &jlu;
2,376✔
2776
        ypc.ypc_ignore_unused = true;
2,376✔
2777
        ypc.ypc_alt_callbacks.yajl_start_array = json_array_start_const;
2,376✔
2778
        ypc.ypc_alt_callbacks.yajl_end_array = json_array_end;
2,376✔
2779
        ypc.ypc_alt_callbacks.yajl_start_map = json_array_start_const;
2,376✔
2780
        ypc.ypc_alt_callbacks.yajl_end_map = json_array_end;
2,376✔
2781
        jlu.jlu_format = this;
2,376✔
2782
        jlu.jlu_line = &ll;
2,376✔
2783
        jlu.jlu_handle = handle;
2,376✔
2784
        jlu.jlu_line_value = sbr.get_data();
2,376✔
2785
        jlu.jlu_format_hits.resize(this->jlf_line_format.size());
2,376✔
2786

2787
        yajl_status parse_status = yajl_parse(
4,752✔
2788
            handle, (const unsigned char*) sbr.get_data(), sbr.length());
2,376✔
2789
        if (parse_status != yajl_status_ok
2,376✔
2790
            || yajl_complete_parse(handle) != yajl_status_ok)
2,376✔
2791
        {
2792
            unsigned char* msg;
2793
            std::string full_msg;
14✔
2794

2795
            msg = yajl_get_error(
28✔
2796
                handle, 1, (const unsigned char*) sbr.get_data(), sbr.length());
14✔
2797
            if (msg != nullptr) {
14✔
2798
                full_msg = fmt::format(
14✔
2799
                    FMT_STRING("[offset: {}] {}\n{}"),
28✔
2800
                    ll.get_offset(),
14✔
2801
                    fmt::string_view{sbr.get_data(), sbr.length()},
14✔
2802
                    reinterpret_cast<char*>(msg));
28✔
2803
                yajl_free_error(handle, msg);
14✔
2804
            }
2805

2806
            this->jlf_cached_line.resize(full_msg.size());
14✔
2807
            memcpy(
14✔
2808
                this->jlf_cached_line.data(), full_msg.data(), full_msg.size());
14✔
2809
            this->jlf_line_values.clear();
14✔
2810
            this->jlf_line_attrs.emplace_back(
14✔
2811
                line_range{0, -1},
×
2812
                SA_INVALID.value("JSON line failed to parse"));
28✔
2813
        } else {
14✔
2814
            std::vector<logline_value>::iterator lv_iter;
2,362✔
2815
            bool used_values[this->jlf_line_values.lvv_values.size()];
4,724✔
2816
            struct line_range lr;
2,362✔
2817

2818
            memset(used_values, 0, sizeof(used_values));
2,362✔
2819
            for (lv_iter = this->jlf_line_values.lvv_values.begin();
2,362✔
2820
                 lv_iter != this->jlf_line_values.lvv_values.end();
21,047✔
2821
                 ++lv_iter)
18,685✔
2822
            {
2823
                lv_iter->lv_meta.lvm_format = this;
18,685✔
2824
            }
2825

2826
            if (jlu.jlu_tid_number) {
2,362✔
2827
                this->jlf_line_values.lvv_thread_id_value
2828
                    = fmt::to_string(jlu.jlu_tid_number.value());
147✔
2829
            } else if (jlu.jlu_tid_frag) {
2,215✔
2830
                this->jlf_line_values.lvv_thread_id_value
2831
                    = jlu.jlu_tid_frag->to_string();
×
2832
            }
2833

2834
            if (this->elf_opid_field.empty()
2,362✔
2835
                && this->lf_opid_source.value_or(
1,350✔
2836
                       opid_source_t::from_description)
1,350✔
2837
                    == opid_source_t::from_description
2838
                && this->lf_opid_description_def->size() == 1)
3,712✔
2839
            {
2840
                auto found_opid_desc = false;
209✔
2841
                const auto& od = this->lf_opid_description_def->begin()->second;
209✔
2842
                for (const auto& desc : *od.od_descriptors) {
627✔
2843
                    auto desc_iter
2844
                        = this->lf_desc_captures.find(desc.od_field.pp_value);
418✔
2845
                    if (desc_iter == this->lf_desc_captures.end()) {
418✔
2846
                        continue;
372✔
2847
                    }
2848
                    found_opid_desc = true;
46✔
2849
                    jlu.jlu_opid_hasher.update(desc_iter->second);
46✔
2850
                }
2851
                if (found_opid_desc) {
209✔
2852
                    this->jlf_line_values.lvv_opid_value
2853
                        = jlu.jlu_opid_hasher.to_string();
23✔
2854
                    this->jlf_line_values.lvv_opid_provenance
2855
                        = logline_value_vector::opid_provenance::file;
23✔
2856
                }
2857
            } else if (!jlu.jlu_opid_desc_frag && !jlu.jlu_opid_frag
4,274✔
2858
                       && jlu.jlu_duration > 0us)
4,274✔
2859
            {
2860
                jlu.jlu_opid_hasher.update(line_frag);
×
2861
                this->jlf_line_values.lvv_opid_value
2862
                    = jlu.jlu_opid_hasher.to_string();
×
2863
                this->jlf_line_values.lvv_opid_provenance
2864
                    = logline_value_vector::opid_provenance::file;
×
2865
            }
2866
            if (jlu.jlu_opid_desc_frag) {
2,362✔
2867
                this->jlf_line_values.lvv_opid_value
2868
                    = jlu.jlu_opid_hasher.to_string();
32✔
2869
                this->jlf_line_values.lvv_opid_provenance
2870
                    = logline_value_vector::opid_provenance::file;
32✔
2871
            }
2872
            if (jlu.jlu_opid_frag) {
2,362✔
2873
                this->jlf_line_values.lvv_opid_value
2874
                    = jlu.jlu_opid_frag->to_string();
×
2875
                this->jlf_line_values.lvv_opid_provenance
2876
                    = logline_value_vector::opid_provenance::file;
×
2877
            }
2878

2879
            int sub_offset = this->jlf_line_format_init_count;
2,362✔
2880
            for (const auto& jfe : this->jlf_line_format) {
30,579✔
2881
                static const intern_string_t ts_field
2882
                    = intern_string::lookup("__timestamp__", -1);
28,217✔
2883
                static const intern_string_t level_field
2884
                    = intern_string::lookup("__level__");
28,311✔
2885
                size_t begin_size = this->jlf_cached_line.size();
28,217✔
2886

2887
                switch (jfe.jfe_type) {
28,217✔
2888
                    case json_log_field::CONSTANT:
3,838✔
2889
                        this->json_append_to_cache(
3,838✔
2890
                            jfe.jfe_default_value.c_str(),
2891
                            jfe.jfe_default_value.size());
3,838✔
2892
                        break;
3,838✔
2893
                    case json_log_field::VARIABLE:
24,379✔
2894
                        lv_iter = find_if(
24,379✔
2895
                            this->jlf_line_values.lvv_values.begin(),
2896
                            this->jlf_line_values.lvv_values.end(),
2897
                            logline_value_name_cmp(&jfe.jfe_value.pp_value));
2898
                        if (lv_iter != this->jlf_line_values.lvv_values.end()) {
24,379✔
2899
                            auto str = lv_iter->to_string();
8,681✔
2900
                            value_def* vd = nullptr;
8,681✔
2901

2902
                            if (lv_iter->lv_meta.lvm_values_index) {
8,681✔
2903
                                vd = this->elf_value_def_order
2904
                                         [lv_iter->lv_meta.lvm_values_index
8,681✔
2905
                                              .value()]
8,681✔
2906
                                             .get();
8,681✔
2907
                            }
2908
                            while (endswith(str, "\n")) {
8,943✔
2909
                                str.pop_back();
262✔
2910
                            }
2911
                            size_t nl_pos = str.find('\n');
8,681✔
2912

2913
                            if (!jfe.jfe_prefix.empty()) {
8,681✔
2914
                                this->json_append_to_cache(jfe.jfe_prefix);
4,945✔
2915
                            }
2916
                            lr.lr_start = this->jlf_cached_line.size();
8,681✔
2917

2918
                            if ((int) str.size() > jfe.jfe_max_width) {
8,681✔
2919
                                switch (jfe.jfe_overflow) {
237✔
2920
                                    case json_format_element::overflow_t::
169✔
2921
                                        ABBREV: {
2922
                                        size_t new_size
2923
                                            = abbreviate_str(&str[0],
169✔
2924
                                                             str.size(),
2925
                                                             jfe.jfe_max_width);
169✔
2926
                                        str.resize(new_size);
169✔
2927
                                        this->json_append(lffs, jfe, vd, str);
169✔
2928
                                        break;
169✔
2929
                                    }
2930
                                    case json_format_element::overflow_t::
62✔
2931
                                        TRUNCATE: {
2932
                                        this->json_append_to_cache(
62✔
2933
                                            str.c_str(), jfe.jfe_max_width);
62✔
2934
                                        break;
62✔
2935
                                    }
2936
                                    case json_format_element::overflow_t::
6✔
2937
                                        DOTDOT: {
2938
                                        size_t middle
6✔
2939
                                            = (jfe.jfe_max_width / 2) - 1;
6✔
2940
                                        this->json_append_to_cache(str.c_str(),
6✔
2941
                                                                   middle);
2942
                                        this->json_append_to_cache("..", 2);
6✔
2943
                                        size_t rest
6✔
2944
                                            = (jfe.jfe_max_width - middle - 2);
6✔
2945
                                        this->json_append_to_cache(
12✔
2946
                                            str.c_str() + str.size() - rest,
6✔
2947
                                            rest);
2948
                                        break;
6✔
2949
                                    }
2950
                                    case json_format_element::overflow_t::
×
2951
                                        LASTWORD: {
2952
                                        size_t new_size
2953
                                            = last_word_str(&str[0],
×
2954
                                                            str.size(),
2955
                                                            jfe.jfe_max_width);
×
2956
                                        str.resize(new_size);
×
2957
                                        this->json_append(lffs, jfe, vd, str);
×
2958
                                        break;
×
2959
                                    }
2960
                                }
2961
                            } else {
2962
                                sub_offset
2963
                                    += std::count(str.begin(), str.end(), '\n');
8,444✔
2964
                                this->json_append(lffs, jfe, vd, str);
8,444✔
2965
                            }
2966

2967
                            if (nl_pos == std::string::npos
8,681✔
2968
                                || opts.full_message)
3✔
2969
                            {
2970
                                lr.lr_end = this->jlf_cached_line.size();
8,678✔
2971
                            } else {
2972
                                lr.lr_end = lr.lr_start + nl_pos;
3✔
2973
                            }
2974

2975
                            if (lv_iter->lv_meta.lvm_name
8,681✔
2976
                                == this->lf_timestamp_field)
8,681✔
2977
                            {
2978
                                this->jlf_line_attrs.emplace_back(
1,003✔
2979
                                    lr, L_TIMESTAMP.value());
2,006✔
2980
                            } else if (lv_iter->lv_meta.lvm_name
7,678✔
2981
                                       == this->elf_body_field)
7,678✔
2982
                            {
2983
                                this->jlf_line_attrs.emplace_back(
1,168✔
2984
                                    lr, SA_BODY.value());
2,336✔
2985
                            } else if (lv_iter->lv_meta.lvm_name
6,510✔
2986
                                       == this->elf_src_file_field)
6,510✔
2987
                            {
2988
                                this->jlf_line_attrs.emplace_back(
11✔
2989
                                    lr, SA_SRC_FILE.value());
22✔
2990
                            } else if (lv_iter->lv_meta.lvm_name
6,499✔
2991
                                       == this->elf_src_line_field)
6,499✔
2992
                            {
2993
                                this->jlf_line_attrs.emplace_back(
11✔
2994
                                    lr, SA_SRC_LINE.value());
22✔
2995
                            } else if (lv_iter->lv_meta.lvm_name
6,488✔
2996
                                       == this->elf_thread_id_field)
6,488✔
2997
                            {
2998
                                this->jlf_line_attrs.emplace_back(
88✔
2999
                                    lr, SA_THREAD_ID.value());
176✔
3000
                            } else if (lv_iter->lv_meta.lvm_name
6,400✔
3001
                                       == this->elf_duration_field)
6,400✔
3002
                            {
3003
                                this->jlf_line_attrs.emplace_back(
×
3004
                                    lr, SA_DURATION.value());
×
3005
                            } else if (lv_iter->lv_meta.lvm_name
6,400✔
3006
                                       == this->elf_level_field)
6,400✔
3007
                            {
3008
                                this->jlf_line_attrs.emplace_back(
1,082✔
3009
                                    lr, L_LEVEL.value());
2,164✔
3010
                            } else if (lv_iter->lv_meta.lvm_name
10,636✔
3011
                                           == this->elf_opid_field
5,318✔
3012
                                       && !lr.empty())
5,318✔
3013
                            {
3014
                                this->jlf_line_attrs.emplace_back(
967✔
3015
                                    lr, L_OPID.value());
1,934✔
3016
                            }
3017
                            lv_iter->lv_origin = lr;
8,681✔
3018
                            lv_iter->lv_sub_offset = sub_offset;
8,681✔
3019
                            used_values[std::distance(
8,681✔
3020
                                this->jlf_line_values.lvv_values.begin(),
3021
                                lv_iter)]
3022
                                = true;
8,681✔
3023

3024
                            if (!jfe.jfe_suffix.empty()) {
8,681✔
3025
                                this->json_append_to_cache(jfe.jfe_suffix);
1,332✔
3026
                            }
3027
                        } else if (jfe.jfe_value.pp_value == ts_field) {
24,379✔
3028
                            line_range lr;
1,504✔
3029
                            ssize_t ts_len;
3030
                            char ts[64];
3031
                            exttm et;
1,504✔
3032

3033
                            ll.to_exttm(et);
1,504✔
3034
                            et.et_nsec += jlu.jlu_exttm.et_nsec % 1000;
1,504✔
3035
                            et.et_gmtoff = jlu.jlu_exttm.et_gmtoff;
1,504✔
3036
                            et.et_flags |= jlu.jlu_exttm.et_flags;
1,504✔
3037
                            if (!jfe.jfe_prefix.empty()) {
1,504✔
3038
                                this->json_append_to_cache(jfe.jfe_prefix);
3✔
3039
                            }
3040
                            if (jfe.jfe_ts_format.empty()) {
1,504✔
3041
                                ts_len = this->lf_date_time.ftime(
1,345✔
3042
                                    ts,
3043
                                    sizeof(ts),
3044
                                    this->get_timestamp_formats(),
3045
                                    et);
3046
                            } else {
3047
                                ts_len = ftime_fmt(ts,
159✔
3048
                                                   sizeof(ts),
3049
                                                   jfe.jfe_ts_format.c_str(),
3050
                                                   et);
3051
                            }
3052
                            lr.lr_start = this->jlf_cached_line.size();
1,504✔
3053
                            this->json_append_to_cache(ts, ts_len);
1,504✔
3054
                            lr.lr_end = this->jlf_cached_line.size();
1,504✔
3055
                            this->jlf_line_attrs.emplace_back(
1,504✔
3056
                                lr, L_TIMESTAMP.value());
3,008✔
3057

3058
                            lv_iter = find_if(
1,504✔
3059
                                this->jlf_line_values.lvv_values.begin(),
3060
                                this->jlf_line_values.lvv_values.end(),
3061
                                logline_value_name_cmp(
3062
                                    &this->lf_timestamp_field));
1,504✔
3063
                            if (lv_iter
1,504✔
3064
                                != this->jlf_line_values.lvv_values.end())
1,504✔
3065
                            {
3066
                                used_values[distance(
1,504✔
3067
                                    this->jlf_line_values.lvv_values.begin(),
3068
                                    lv_iter)]
3069
                                    = true;
1,504✔
3070
                            }
3071
                            if (!jfe.jfe_suffix.empty()) {
1,504✔
3072
                                this->json_append_to_cache(jfe.jfe_suffix);
3✔
3073
                            }
3074
                        } else if (jfe.jfe_value.pp_value == level_field
14,194✔
3075
                                   || jfe.jfe_value.pp_value
28,266✔
3076
                                       == this->elf_level_field)
14,072✔
3077
                        {
3078
                            auto level_name = ll.get_level_name();
122✔
3079
                            lr.lr_start = this->jlf_cached_line.size();
122✔
3080
                            this->json_append(lffs, jfe, nullptr, level_name);
122✔
3081
                            if (jfe.jfe_auto_width) {
122✔
3082
                                this->json_append_to_cache(
88✔
3083
                                    MAX_LEVEL_NAME_LEN - level_name.length());
88✔
3084
                            }
3085
                            lr.lr_end = this->jlf_cached_line.size();
122✔
3086
                            this->jlf_line_attrs.emplace_back(lr,
122✔
3087
                                                              L_LEVEL.value());
244✔
3088
                        } else if (!jfe.jfe_default_value.empty()) {
14,072✔
3089
                            if (!jfe.jfe_prefix.empty()) {
124✔
3090
                                this->json_append_to_cache(jfe.jfe_prefix);
×
3091
                            }
3092
                            this->json_append(
124✔
3093
                                lffs, jfe, nullptr, jfe.jfe_default_value);
124✔
3094
                            if (!jfe.jfe_suffix.empty()) {
124✔
3095
                                this->json_append_to_cache(jfe.jfe_suffix);
×
3096
                            }
3097
                        }
3098

3099
                        switch (jfe.jfe_text_transform) {
24,379✔
3100
                            case json_format_element::transform_t::NONE:
24,257✔
3101
                                break;
24,257✔
3102
                            case json_format_element::transform_t::UPPERCASE:
122✔
3103
                                for (size_t cindex = begin_size;
122✔
3104
                                     cindex < this->jlf_cached_line.size();
965✔
3105
                                     cindex++)
3106
                                {
3107
                                    this->jlf_cached_line[cindex] = toupper(
843✔
3108
                                        this->jlf_cached_line[cindex]);
843✔
3109
                                }
3110
                                break;
122✔
3111
                            case json_format_element::transform_t::LOWERCASE:
×
3112
                                for (size_t cindex = begin_size;
×
3113
                                     cindex < this->jlf_cached_line.size();
×
3114
                                     cindex++)
3115
                                {
3116
                                    this->jlf_cached_line[cindex] = tolower(
×
3117
                                        this->jlf_cached_line[cindex]);
×
3118
                                }
3119
                                break;
×
3120
                            case json_format_element::transform_t::CAPITALIZE:
×
3121
                                for (size_t cindex = begin_size;
×
3122
                                     cindex < begin_size + 1;
×
3123
                                     cindex++)
3124
                                {
3125
                                    this->jlf_cached_line[cindex] = toupper(
×
3126
                                        this->jlf_cached_line[cindex]);
×
3127
                                }
3128
                                for (size_t cindex = begin_size + 1;
×
3129
                                     cindex < this->jlf_cached_line.size();
×
3130
                                     cindex++)
3131
                                {
3132
                                    this->jlf_cached_line[cindex] = tolower(
×
3133
                                        this->jlf_cached_line[cindex]);
×
3134
                                }
3135
                                break;
×
3136
                        }
3137
                        break;
24,379✔
3138
                }
3139
            }
3140
            this->json_append_to_cache("\n", 1);
2,362✔
3141
            sub_offset += 1;
2,362✔
3142

3143
            for (size_t lpc = 0; lpc < this->jlf_line_values.lvv_values.size();
21,047✔
3144
                 lpc++)
3145
            {
3146
                static const intern_string_t body_name
3147
                    = intern_string::lookup("body", -1);
18,685✔
3148
                auto& lv = this->jlf_line_values.lvv_values[lpc];
18,685✔
3149

3150
                if (lv.lv_meta.is_hidden() || used_values[lpc]
28,659✔
3151
                    || body_name == lv.lv_meta.lvm_name)
28,659✔
3152
                {
3153
                    continue;
17,541✔
3154
                }
3155

3156
                auto str = lv.to_string();
1,144✔
3157
                while (endswith(str, "\n")) {
1,144✔
3158
                    str.pop_back();
×
3159
                }
3160

3161
                lv.lv_sub_offset = sub_offset;
1,144✔
3162
                lv.lv_origin.lr_start = this->jlf_cached_line.size() + 2
1,144✔
3163
                    + lv.lv_meta.lvm_name.size() + 2;
1,144✔
3164
                auto frag = string_fragment::from_str(str);
1,144✔
3165
                while (true) {
3166
                    auto utf_scan_res = is_utf8(frag, '\n');
1,150✔
3167

3168
                    this->json_append_to_cache("  ", 2);
1,150✔
3169
                    this->json_append_to_cache(
1,150✔
3170
                        lv.lv_meta.lvm_name.to_string_fragment());
1,150✔
3171
                    this->json_append_to_cache(": ", 2);
1,150✔
3172
                    lr.lr_start = this->jlf_cached_line.size();
1,150✔
3173
                    this->json_append_to_cache(utf_scan_res.usr_valid_frag);
1,150✔
3174
                    lr.lr_end = this->jlf_cached_line.size();
1,150✔
3175
                    if (lv.lv_meta.lvm_name == this->elf_body_field) {
1,150✔
3176
                        this->jlf_line_attrs.emplace_back(lr, SA_BODY.value());
×
3177
                    } else {
3178
                        this->jlf_line_attrs.emplace_back(
1,150✔
3179
                            lr, SA_EXTRA_CONTENT.value());
2,300✔
3180
                    }
3181
                    this->json_append_to_cache("\n", 1);
1,150✔
3182
                    sub_offset += 1;
1,150✔
3183
                    if (utf_scan_res.usr_remaining) {
1,150✔
3184
                        frag = utf_scan_res.usr_remaining.value();
6✔
3185
                    } else {
3186
                        break;
1,144✔
3187
                    }
3188
                }
6✔
3189
                lv.lv_origin.lr_end = this->jlf_cached_line.size() - 1;
1,144✔
3190
                if (lv.lv_meta.lvm_name == this->elf_opid_field
1,144✔
3191
                    && !lv.lv_origin.empty())
1,144✔
3192
                {
3193
                    this->jlf_line_attrs.emplace_back(lv.lv_origin,
×
3194
                                                      L_OPID.value());
×
3195
                }
3196
            }
1,144✔
3197
        }
2,362✔
3198

3199
        this->jlf_line_offsets.push_back(0);
2,376✔
3200
        for (size_t lpc = 0; lpc < this->jlf_cached_line.size(); lpc++) {
267,735✔
3201
            if (this->jlf_cached_line[lpc] == '\n') {
265,359✔
3202
                this->jlf_line_offsets.push_back(lpc + 1);
4,306✔
3203
            }
3204
        }
3205
        this->jlf_line_offsets.push_back(this->jlf_cached_line.size());
2,376✔
3206
        this->jlf_cached_offset = ll.get_offset();
2,376✔
3207
        this->jlf_cached_opts = opts;
2,376✔
3208
    }
2,448✔
3209

3210
    off_t this_off = 0, next_off = 0;
4,577✔
3211

3212
    if (!this->jlf_line_offsets.empty()
4,577✔
3213
        && ll.get_sub_offset() < this->jlf_line_offsets.size())
4,577✔
3214
    {
3215
        require(ll.get_sub_offset() < this->jlf_line_offsets.size());
4,577✔
3216

3217
        this_off = this->jlf_line_offsets[ll.get_sub_offset()];
4,577✔
3218
        if ((ll.get_sub_offset() + 1) < (int) this->jlf_line_offsets.size()) {
4,577✔
3219
            next_off = this->jlf_line_offsets[ll.get_sub_offset() + 1];
4,577✔
3220
        } else {
3221
            next_off = this->jlf_cached_line.size();
×
3222
        }
3223
        if (next_off > 0 && this->jlf_cached_line[next_off - 1] == '\n'
4,577✔
3224
            && this_off != next_off)
9,154✔
3225
        {
3226
            next_off -= 1;
4,577✔
3227
        }
3228
    }
3229

3230
    if (opts.full_message) {
4,577✔
3231
        sbr.share(this->jlf_share_manager,
642✔
3232
                  &this->jlf_cached_line[0],
321✔
3233
                  this->jlf_cached_line.size());
3234
    } else {
3235
        sbr.share(this->jlf_share_manager,
8,512✔
3236
                  this->jlf_cached_line.data() + this_off,
4,256✔
3237
                  next_off - this_off);
4,256✔
3238
    }
3239
    sbr.get_metadata().m_valid_utf = ll.is_valid_utf();
4,577✔
3240
    sbr.get_metadata().m_has_ansi = ll.has_ansi();
4,577✔
3241
    this->jlf_cached_sub_range.lr_start = this_off;
4,577✔
3242
    this->jlf_cached_sub_range.lr_end = next_off;
4,577✔
3243
    this->jlf_line_values.lvv_sbr = sbr.clone();
4,577✔
3244
}
3245

3246
struct compiled_header_expr {
3247
    auto_mem<sqlite3_stmt> che_stmt{sqlite3_finalize};
3248
    bool che_enabled{true};
3249
};
3250

3251
struct format_header_expressions : public lnav_config_listener {
3252
    format_header_expressions() : lnav_config_listener(__FILE__) {}
1,167✔
3253

3254
    auto_sqlite3 e_db;
3255
    std::map<intern_string_t, std::map<std::string, compiled_header_expr>>
3256
        e_header_exprs;
3257
};
3258

3259
using safe_format_header_expressions = safe::Safe<format_header_expressions>;
3260

3261
static safe_format_header_expressions format_header_exprs;
3262

3263
std::optional<external_file_format>
3264
detect_mime_type(const std::filesystem::path& filename)
609✔
3265
{
3266
    uint8_t buffer[1024];
3267
    size_t buffer_size = 0;
609✔
3268

3269
    {
3270
        auto_fd fd;
609✔
3271

3272
        if ((fd = lnav::filesystem::openp(filename, O_RDONLY)) == -1) {
609✔
3273
            return std::nullopt;
×
3274
        }
3275

3276
        ssize_t rc;
3277

3278
        if ((rc = read(fd, buffer, sizeof(buffer))) == -1) {
609✔
3279
            return std::nullopt;
×
3280
        }
3281
        buffer_size = rc;
609✔
3282
    }
609✔
3283

3284
    auto hexbuf = auto_buffer::alloc(buffer_size * 2);
609✔
3285

3286
    for (size_t lpc = 0; lpc < buffer_size; lpc++) {
324,715✔
3287
        fmt::format_to(
324,106✔
3288
            std::back_inserter(hexbuf), FMT_STRING("{:02x}"), buffer[lpc]);
1,296,424✔
3289
    }
3290

3291
    safe::WriteAccess<safe_format_header_expressions> in(format_header_exprs);
609✔
3292

3293
    for (const auto& format : log_format::get_root_formats()) {
45,572✔
3294
        auto elf = std::dynamic_pointer_cast<external_log_format>(format);
44,963✔
3295
        if (elf == nullptr) {
44,963✔
3296
            continue;
3,045✔
3297
        }
3298

3299
        if (elf->elf_converter.c_header.h_exprs.he_exprs.empty()) {
41,918✔
3300
            continue;
41,309✔
3301
        }
3302

3303
        if (buffer_size < elf->elf_converter.c_header.h_size) {
609✔
3304
            log_debug(
21✔
3305
                "%s: file content too small (%zu) for header detection: %s",
3306
                filename.c_str(),
3307
                buffer_size,
3308
                elf->get_name().get());
3309
            continue;
21✔
3310
        }
3311
        for (const auto& hpair : elf->elf_converter.c_header.h_exprs.he_exprs) {
2,940✔
3312
            auto& he = in->e_header_exprs[elf->get_name()][hpair.first];
2,352✔
3313

3314
            if (!he.che_enabled) {
2,352✔
3315
                continue;
×
3316
            }
3317

3318
            auto* stmt = he.che_stmt.in();
2,352✔
3319

3320
            if (stmt == nullptr) {
2,352✔
3321
                continue;
×
3322
            }
3323
            sqlite3_reset(stmt);
2,352✔
3324
            auto count = sqlite3_bind_parameter_count(stmt);
2,352✔
3325
            for (int lpc = 0; lpc < count; lpc++) {
4,704✔
3326
                const auto* name = sqlite3_bind_parameter_name(stmt, lpc + 1);
2,352✔
3327

3328
                if (name[0] == '$') {
2,352✔
3329
                    const char* env_value;
3330

3331
                    if ((env_value = getenv(&name[1])) != nullptr) {
×
3332
                        sqlite3_bind_text(
×
3333
                            stmt, lpc + 1, env_value, -1, SQLITE_STATIC);
3334
                    }
3335
                    continue;
×
3336
                }
3337
                if (strcmp(name, ":header") == 0) {
2,352✔
3338
                    sqlite3_bind_text(stmt,
2,352✔
3339
                                      lpc + 1,
3340
                                      hexbuf.in(),
2,352✔
3341
                                      hexbuf.size(),
2,352✔
3342
                                      SQLITE_STATIC);
3343
                    continue;
2,352✔
3344
                }
3345
                if (strcmp(name, ":filepath") == 0) {
×
3346
                    sqlite3_bind_text(
×
3347
                        stmt, lpc + 1, filename.c_str(), -1, SQLITE_STATIC);
3348
                    continue;
×
3349
                }
3350
            }
3351

3352
            auto step_res = sqlite3_step(stmt);
2,352✔
3353

3354
            switch (step_res) {
2,352✔
3355
                case SQLITE_OK:
2,352✔
3356
                case SQLITE_DONE:
3357
                    continue;
2,352✔
3358
                case SQLITE_ROW:
×
3359
                    break;
×
3360
                default: {
×
3361
                    log_error(
×
3362
                        "failed to execute file-format header expression: "
3363
                        "%s:%s -- %s",
3364
                        elf->get_name().get(),
3365
                        hpair.first.c_str(),
3366
                        sqlite3_errmsg(in->e_db));
3367
                    he.che_enabled = false;
×
3368
                    continue;
×
3369
                }
3370
            }
3371

3372
            log_info("detected format for: %s -- %s (header-expr: %s)",
×
3373
                     filename.c_str(),
3374
                     elf->get_name().get(),
3375
                     hpair.first.c_str());
3376
            return external_file_format{
×
3377
                elf->get_name().to_string(),
×
3378
                elf->elf_converter.c_command.pp_value,
×
3379
                elf->elf_converter.c_command.pp_location.sl_source.to_string(),
×
3380
            };
3381
        }
3382
    }
44,963✔
3383

3384
    return std::nullopt;
609✔
3385
}
609✔
3386

3387
log_format::scan_result_t
3388
log_format::test_line(sample_t& sample,
×
3389
                      std::vector<lnav::console::user_message>& msgs)
3390
{
3391
    return scan_no_match{};
×
3392
}
3393

3394
log_format::scan_result_t
3395
external_log_format::test_line(sample_t& sample,
184,544✔
3396
                               std::vector<lnav::console::user_message>& msgs)
3397
{
3398
    auto lines
3399
        = string_fragment::from_str(sample.s_line.pp_value).split_lines();
184,544✔
3400

3401
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
184,544✔
3402
        auto alloc = ArenaAlloc::Alloc<char>{};
2,243✔
3403
        pattern_locks pats;
2,243✔
3404
        auto sbc = scan_batch_context{
2,243✔
3405
            alloc,
3406
            pats,
3407
        };
2,243✔
3408
        sbc.sbc_value_stats.resize(this->elf_value_defs.size());
2,243✔
3409
        std::vector<logline> dst;
2,243✔
3410
        auto li = line_info{
2,243✔
3411
            {0, lines[0].length()},
2,243✔
3412
        };
2,243✔
3413
        shared_buffer sb;
2,243✔
3414
        shared_buffer_ref sbr;
2,243✔
3415
        sbr.share(sb, lines[0].data(), (size_t) lines[0].length());
2,243✔
3416

3417
        return this->scan_json(dst, li, sbr, sbc);
2,243✔
3418
    }
2,243✔
3419

3420
    scan_result_t retval = scan_no_match{"no patterns matched"};
182,301✔
3421
    auto found = false;
182,301✔
3422

3423
    for (auto pat_iter = this->elf_pattern_order.begin();
182,301✔
3424
         pat_iter != this->elf_pattern_order.end();
1,371,768✔
3425
         ++pat_iter)
1,189,467✔
3426
    {
3427
        auto& pat = *(*pat_iter);
1,189,467✔
3428

3429
        if (!pat.p_pcre.pp_value) {
1,189,467✔
3430
            continue;
1,007,168✔
3431
        }
3432

3433
        auto md = pat.p_pcre.pp_value->create_match_data();
1,189,467✔
3434
        auto match_res = pat.p_pcre.pp_value->capture_from(lines[0])
1,189,467✔
3435
                             .into(md)
1,189,467✔
3436
                             .matches(PCRE2_NO_UTF_CHECK)
2,378,934✔
3437
                             .ignore_error();
1,189,467✔
3438
        if (!match_res) {
1,189,467✔
3439
            continue;
1,007,168✔
3440
        }
3441
        retval = scan_match{1000};
182,299✔
3442
        found = true;
182,299✔
3443

3444
        sample.s_matched_regexes.insert(pat.p_name.to_string());
182,299✔
3445

3446
        const auto ts_cap = md[pat.p_timestamp_field_index];
182,299✔
3447
        const auto level_cap = md[pat.p_level_field_index];
182,299✔
3448
        const char* const* custom_formats = this->get_timestamp_formats();
182,299✔
3449
        date_time_scanner dts;
182,299✔
3450
        timeval tv;
3451
        exttm tm;
182,299✔
3452

3453
        if (ts_cap && ts_cap->sf_begin == 0) {
182,299✔
3454
            pat.p_timestamp_end = ts_cap->sf_end;
111,692✔
3455
        }
3456
        const char* dts_scan_res = nullptr;
182,299✔
3457

3458
        if (ts_cap) {
182,299✔
3459
            dts_scan_res = dts.scan(
182,297✔
3460
                ts_cap->data(), ts_cap->length(), custom_formats, &tm, tv);
182,297✔
3461
        }
3462
        if (dts_scan_res != nullptr) {
182,299✔
3463
            if (dts_scan_res != ts_cap->data() + ts_cap->length()) {
182,296✔
3464
                auto match_len = dts_scan_res - ts_cap->data();
×
3465
                auto notes = attr_line_t("the used timestamp format: ");
×
3466
                if (custom_formats == nullptr) {
×
3467
                    notes.append(PTIMEC_FORMATS[dts.dts_fmt_lock].pf_fmt);
×
3468
                } else {
3469
                    notes.append(custom_formats[dts.dts_fmt_lock]);
×
3470
                }
3471
                notes.append("\n  ")
×
3472
                    .append(ts_cap.value())
×
3473
                    .append("\n")
×
3474
                    .append(2 + match_len, ' ')
×
3475
                    .append("^ matched up to here"_snippet_border);
×
3476
                auto um = lnav::console::user_message::warning(
×
3477
                              attr_line_t("timestamp was not fully matched: ")
×
3478
                                  .append_quoted(ts_cap.value()))
×
3479
                              .with_snippet(sample.s_line.to_snippet())
×
3480
                              .with_note(notes)
×
3481
                              .move();
×
3482

3483
                msgs.emplace_back(um);
×
3484
            }
3485
        } else if (!ts_cap) {
3✔
3486
            msgs.emplace_back(
2✔
3487
                lnav::console::user_message::error(
×
3488
                    attr_line_t("invalid sample log message: ")
4✔
3489
                        .append(lnav::to_json(sample.s_line.pp_value)))
4✔
3490
                    .with_reason(attr_line_t("timestamp was not captured"))
4✔
3491
                    .with_snippet(sample.s_line.to_snippet())
4✔
3492
                    .with_help(attr_line_t(
4✔
3493
                        "A timestamp needs to be captured in order for a "
3494
                        "line to be recognized as a log message")));
3495
        } else {
3496
            attr_line_t notes;
1✔
3497

3498
            if (custom_formats == nullptr) {
1✔
3499
                notes.append("the following built-in formats were tried:");
×
3500
                for (int lpc = 0; PTIMEC_FORMATS[lpc].pf_fmt != nullptr; lpc++)
×
3501
                {
3502
                    off_t off = 0;
×
3503

3504
                    PTIMEC_FORMATS[lpc].pf_func(
×
3505
                        &tm, ts_cap->data(), off, ts_cap->length());
×
3506
                    notes.append("\n  ")
×
3507
                        .append(ts_cap.value())
×
3508
                        .append("\n")
×
3509
                        .append(2 + off, ' ')
×
3510
                        .append("^ "_snippet_border)
×
3511
                        .append_quoted(
×
3512
                            lnav::roles::symbol(PTIMEC_FORMATS[lpc].pf_fmt))
×
3513
                        .append(" matched up to here"_snippet_border);
×
3514
                }
3515
            } else {
3516
                notes.append("the following custom formats were tried:");
1✔
3517
                for (int lpc = 0; custom_formats[lpc] != nullptr; lpc++) {
2✔
3518
                    off_t off = 0;
1✔
3519

3520
                    ptime_fmt(custom_formats[lpc],
1✔
3521
                              &tm,
3522
                              ts_cap->data(),
3523
                              off,
3524
                              ts_cap->length());
1✔
3525
                    notes.append("\n  ")
1✔
3526
                        .append(ts_cap.value())
1✔
3527
                        .append("\n")
1✔
3528
                        .append(2 + off, ' ')
1✔
3529
                        .append("^ "_snippet_border)
1✔
3530
                        .append_quoted(lnav::roles::symbol(custom_formats[lpc]))
2✔
3531
                        .append(" matched up to here"_snippet_border);
1✔
3532
                }
3533
            }
3534

3535
            msgs.emplace_back(
1✔
3536
                lnav::console::user_message::error(
×
3537
                    attr_line_t("invalid sample log message: ")
1✔
3538
                        .append(lnav::to_json(sample.s_line.pp_value)))
2✔
3539
                    .with_reason(attr_line_t("unrecognized timestamp -- ")
2✔
3540
                                     .append(ts_cap.value()))
1✔
3541
                    .with_snippet(sample.s_line.to_snippet())
2✔
3542
                    .with_note(notes)
1✔
3543
                    .with_help(attr_line_t("If the timestamp format is not "
2✔
3544
                                           "supported by default, you can "
3545
                                           "add a custom format with the ")
3546
                                   .append_quoted("timestamp-format"_symbol)
1✔
3547
                                   .append(" property")));
1✔
3548
        }
1✔
3549

3550
        auto level = this->convert_level(
182,299✔
3551
            level_cap.value_or(string_fragment::invalid()), nullptr);
182,299✔
3552

3553
        if (sample.s_level != LEVEL_UNKNOWN && sample.s_level != level) {
182,299✔
3554
            attr_line_t note_al;
1✔
3555

3556
            note_al.append("matched regex = ")
1✔
3557
                .append(lnav::roles::symbol(pat.p_name.to_string()))
2✔
3558
                .append("\n")
1✔
3559
                .append("captured level = ")
1✔
3560
                .append_quoted(level_cap->to_string());
1✔
3561
            if (level_cap && !this->elf_level_patterns.empty()) {
1✔
3562
                thread_local auto md = lnav::pcre2pp::match_data::unitialized();
1✔
3563

3564
                note_al.append("\nlevel regular expression match results:");
1✔
3565
                for (const auto& level_pattern : this->elf_level_patterns) {
3✔
3566
                    attr_line_t regex_al
3567
                        = level_pattern.second.lp_pcre.pp_value->get_pattern();
2✔
3568
                    lnav::snippets::regex_highlighter(
2✔
3569
                        regex_al, -1, line_range{0, (int) regex_al.length()});
2✔
3570
                    note_al.append("\n  ")
2✔
3571
                        .append(lnav::roles::symbol(
4✔
3572
                            level_pattern.second.lp_pcre.pp_path.to_string()))
4✔
3573
                        .append(" = ")
2✔
3574
                        .append(regex_al)
2✔
3575
                        .append("\n    ");
2✔
3576
                    auto match_res = level_pattern.second.lp_pcre.pp_value
2✔
3577
                                         ->capture_from(level_cap.value())
2✔
3578
                                         .into(md)
2✔
3579
                                         .matches(PCRE2_NO_UTF_CHECK)
4✔
3580
                                         .ignore_error();
2✔
3581
                    if (!match_res) {
2✔
3582
                        note_al.append(lnav::roles::warning("no match"));
1✔
3583
                        continue;
1✔
3584
                    }
3585

3586
                    note_al.append(level_cap.value())
1✔
3587
                        .append("\n    ")
1✔
3588
                        .append(md.leading().length(), ' ')
1✔
3589
                        .append("^"_snippet_border);
1✔
3590
                    if (match_res->f_all.length() > 2) {
1✔
3591
                        note_al.append(lnav::roles::snippet_border(
1✔
3592
                            std::string(match_res->f_all.length() - 2, '-')));
3✔
3593
                    }
3594
                    if (match_res->f_all.length() > 1) {
1✔
3595
                        note_al.append("^"_snippet_border);
1✔
3596
                    }
3597
                }
2✔
3598
            }
3599
            auto um
3600
                = lnav::console::user_message::error(
×
3601
                      attr_line_t("invalid sample log message: ")
1✔
3602
                          .append(lnav::to_json(sample.s_line.pp_value)))
2✔
3603
                      .with_reason(attr_line_t()
2✔
3604
                                       .append_quoted(lnav::roles::symbol(
2✔
3605
                                           level_names[level]))
1✔
3606
                                       .append(" does not match the expected "
1✔
3607
                                               "level of ")
3608
                                       .append_quoted(lnav::roles::symbol(
2✔
3609
                                           level_names[sample.s_level])))
1✔
3610
                      .with_snippet(sample.s_line.to_snippet())
2✔
3611
                      .with_note(note_al)
1✔
3612
                      .move();
1✔
3613
            if (!this->elf_level_patterns.empty()) {
1✔
3614
                um.with_help(
1✔
3615
                    attr_line_t("Level regexes are not anchored to the "
2✔
3616
                                "start/end of the string.  Prepend ")
3617
                        .append_quoted("^"_symbol)
1✔
3618
                        .append(" to the expression to match from the "
1✔
3619
                                "start of the string and append ")
3620
                        .append_quoted("$"_symbol)
1✔
3621
                        .append(" to match up to the end of the string."));
1✔
3622
            }
3623
            msgs.emplace_back(um);
1✔
3624
        }
1✔
3625

3626
        {
3627
            auto full_match_res
3628
                = pat.p_pcre.pp_value->capture_from(sample.s_line.pp_value)
182,299✔
3629
                      .into(md)
182,299✔
3630
                      .matches()
364,598✔
3631
                      .ignore_error();
182,299✔
3632
            if (!full_match_res) {
182,299✔
3633
                attr_line_t regex_al = pat.p_pcre.pp_value->get_pattern();
1✔
3634
                lnav::snippets::regex_highlighter(
1✔
3635
                    regex_al, -1, line_range{0, (int) regex_al.length()});
1✔
3636
                msgs.emplace_back(
1✔
3637
                    lnav::console::user_message::error(
×
3638
                        attr_line_t("invalid pattern: ")
1✔
3639
                            .append_quoted(
1✔
3640
                                lnav::roles::symbol(pat.p_name.to_string())))
2✔
3641
                        .with_reason("pattern does not match entire "
2✔
3642
                                     "multiline sample message")
3643
                        .with_snippet(sample.s_line.to_snippet())
2✔
3644
                        .with_note(attr_line_t()
2✔
3645
                                       .append(lnav::roles::symbol(
1✔
3646
                                           pat.p_name.to_string()))
2✔
3647
                                       .append(" = ")
1✔
3648
                                       .append(regex_al))
1✔
3649
                        .with_help(
3650
                            attr_line_t("use ").append_quoted(".*").append(
2✔
3651
                                " to match new-lines")));
3652
            } else if (static_cast<size_t>(full_match_res->f_all.length())
182,299✔
3653
                       != sample.s_line.pp_value.length())
182,298✔
3654
            {
3655
                attr_line_t regex_al = pat.p_pcre.pp_value->get_pattern();
1✔
3656
                lnav::snippets::regex_highlighter(
1✔
3657
                    regex_al, -1, line_range{0, (int) regex_al.length()});
1✔
3658
                auto match_length
3659
                    = static_cast<size_t>(full_match_res->f_all.length());
1✔
3660
                attr_line_t sample_al = sample.s_line.pp_value;
1✔
3661
                sample_al.append("\n")
1✔
3662
                    .append(match_length, ' ')
1✔
3663
                    .append("^ matched up to here"_error)
1✔
3664
                    .with_attr_for_all(VC_ROLE.value(role_t::VCR_QUOTED_CODE));
1✔
3665
                auto sample_snippet = lnav::console::snippet::from(
3666
                    sample.s_line.pp_location, sample_al);
1✔
3667
                msgs.emplace_back(
1✔
3668
                    lnav::console::user_message::error(
×
3669
                        attr_line_t("invalid pattern: ")
1✔
3670
                            .append_quoted(
1✔
3671
                                lnav::roles::symbol(pat.p_name.to_string())))
2✔
3672
                        .with_reason("pattern does not match entire "
2✔
3673
                                     "message")
3674
                        .with_snippet(sample_snippet)
1✔
3675
                        .with_note(attr_line_t()
3✔
3676
                                       .append(lnav::roles::symbol(
2✔
3677
                                           pat.p_name.to_string()))
2✔
3678
                                       .append(" = ")
1✔
3679
                                       .append(regex_al))
1✔
3680
                        .with_help("update the regular expression to fully "
3681
                                   "capture the sample message"));
3682
            }
1✔
3683
        }
3684
    }
1,189,467✔
3685

3686
    if (!found && !this->elf_pattern_order.empty()) {
182,301✔
3687
        std::vector<std::pair<ssize_t, intern_string_t>> partial_indexes;
2✔
3688
        attr_line_t notes;
2✔
3689
        size_t max_name_width = 0;
2✔
3690

3691
        for (const auto& pat_iter : this->elf_pattern_order) {
10✔
3692
            auto& pat = *pat_iter;
8✔
3693

3694
            if (!pat.p_pcre.pp_value) {
8✔
3695
                continue;
×
3696
            }
3697

3698
            partial_indexes.emplace_back(
8✔
3699
                pat.p_pcre.pp_value->match_partial(lines[0]), pat.p_name);
8✔
3700
            max_name_width = std::max(max_name_width, pat.p_name.size());
8✔
3701
        }
3702
        for (const auto& line_frag : lines) {
4✔
3703
            auto src_line = attr_line_t(line_frag.to_string());
2✔
3704
            if (!line_frag.endswith("\n")) {
2✔
3705
                src_line.append("\n");
2✔
3706
            }
3707
            src_line.with_attr_for_all(VC_ROLE.value(role_t::VCR_QUOTED_CODE));
2✔
3708
            notes.append("   ").append(src_line);
2✔
3709
            for (auto& part_pair : partial_indexes) {
10✔
3710
                if (part_pair.first >= 0
16✔
3711
                    && part_pair.first < line_frag.length())
8✔
3712
                {
3713
                    notes.append("   ")
8✔
3714
                        .append(part_pair.first, ' ')
8✔
3715
                        .append("^ "_snippet_border)
8✔
3716
                        .append(
8✔
3717
                            lnav::roles::symbol(part_pair.second.to_string()))
16✔
3718
                        .append(" matched up to here"_snippet_border)
8✔
3719
                        .append("\n");
8✔
3720
                }
3721
                part_pair.first -= line_frag.length();
8✔
3722
            }
3723
        }
2✔
3724
        notes.add_header(
2✔
3725
            "the following shows how each pattern matched this sample:\n");
3726

3727
        attr_line_t regex_note;
2✔
3728
        for (const auto& pat_iter : this->elf_pattern_order) {
10✔
3729
            if (!pat_iter->p_pcre.pp_value) {
8✔
3730
                regex_note
3731
                    .append(lnav::roles::symbol(fmt::format(
×
3732
                        FMT_STRING("{:{}}"), pat_iter->p_name, max_name_width)))
×
3733
                    .append(" is invalid");
×
3734
                continue;
×
3735
            }
3736

3737
            attr_line_t regex_al = pat_iter->p_pcre.pp_value->get_pattern();
8✔
3738
            lnav::snippets::regex_highlighter(
8✔
3739
                regex_al, -1, line_range{0, (int) regex_al.length()});
8✔
3740

3741
            regex_note
3742
                .append(lnav::roles::symbol(fmt::format(
16✔
3743
                    FMT_STRING("{:{}}"), pat_iter->p_name, max_name_width)))
24✔
3744
                .append(" = ")
8✔
3745
                .append_quoted(regex_al)
16✔
3746
                .append("\n");
8✔
3747
        }
8✔
3748

3749
        msgs.emplace_back(
2✔
3750
            lnav::console::user_message::error(
×
3751
                attr_line_t("invalid sample log message: ")
2✔
3752
                    .append(lnav::to_json(sample.s_line.pp_value)))
4✔
3753
                .with_reason("sample does not match any patterns")
4✔
3754
                .with_snippet(sample.s_line.to_snippet())
4✔
3755
                .with_note(notes.rtrim())
4✔
3756
                .with_note(regex_note));
3757
    }
2✔
3758

3759
    return retval;
182,301✔
3760
}
184,544✔
3761

3762
void
3763
external_log_format::build(std::vector<lnav::console::user_message>& errors)
51,862✔
3764
{
3765
    auto& vc = view_colors::singleton();
51,862✔
3766

3767
    if (!this->lf_timestamp_field.empty()) {
51,862✔
3768
        auto& vd = this->elf_value_defs[this->lf_timestamp_field];
51,862✔
3769
        if (vd.get() == nullptr) {
51,862✔
3770
            vd = std::make_shared<value_def>(
37,573✔
3771
                this->lf_timestamp_field,
37,573✔
3772
                value_kind_t::VALUE_TEXT,
×
3773
                logline_value_meta::internal_column{},
×
3774
                this);
37,573✔
3775
            if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
37,573✔
3776
                this->elf_value_def_order.emplace_back(vd);
5,711✔
3777
            }
3778
        }
3779
        vd->vd_meta.lvm_name = this->lf_timestamp_field;
51,862✔
3780
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
51,862✔
3781
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
51,862✔
3782
        vd->vd_internal = true;
51,862✔
3783

3784
        this->elf_value_defs[LOG_TIME_STR] = vd;
51,862✔
3785
    }
3786

3787
    if (!this->lf_subsecond_field.empty()) {
51,862✔
3788
        if (!this->lf_subsecond_unit.has_value()) {
97✔
3789
            errors.emplace_back(
1✔
3790
                lnav::console::user_message::error(
×
3791
                    attr_line_t()
2✔
3792
                        .append_quoted(
1✔
3793
                            lnav::roles::symbol(this->elf_name.to_string()))
2✔
3794
                        .append(" is not a valid log format"))
1✔
3795
                    .with_reason(attr_line_t()
2✔
3796
                                     .append_quoted("subsecond-units"_symbol)
1✔
3797
                                     .append(" must be set when ")
1✔
3798
                                     .append_quoted("subsecond-field"_symbol)
1✔
3799
                                     .append(" is used"))
1✔
3800
                    .with_snippets(this->get_snippets()));
2✔
3801
        } else {
3802
            auto& vd = this->elf_value_defs[this->lf_subsecond_field];
96✔
3803
            if (vd.get() == nullptr) {
96✔
3804
                vd = std::make_shared<value_def>(
96✔
3805
                    this->lf_subsecond_field,
96✔
3806
                    value_kind_t::VALUE_INTEGER,
×
3807
                    logline_value_meta::internal_column{},
×
3808
                    this);
96✔
3809
                if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
96✔
3810
                    this->elf_value_def_order.emplace_back(vd);
96✔
3811
                }
3812
            }
3813
            vd->vd_meta.lvm_name = this->lf_subsecond_field;
96✔
3814
            vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
96✔
3815
            vd->vd_meta.lvm_hidden = true;
96✔
3816
            vd->vd_internal = true;
96✔
3817
        }
3818
    }
3819

3820
    if (startswith(this->elf_level_field.get(), "/")) {
51,862✔
3821
        this->elf_level_field
3822
            = intern_string::lookup(this->elf_level_field.get() + 1);
192✔
3823
    }
3824
    if (!this->elf_level_field.empty()) {
51,862✔
3825
        auto level_iter = this->elf_value_defs.find(this->elf_level_field);
51,862✔
3826
        if (level_iter == this->elf_value_defs.end()) {
51,862✔
3827
            auto& vd = this->elf_value_defs[this->elf_level_field];
25,524✔
3828
            vd = std::make_shared<value_def>(
25,524✔
3829
                this->elf_level_field,
25,524✔
3830
                value_kind_t::VALUE_TEXT,
×
3831
                logline_value_meta::internal_column{},
×
3832
                this);
25,524✔
3833
            if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
25,524✔
3834
                this->elf_value_def_order.emplace_back(vd);
2,627✔
3835
            }
3836
            vd->vd_meta.lvm_name = this->elf_level_field;
25,524✔
3837
            vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
25,524✔
3838
            vd->vd_internal = true;
25,524✔
3839

3840
            if (this->elf_level_field != this->elf_body_field) {
25,524✔
3841
                this->elf_value_defs[LOG_LEVEL_STR] = vd;
24,681✔
3842
            }
3843
        } else {
3844
            if (level_iter->second->vd_meta.lvm_kind
26,338✔
3845
                != value_kind_t::VALUE_TEXT)
26,338✔
3846
            {
3847
                this->lf_level_hideable = false;
5,325✔
3848
            }
3849
            this->elf_value_defs[LOG_LEVEL_STR] = level_iter->second;
26,338✔
3850
        }
3851
    }
3852

3853
    auto opid_field_iter = this->elf_value_defs.find(LOG_OPID_STR);
51,862✔
3854
    if (opid_field_iter == this->elf_value_defs.end()) {
51,862✔
3855
        auto vd
3856
            = std::make_shared<value_def>(this->elf_opid_field,
51,862✔
3857
                                          value_kind_t::VALUE_TEXT,
×
3858
                                          logline_value_meta::internal_column{},
×
3859
                                          this);
51,862✔
3860
        if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
51,862✔
3861
            this->elf_value_def_order.emplace_back(vd);
9,542✔
3862
        }
3863
        vd->vd_meta.lvm_name = LOG_OPID_STR;
51,862✔
3864
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
51,862✔
3865
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
51,862✔
3866
        vd->vd_internal = true;
51,862✔
3867

3868
        this->elf_value_defs[LOG_OPID_STR] = vd;
51,862✔
3869
    }
51,862✔
3870

3871
    if (!this->elf_body_field.empty()) {
51,862✔
3872
        auto& vd = this->elf_value_defs[this->elf_body_field];
51,862✔
3873
        if (vd.get() == nullptr) {
51,862✔
3874
            vd = std::make_shared<value_def>(
42,705✔
3875
                this->elf_body_field,
42,705✔
3876
                value_kind_t::VALUE_TEXT,
×
3877
                logline_value_meta::internal_column{},
×
3878
                this);
42,705✔
3879
            if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
42,705✔
3880
                this->elf_value_def_order.emplace_back(vd);
6,457✔
3881
            }
3882
        }
3883
        vd->vd_meta.lvm_name = this->elf_body_field;
51,862✔
3884
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
51,862✔
3885
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
51,862✔
3886
        vd->vd_internal = true;
51,862✔
3887
    }
3888

3889
    if (!this->elf_src_file_field.empty()) {
51,862✔
3890
        auto& vd = this->elf_value_defs[this->elf_src_file_field];
7,471✔
3891
        if (vd.get() == nullptr) {
7,471✔
3892
            vd = std::make_shared<value_def>(
1✔
3893
                this->elf_src_file_field,
1✔
3894
                value_kind_t::VALUE_TEXT,
×
3895
                logline_value_meta::internal_column{},
×
3896
                this);
2✔
3897
        }
3898
        vd->vd_meta.lvm_name = this->elf_src_file_field;
7,471✔
3899
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
7,471✔
3900
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
7,471✔
3901
    }
3902

3903
    if (!this->elf_src_line_field.empty()) {
51,862✔
3904
        auto& vd = this->elf_value_defs[this->elf_src_line_field];
7,471✔
3905
        if (vd.get() == nullptr) {
7,471✔
3906
            vd = std::make_shared<value_def>(
1✔
3907
                this->elf_src_line_field,
1✔
3908
                value_kind_t::VALUE_INTEGER,
×
3909
                logline_value_meta::internal_column{},
×
3910
                this);
2✔
3911
        }
3912
        vd->vd_meta.lvm_name = this->elf_src_line_field;
7,471✔
3913
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_INTEGER;
7,471✔
3914
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
7,471✔
3915
    }
3916

3917
    if (!this->elf_thread_id_field.empty()) {
51,862✔
3918
        auto& vd = this->elf_value_defs[this->elf_thread_id_field];
17,182✔
3919
        if (vd.get() == nullptr) {
17,182✔
3920
            vd = std::make_shared<value_def>(
1✔
3921
                this->elf_thread_id_field,
1✔
3922
                value_kind_t::VALUE_TEXT,
×
3923
                logline_value_meta::internal_column{},
×
3924
                this);
2✔
3925
        }
3926
        vd->vd_meta.lvm_name = this->elf_thread_id_field;
17,182✔
3927
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
17,182✔
3928
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
17,182✔
3929
    }
3930

3931
    if (!this->elf_duration_field.empty()) {
51,862✔
3932
        auto& vd = this->elf_value_defs[this->elf_duration_field];
2,241✔
3933
        if (vd.get() == nullptr) {
2,241✔
3934
            vd = std::make_shared<value_def>(
×
3935
                this->elf_duration_field,
×
3936
                value_kind_t::VALUE_FLOAT,
×
3937
                logline_value_meta::internal_column{},
×
3938
                this);
×
3939
        }
3940
        vd->vd_meta.lvm_name = this->elf_duration_field;
2,241✔
3941
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_FLOAT;
2,241✔
3942
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
2,241✔
3943
    }
3944

3945
    for (auto& od_pair : *this->lf_opid_description_def) {
74,274✔
3946
        od_pair.second.od_index = this->lf_opid_description_def_vec->size();
22,412✔
3947
        this->lf_opid_description_def_vec->emplace_back(&od_pair.second);
22,412✔
3948
    }
3949

3950
    for (auto& od_pair : *this->lf_subid_description_def) {
52,609✔
3951
        od_pair.second.od_index = this->lf_subid_description_def_vec->size();
747✔
3952
        this->lf_subid_description_def_vec->emplace_back(&od_pair.second);
747✔
3953
    }
3954

3955
    if (!this->lf_timestamp_format.empty()) {
51,862✔
3956
        this->lf_timestamp_format.push_back(nullptr);
5,329✔
3957
    }
3958
    auto src_file_found = 0;
51,862✔
3959
    auto src_line_found = 0;
51,862✔
3960
    auto thread_id_found = 0;
51,862✔
3961
    auto duration_found = 0;
51,862✔
3962
    for (auto& elf_pattern : this->elf_patterns) {
148,813✔
3963
        auto& pat = *elf_pattern.second;
96,951✔
3964

3965
        if (pat.p_pcre.pp_value == nullptr) {
96,951✔
3966
            continue;
1✔
3967
        }
3968

3969
        if (pat.p_opid_field_index == -1
193,900✔
3970
            && this->lf_opid_source.value_or(opid_source_t::from_description)
96,950✔
3971
                == opid_source_t::from_description
3972
            && this->lf_opid_description_def->size() == 1)
193,900✔
3973
        {
3974
            const auto& opid_def
3975
                = this->lf_opid_description_def->begin()->second;
24,651✔
3976
            for (const auto& desc : *opid_def.od_descriptors) {
55,278✔
3977
                for (auto named_cap : pat.p_pcre.pp_value->get_named_captures())
357,066✔
3978
                {
3979
                    const intern_string_t name
3980
                        = intern_string::lookup(named_cap.get_name());
326,439✔
3981

3982
                    if (name == desc.od_field.pp_value) {
326,439✔
3983
                        pat.p_opid_description_field_indexes.emplace_back(
56,772✔
3984
                            named_cap.get_index());
28,386✔
3985
                    }
3986
                }
3987
            }
3988
        }
3989

3990
        for (auto named_cap : pat.p_pcre.pp_value->get_named_captures()) {
837,676✔
3991
            const intern_string_t name
3992
                = intern_string::lookup(named_cap.get_name());
740,726✔
3993

3994
            if (name == this->lf_timestamp_field) {
740,726✔
3995
                pat.p_timestamp_field_index = named_cap.get_index();
96,948✔
3996
            }
3997
            if (name == this->lf_time_field) {
740,726✔
3998
                pat.p_time_field_index = named_cap.get_index();
747✔
3999
            }
4000
            if (name == this->elf_level_field) {
740,726✔
4001
                pat.p_level_field_index = named_cap.get_index();
73,592✔
4002
            }
4003
            if (name == this->elf_opid_field) {
740,726✔
4004
                pat.p_opid_field_index = named_cap.get_index();
20,169✔
4005
            }
4006
            if (name == this->elf_subid_field) {
740,726✔
4007
                pat.p_subid_field_index = named_cap.get_index();
11,205✔
4008
            }
4009
            if (name == this->elf_body_field) {
740,726✔
4010
                pat.p_body_field_index = named_cap.get_index();
83,502✔
4011
            }
4012
            if (name == this->elf_src_file_field) {
740,726✔
4013
                pat.p_src_file_field_index = named_cap.get_index();
11,952✔
4014
                src_file_found += 1;
11,952✔
4015
            }
4016
            if (name == this->elf_src_line_field) {
740,726✔
4017
                pat.p_src_line_field_index = named_cap.get_index();
13,446✔
4018
                src_line_found += 1;
13,446✔
4019
            }
4020
            if (name == this->elf_thread_id_field) {
740,726✔
4021
                pat.p_thread_id_field_index = named_cap.get_index();
41,832✔
4022
                thread_id_found += 1;
41,832✔
4023
            }
4024
            if (name == this->elf_duration_field) {
740,726✔
4025
                pat.p_duration_field_index = named_cap.get_index();
4,482✔
4026
                duration_found += 1;
4,482✔
4027
            }
4028

4029
            auto value_iter = this->elf_value_defs.find(name);
740,726✔
4030
            if (value_iter != this->elf_value_defs.end()) {
740,726✔
4031
                auto vd = value_iter->second;
729,423✔
4032
                indexed_value_def ivd;
729,423✔
4033

4034
                ivd.ivd_index = named_cap.get_index();
729,423✔
4035
                if (!vd->vd_unit_field.empty()) {
729,423✔
4036
                    ivd.ivd_unit_field_index = pat.p_pcre.pp_value->name_index(
1,494✔
4037
                        vd->vd_unit_field.get());
747✔
4038
                } else {
4039
                    ivd.ivd_unit_field_index = -1;
728,676✔
4040
                }
4041
                if (!vd->vd_internal
729,423✔
4042
                    && !vd->vd_meta.lvm_column
1,254,203✔
4043
                            .is<logline_value_meta::table_column>())
524,780✔
4044
                {
4045
                    vd->vd_meta.lvm_column = logline_value_meta::table_column{
293,957✔
4046
                        this->elf_column_count++};
293,957✔
4047
                }
4048
                ivd.ivd_value_def = vd;
729,423✔
4049
                pat.p_value_by_index.push_back(ivd);
729,423✔
4050
            }
729,423✔
4051
            pat.p_value_name_to_index[name] = named_cap.get_index();
740,726✔
4052
        }
4053

4054
        stable_sort(pat.p_value_by_index.begin(), pat.p_value_by_index.end());
96,950✔
4055

4056
        for (int lpc = 0; lpc < (int) pat.p_value_by_index.size(); lpc++) {
826,373✔
4057
            auto& ivd = pat.p_value_by_index[lpc];
729,423✔
4058
            auto vd = ivd.ivd_value_def;
729,423✔
4059

4060
            if (!vd->vd_meta.lvm_foreign_key && !vd->vd_meta.lvm_identifier) {
729,423✔
4061
                switch (vd->vd_meta.lvm_kind) {
369,923✔
4062
                    case value_kind_t::VALUE_INTEGER:
51,639✔
4063
                    case value_kind_t::VALUE_FLOAT:
4064
                        pat.p_numeric_value_indexes.push_back(lpc);
51,639✔
4065
                        break;
51,639✔
4066
                    default:
318,284✔
4067
                        break;
318,284✔
4068
                }
4069
            }
4070
        }
729,423✔
4071

4072
        if (pat.p_timestamp_field_index == -1) {
96,950✔
4073
            errors.emplace_back(
2✔
4074
                lnav::console::user_message::error(
×
4075
                    attr_line_t("invalid pattern: ")
4✔
4076
                        .append_quoted(lnav::roles::symbol(pat.p_config_path)))
4✔
4077
                    .with_reason("no timestamp capture found in the pattern")
4✔
4078
                    .with_snippets(this->get_snippets())
4✔
4079
                    .with_help("all log messages need a timestamp"));
4080
        }
4081

4082
        if (!this->elf_level_field.empty() && pat.p_level_field_index == -1) {
96,950✔
4083
            log_warning("%s:level field '%s' not found in pattern",
23,358✔
4084
                        pat.p_config_path.c_str(),
4085
                        this->elf_level_field.get());
4086
        }
4087
        if (!this->elf_body_field.empty() && pat.p_body_field_index == -1) {
96,950✔
4088
            log_warning("%s:body field '%s' not found in pattern",
13,448✔
4089
                        pat.p_config_path.c_str(),
4090
                        this->elf_body_field.get());
4091
        }
4092

4093
        this->elf_pattern_order.push_back(elf_pattern.second);
96,950✔
4094
    }
4095
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
103,724✔
4096
        && !this->elf_src_file_field.empty() && src_file_found == 0)
51,862✔
4097
    {
4098
        errors.emplace_back(
1✔
4099
            lnav::console::user_message::error(
×
4100
                attr_line_t("invalid pattern: ")
2✔
4101
                    .append_quoted(
1✔
4102
                        lnav::roles::symbol(this->elf_name.to_string())))
2✔
4103
                .with_reason("no source file capture found in the pattern")
2✔
4104
                .with_snippets(this->get_snippets())
2✔
4105
                .with_help(attr_line_t("at least one pattern needs a source "
2✔
4106
                                       "file capture named ")
4107
                               .append_quoted(this->elf_src_file_field.get())));
1✔
4108
    }
4109
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
103,724✔
4110
        && !this->elf_src_line_field.empty() && src_line_found == 0)
51,862✔
4111
    {
4112
        errors.emplace_back(
1✔
4113
            lnav::console::user_message::error(
×
4114
                attr_line_t("invalid pattern: ")
2✔
4115
                    .append_quoted(
1✔
4116
                        lnav::roles::symbol(this->elf_name.to_string())))
2✔
4117
                .with_reason("no source line capture found in the pattern")
2✔
4118
                .with_snippets(this->get_snippets())
2✔
4119
                .with_help(attr_line_t("at least one pattern needs a source "
2✔
4120
                                       "line capture named ")
4121
                               .append_quoted(this->elf_src_line_field.get())));
1✔
4122
    }
4123
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
103,724✔
4124
        && !this->elf_thread_id_field.empty() && thread_id_found == 0)
51,862✔
4125
    {
4126
        errors.emplace_back(
1✔
4127
            lnav::console::user_message::error(
×
4128
                attr_line_t("invalid pattern: ")
2✔
4129
                    .append_quoted(
1✔
4130
                        lnav::roles::symbol(this->elf_name.to_string())))
2✔
4131
                .with_reason("no thread ID capture found in the pattern")
2✔
4132
                .with_snippets(this->get_snippets())
2✔
4133
                .with_help(
4134
                    attr_line_t(
2✔
4135
                        "at least one pattern needs a thread ID capture named ")
4136
                        .append_quoted(this->elf_thread_id_field.get())));
1✔
4137
    }
4138
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
103,724✔
4139
        && !this->elf_duration_field.empty() && duration_found == 0)
51,862✔
4140
    {
4141
        errors.emplace_back(
×
4142
            lnav::console::user_message::error(
×
4143
                attr_line_t("invalid pattern: ")
×
4144
                    .append_quoted(
×
4145
                        lnav::roles::symbol(this->elf_name.to_string())))
×
4146
                .with_reason("no duration capture found in the pattern")
×
4147
                .with_snippets(this->get_snippets())
×
4148
                .with_help(
4149
                    attr_line_t(
×
4150
                        "at least one pattern needs a duration capture named ")
4151
                        .append_quoted(this->elf_duration_field.get())));
×
4152
    }
4153

4154
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
51,862✔
4155
        if (!this->elf_patterns.empty()) {
9,542✔
4156
            errors.emplace_back(
1✔
4157
                lnav::console::user_message::error(
×
4158
                    attr_line_t()
2✔
4159
                        .append_quoted(
1✔
4160
                            lnav::roles::symbol(this->elf_name.to_string()))
2✔
4161
                        .append(" is not a valid log format"))
1✔
4162
                    .with_reason("structured logs cannot have regexes")
2✔
4163
                    .with_snippets(this->get_snippets()));
2✔
4164
        }
4165
        if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
9,542✔
4166
            this->lf_multiline = true;
9,542✔
4167
            this->lf_structured = true;
9,542✔
4168
            this->lf_formatted_lines = true;
9,542✔
4169
            this->jlf_parse_context
4170
                = std::make_shared<yajlpp_parse_context>(this->elf_name);
9,542✔
4171
            this->jlf_yajl_handle.reset(
9,542✔
4172
                yajl_alloc(&this->jlf_parse_context->ypc_callbacks,
9,542✔
4173
                           nullptr,
4174
                           this->jlf_parse_context.get()),
9,542✔
4175
                yajl_handle_deleter());
4176
            yajl_config(
9,542✔
4177
                this->jlf_yajl_handle.get(), yajl_dont_validate_strings, 1);
4178
        }
4179
    } else {
4180
        if (this->elf_patterns.empty()) {
42,320✔
4181
            errors.emplace_back(lnav::console::user_message::error(
2✔
4182
                                    attr_line_t()
4✔
4183
                                        .append_quoted(lnav::roles::symbol(
4✔
4184
                                            this->elf_name.to_string()))
4✔
4185
                                        .append(" is not a valid log format"))
2✔
4186
                                    .with_reason("no regexes specified")
4✔
4187
                                    .with_snippets(this->get_snippets()));
4✔
4188
        }
4189
    }
4190

4191
    stable_sort(this->elf_level_pairs.begin(), this->elf_level_pairs.end());
51,862✔
4192

4193
    {
4194
        safe::WriteAccess<safe_format_header_expressions> hexprs(
4195
            format_header_exprs);
51,862✔
4196

4197
        if (hexprs->e_db.in() == nullptr) {
51,862✔
4198
            if (sqlite3_open(":memory:", hexprs->e_db.out()) != SQLITE_OK) {
747✔
4199
                log_error("unable to open memory DB");
×
4200
                return;
×
4201
            }
4202
            register_sqlite_funcs(hexprs->e_db.in(), sqlite_registration_funcs);
747✔
4203
        }
4204

4205
        for (const auto& hpair : this->elf_converter.c_header.h_exprs.he_exprs)
54,851✔
4206
        {
4207
            auto stmt_str
4208
                = fmt::format(FMT_STRING("SELECT 1 WHERE {}"), hpair.second);
8,967✔
4209
            compiled_header_expr che;
2,989✔
4210

4211
            log_info("preparing file-format header expression: %s",
2,989✔
4212
                     stmt_str.c_str());
4213
            auto retcode = sqlite3_prepare_v2(hexprs->e_db.in(),
5,978✔
4214
                                              stmt_str.c_str(),
4215
                                              stmt_str.size(),
2,989✔
4216
                                              che.che_stmt.out(),
4217
                                              nullptr);
4218
            if (retcode != SQLITE_OK) {
2,989✔
4219
                auto sql_al = attr_line_t(hpair.second)
2✔
4220
                                  .with_attr_for_all(SA_PREFORMATTED.value())
2✔
4221
                                  .with_attr_for_all(
1✔
4222
                                      VC_ROLE.value(role_t::VCR_QUOTED_CODE))
2✔
4223
                                  .move();
1✔
4224
                readline_sql_highlighter(
1✔
4225
                    sql_al, lnav::sql::dialect::sqlite, std::nullopt);
4226
                intern_string_t watch_expr_path = intern_string::lookup(
4227
                    fmt::format(FMT_STRING("/{}/converter/header/expr/{}"),
3✔
4228
                                this->elf_name,
1✔
4229
                                hpair.first));
2✔
4230
                auto snippet = lnav::console::snippet::from(
4231
                    source_location(watch_expr_path), sql_al);
1✔
4232

4233
                auto um = lnav::console::user_message::error(
2✔
4234
                              "SQL expression is invalid")
4235
                              .with_reason(sqlite3_errmsg(hexprs->e_db.in()))
2✔
4236
                              .with_snippet(snippet)
1✔
4237
                              .move();
1✔
4238

4239
                errors.emplace_back(um);
1✔
4240
                continue;
1✔
4241
            }
1✔
4242

4243
            hexprs->e_header_exprs[this->elf_name][hpair.first]
2,988✔
4244
                = std::move(che);
5,976✔
4245
        }
2,990✔
4246

4247
        if (!this->elf_converter.c_header.h_exprs.he_exprs.empty()
51,862✔
4248
            && this->elf_converter.c_command.pp_value.empty())
51,862✔
4249
        {
4250
            auto um = lnav::console::user_message::error(
2✔
4251
                          "A command is required when a converter is defined")
4252
                          .with_help(
2✔
4253
                              "The converter command transforms the file "
4254
                              "into a format that can be consumed by lnav")
4255
                          .with_snippets(this->get_snippets())
2✔
4256
                          .move();
1✔
4257
            errors.emplace_back(um);
1✔
4258
        }
1✔
4259
    }
51,862✔
4260

4261
    for (auto& vd : this->elf_value_def_order) {
510,104✔
4262
        std::vector<std::string>::iterator act_iter;
458,242✔
4263

4264
        if (!vd->vd_internal
458,242✔
4265
            && log_vtab_impl::RESERVED_COLUMNS.count(
869,448✔
4266
                vd->vd_meta.lvm_name.to_string_fragment()))
869,448✔
4267
        {
4268
            auto um = lnav::console::user_message::error(
×
4269
                          attr_line_t("value name ")
1✔
4270
                              .append_quoted(lnav::roles::symbol(
2✔
4271
                                  fmt::format(FMT_STRING("/{}/value/{}"),
4✔
4272
                                              this->elf_name,
1✔
4273
                                              vd->vd_meta.lvm_name)))
1✔
4274
                              .append(" is reserved and cannot be used"))
1✔
4275
                          .with_reason(
2✔
4276
                              "lnav automatically defines several columns in "
4277
                              "the log virtual table")
4278
                          .with_snippets(this->get_snippets())
2✔
4279
                          .with_help("Choose another name")
2✔
4280
                          .move();
1✔
4281
            errors.emplace_back(um);
1✔
4282
        }
1✔
4283

4284
        vd->vd_meta.lvm_format = this;
458,242✔
4285
        if (!vd->vd_internal
458,242✔
4286
            && !vd->vd_meta.lvm_column.is<logline_value_meta::table_column>())
458,242✔
4287
        {
4288
            vd->vd_meta.lvm_column
117,249✔
4289
                = logline_value_meta::table_column{this->elf_column_count++};
117,249✔
4290
        }
4291

4292
        if (vd->vd_meta.lvm_kind == value_kind_t::VALUE_UNKNOWN) {
458,242✔
4293
            vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
×
4294
        }
4295

4296
        if (this->elf_type == elf_type_t::ELF_TYPE_TEXT) {
458,242✔
4297
            std::set<std::string> available_captures;
309,646✔
4298

4299
            bool found_in_pattern = false;
309,646✔
4300
            for (const auto& pat : this->elf_patterns) {
522,545✔
4301
                if (pat.second->p_pcre.pp_value == nullptr) {
522,543✔
4302
                    continue;
×
4303
                }
4304

4305
                auto cap_index = pat.second->p_pcre.pp_value->name_index(
1,045,086✔
4306
                    vd->vd_meta.lvm_name.get());
522,543✔
4307
                if (cap_index >= 0) {
522,543✔
4308
                    found_in_pattern = true;
309,644✔
4309
                    break;
309,644✔
4310
                }
4311

4312
                for (auto named_cap :
212,899✔
4313
                     pat.second->p_pcre.pp_value->get_named_captures())
1,942,965✔
4314
                {
4315
                    available_captures.insert(named_cap.get_name().to_string());
1,517,167✔
4316
                }
4317
            }
4318
            if (!found_in_pattern) {
309,646✔
4319
                auto notes
4320
                    = attr_line_t("the following captures are available:\n  ")
2✔
4321
                          .join(available_captures,
2✔
4322
                                VC_ROLE.value(role_t::VCR_SYMBOL),
4✔
4323
                                ", ")
4324
                          .move();
2✔
4325
                errors.emplace_back(
2✔
4326
                    lnav::console::user_message::warning(
×
4327
                        attr_line_t("invalid value ")
2✔
4328
                            .append_quoted(lnav::roles::symbol(
4✔
4329
                                fmt::format(FMT_STRING("/{}/value/{}"),
8✔
4330
                                            this->elf_name,
2✔
4331
                                            vd->vd_meta.lvm_name.get()))))
4✔
4332
                        .with_reason(
4✔
4333
                            attr_line_t("no patterns have a capture named ")
4✔
4334
                                .append_quoted(vd->vd_meta.lvm_name.get()))
2✔
4335
                        .with_note(notes)
2✔
4336
                        .with_snippets(this->get_snippets())
4✔
4337
                        .with_help("values are populated from captures in "
4338
                                   "patterns, so at least one pattern must "
4339
                                   "have a capture with this value name"));
4340
            }
2✔
4341
        }
309,646✔
4342

4343
        for (act_iter = vd->vd_action_list.begin();
458,242✔
4344
             act_iter != vd->vd_action_list.end();
458,989✔
4345
             ++act_iter)
747✔
4346
        {
4347
            if (this->lf_action_defs.find(*act_iter)
747✔
4348
                == this->lf_action_defs.end())
1,494✔
4349
            {
4350
#if 0
4351
                errors.push_back("error:" + this->elf_name.to_string() + ":"
4352
                                 + vd->vd_meta.lvm_name.get()
4353
                                 + ": cannot find action -- " + (*act_iter));
4354
#endif
4355
            }
4356
        }
4357

4358
        vd->set_rewrite_src_name();
458,242✔
4359
    }
4360

4361
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
51,862✔
4362
        for (const auto& vd : this->elf_value_def_order) {
158,138✔
4363
            this->elf_value_def_frag_map[vd->vd_meta.lvm_name
148,596✔
4364
                                             .to_string_fragment()]
148,596✔
4365
                = vd.get();
297,192✔
4366
        }
4367
    }
4368

4369
    for (const auto& td_pair : this->lf_tag_defs) {
54,202✔
4370
        const auto& td = td_pair.second;
2,340✔
4371

4372
        if (td->ftd_pattern.pp_value == nullptr
2,340✔
4373
            || td->ftd_pattern.pp_value->get_pattern().empty())
2,340✔
4374
        {
4375
            errors.emplace_back(
3✔
4376
                lnav::console::user_message::error(
×
4377
                    attr_line_t("invalid tag definition ")
6✔
4378
                        .append_quoted(lnav::roles::symbol(
6✔
4379
                            fmt::format(FMT_STRING("/{}/tags/{}"),
12✔
4380
                                        this->elf_name,
3✔
4381
                                        td_pair.first))))
3✔
4382
                    .with_reason(
6✔
4383
                        "tag definitions must have a non-empty pattern")
4384
                    .with_snippets(this->get_snippets()));
6✔
4385
        }
4386
    }
4387

4388
    if (this->elf_opid_field.empty()
51,862✔
4389
        && this->lf_opid_description_def->size() > 1)
51,862✔
4390
    {
4391
        errors.emplace_back(
1✔
4392
            lnav::console::user_message::error(
×
4393
                attr_line_t("too many opid descriptions")
2✔
4394
                    .append_quoted(lnav::roles::symbol(fmt::format(
2✔
4395
                        FMT_STRING("/{}/opid/description"), this->elf_name))))
4✔
4396
                .with_reason(attr_line_t("when no ")
2✔
4397
                                 .append("opid-field"_symbol)
1✔
4398
                                 .append(" is specified, only a single "
1✔
4399
                                         "description is supported"))
4400
                .with_snippets(this->get_snippets()));
2✔
4401
    }
4402

4403
    for (const auto& opid_desc_pair : *this->lf_opid_description_def) {
74,274✔
4404
        for (const auto& opid_desc : *opid_desc_pair.second.od_descriptors) {
53,041✔
4405
            auto iter = this->elf_value_defs.find(opid_desc.od_field.pp_value);
30,629✔
4406
            if (iter == this->elf_value_defs.end()) {
30,629✔
4407
                errors.emplace_back(
2✔
4408
                    lnav::console::user_message::error(
×
4409
                        attr_line_t("invalid opid description field ")
4✔
4410
                            .append_quoted(lnav::roles::symbol(
4✔
4411
                                opid_desc.od_field.pp_path.to_string())))
4✔
4412
                        .with_reason(
4✔
4413
                            attr_line_t("unknown value name ")
4✔
4414
                                .append_quoted(opid_desc.od_field.pp_value))
2✔
4415
                        .with_snippets(this->get_snippets()));
4✔
4416
            } else {
4417
                this->lf_desc_fields.insert(iter->first);
30,627✔
4418
                iter->second->vd_is_desc_field = true;
30,627✔
4419
            }
4420
        }
4421
    }
4422

4423
    for (const auto& subid_desc_pair : *this->lf_subid_description_def) {
52,609✔
4424
        for (const auto& subid_desc : *subid_desc_pair.second.od_descriptors) {
1,494✔
4425
            auto iter = this->elf_value_defs.find(subid_desc.od_field.pp_value);
747✔
4426
            if (iter == this->elf_value_defs.end()) {
747✔
4427
                errors.emplace_back(
×
4428
                    lnav::console::user_message::error(
×
4429
                        attr_line_t("invalid subid description field ")
×
4430
                            .append_quoted(lnav::roles::symbol(
×
4431
                                subid_desc.od_field.pp_path.to_string())))
×
4432
                        .with_reason(
×
4433
                            attr_line_t("unknown value name ")
×
4434
                                .append_quoted(subid_desc.od_field.pp_value))
×
4435
                        .with_snippets(this->get_snippets()));
×
4436
            } else {
4437
                this->lf_desc_fields.insert(iter->first);
747✔
4438
                iter->second->vd_is_desc_field = true;
747✔
4439
            }
4440
        }
4441
    }
4442

4443
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
103,724✔
4444
        && this->elf_samples.empty())
51,862✔
4445
    {
4446
        errors.emplace_back(
3✔
4447
            lnav::console::user_message::error(
×
4448
                attr_line_t()
6✔
4449
                    .append_quoted(
3✔
4450
                        lnav::roles::symbol(this->elf_name.to_string()))
6✔
4451
                    .append(" is not a valid log format"))
3✔
4452
                .with_reason("log message samples must be included in a format "
6✔
4453
                             "definition")
4454
                .with_snippets(this->get_snippets()));
6✔
4455
    }
4456

4457
    for (const auto& pat : this->elf_pattern_order) {
148,812✔
4458
        if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
96,950✔
4459
            continue;
1✔
4460
        }
4461
        if (pat->p_pcre.pp_value->name_index(this->lf_timestamp_field.get())
96,949✔
4462
            < 0)
96,949✔
4463
        {
4464
            attr_line_t notes;
1✔
4465
            bool first_note = true;
1✔
4466

4467
            if (pat->p_pcre.pp_value->get_capture_count() > 0) {
1✔
4468
                notes.append("the following captures are available:\n  ");
1✔
4469
            }
4470
            for (auto named_cap : pat->p_pcre.pp_value->get_named_captures()) {
4✔
4471
                if (!first_note) {
3✔
4472
                    notes.append(", ");
2✔
4473
                }
4474
                notes.append(
3✔
4475
                    lnav::roles::symbol(named_cap.get_name().to_string()));
6✔
4476
                first_note = false;
3✔
4477
            }
4478
            errors.emplace_back(
1✔
4479
                lnav::console::user_message::error(
×
4480
                    attr_line_t("invalid value for property ")
1✔
4481
                        .append_quoted(lnav::roles::symbol(
2✔
4482
                            fmt::format(FMT_STRING("/{}/timestamp-field"),
4✔
4483
                                        this->elf_name))))
1✔
4484
                    .with_reason(
2✔
4485
                        attr_line_t()
2✔
4486
                            .append_quoted(this->lf_timestamp_field)
1✔
4487
                            .append(" was not found in the pattern at ")
1✔
4488
                            .append(lnav::roles::symbol(pat->p_config_path)))
2✔
4489
                    .with_note(notes)
1✔
4490
                    .with_snippets(this->get_snippets()));
2✔
4491
        }
1✔
4492
    }
4493

4494
    for (size_t sample_index = 0; sample_index < this->elf_samples.size();
236,402✔
4495
         sample_index += 1)
184,540✔
4496
    {
4497
        auto& elf_sample = this->elf_samples[sample_index];
184,540✔
4498
        auto sample_lines
4499
            = string_fragment(elf_sample.s_line.pp_value).split_lines();
184,540✔
4500

4501
        if (this->test_line(elf_sample, errors).is<scan_match>()) {
184,540✔
4502
            for (const auto& pat_name : elf_sample.s_matched_regexes) {
366,837✔
4503
                this->elf_patterns[pat_name]->p_matched_samples.emplace(
182,298✔
4504
                    sample_index);
4505
            }
4506
        }
4507
    }
184,540✔
4508

4509
    if (!this->elf_samples.empty()) {
51,862✔
4510
        for (const auto& elf_sample : this->elf_samples) {
227,604✔
4511
            if (elf_sample.s_matched_regexes.size() <= 1) {
184,540✔
4512
                continue;
184,540✔
4513
            }
4514

4515
            errors.emplace_back(
×
4516
                lnav::console::user_message::warning(
×
4517
                    attr_line_t("invalid log format: ")
×
4518
                        .append_quoted(
×
4519
                            lnav::roles::symbol(this->elf_name.to_string())))
×
4520
                    .with_reason(
×
4521
                        attr_line_t(
×
4522
                            "sample is matched by more than one regex: ")
4523
                            .join(elf_sample.s_matched_regexes,
×
4524
                                  VC_ROLE.value(role_t::VCR_SYMBOL),
×
4525
                                  ", "))
4526
                    .with_snippet(lnav::console::snippet::from(
×
4527
                        elf_sample.s_line.pp_location,
4528
                        attr_line_t().append(lnav::roles::quoted_code(
×
4529
                            elf_sample.s_line.pp_value))))
×
4530
                    .with_help("log format regexes must match a single type "
4531
                               "of log message"));
4532
        }
4533

4534
        for (const auto& pat : this->elf_pattern_order) {
140,011✔
4535
            if (pat->p_matched_samples.empty()) {
96,947✔
4536
                errors.emplace_back(
2✔
4537
                    lnav::console::user_message::warning(
×
4538
                        attr_line_t("invalid pattern: ")
4✔
4539
                            .append_quoted(
2✔
4540
                                lnav::roles::symbol(pat->p_config_path)))
4✔
4541
                        .with_reason("pattern does not match any samples")
4✔
4542
                        .with_snippet(lnav::console::snippet::from(
6✔
4543
                            pat->p_pcre.pp_location, ""))
2✔
4544
                        .with_help(
4545
                            "every pattern should have at least one sample "
4546
                            "that it matches"));
4547
            }
4548
        }
4549
    }
4550

4551
    size_t value_def_index = 0;
51,862✔
4552
    for (auto& elf_value_def : this->elf_value_def_order) {
510,104✔
4553
        elf_value_def->vd_meta.lvm_values_index
458,242✔
4554
            = std::make_optional(value_def_index++);
458,242✔
4555

4556
        if (elf_value_def->vd_meta.lvm_foreign_key
458,242✔
4557
            || elf_value_def->vd_meta.lvm_identifier)
458,242✔
4558
        {
4559
            continue;
244,771✔
4560
        }
4561

4562
        switch (elf_value_def->vd_meta.lvm_kind) {
213,471✔
4563
            case value_kind_t::VALUE_INTEGER:
53,421✔
4564
            case value_kind_t::VALUE_FLOAT:
4565
                this->elf_numeric_value_defs.push_back(elf_value_def);
53,421✔
4566
                break;
53,421✔
4567
            default:
160,050✔
4568
                break;
160,050✔
4569
        }
4570
    }
4571

4572
    int format_index = 0;
51,862✔
4573
    for (auto iter = this->jlf_line_format.begin();
51,862✔
4574
         iter != this->jlf_line_format.end();
159,730✔
4575
         ++iter, format_index++)
107,868✔
4576
    {
4577
        static const intern_string_t ts
4578
            = intern_string::lookup("__timestamp__");
109,362✔
4579
        static const intern_string_t level_field
4580
            = intern_string::lookup("__level__");
109,362✔
4581
        auto& jfe = *iter;
107,868✔
4582

4583
        if (startswith(jfe.jfe_value.pp_value.get(), "/")) {
107,868✔
4584
            jfe.jfe_value.pp_value
4585
                = intern_string::lookup(jfe.jfe_value.pp_value.get() + 1);
192✔
4586
        }
4587
        if (!jfe.jfe_ts_format.empty()) {
107,868✔
4588
            if (!jfe.jfe_value.pp_value.empty() && jfe.jfe_value.pp_value != ts)
843✔
4589
            {
4590
                log_warning(
96✔
4591
                    "%s:line-format[%d]:ignoring field '%s' since "
4592
                    "timestamp-format was used",
4593
                    this->elf_name.get(),
4594
                    format_index,
4595
                    jfe.jfe_value.pp_value.get());
4596
            }
4597
            jfe.jfe_value.pp_value = ts;
843✔
4598
        }
4599

4600
        switch (jfe.jfe_type) {
107,868✔
4601
            case json_log_field::VARIABLE: {
71,778✔
4602
                auto vd_iter
4603
                    = this->elf_value_defs.find(jfe.jfe_value.pp_value);
71,778✔
4604
                if (jfe.jfe_value.pp_value == ts) {
71,778✔
4605
                    this->elf_value_defs[this->lf_timestamp_field]
7,759✔
4606
                        ->vd_meta.lvm_hidden
7,759✔
4607
                        = true;
7,759✔
4608
                } else if (jfe.jfe_value.pp_value == level_field) {
64,019✔
4609
                    this->elf_value_defs[this->elf_level_field]
2,988✔
4610
                        ->vd_meta.lvm_hidden
2,988✔
4611
                        = true;
2,988✔
4612
                } else if (vd_iter == this->elf_value_defs.end()) {
61,031✔
4613
                    errors.emplace_back(
2✔
4614
                        lnav::console::user_message::error(
×
4615
                            attr_line_t("invalid line format element ")
4✔
4616
                                .append_quoted(lnav::roles::symbol(fmt::format(
4✔
4617
                                    FMT_STRING("/{}/line-format/{}/field"),
6✔
4618
                                    this->elf_name,
2✔
4619
                                    format_index))))
4620
                            .with_reason(
4✔
4621
                                attr_line_t()
4✔
4622
                                    .append_quoted(jfe.jfe_value.pp_value)
2✔
4623
                                    .append(" is not a defined value"))
2✔
4624
                            .with_snippet(jfe.jfe_value.to_snippet()));
4✔
4625
                } else {
4626
                    vd_iter->second->vd_line_format_index = format_index;
61,029✔
4627
                    switch (vd_iter->second->vd_meta.lvm_kind) {
61,029✔
4628
                        case value_kind_t::VALUE_INTEGER:
10,650✔
4629
                        case value_kind_t::VALUE_FLOAT:
4630
                            if (jfe.jfe_align
10,650✔
4631
                                == json_format_element::align_t::NONE)
4632
                            {
4633
                                jfe.jfe_align
4634
                                    = json_format_element::align_t::RIGHT;
9,903✔
4635
                            }
4636
                            break;
10,650✔
4637
                        default:
50,379✔
4638
                            break;
50,379✔
4639
                    }
4640
                }
4641
                break;
71,778✔
4642
            }
4643
            case json_log_field::CONSTANT:
36,090✔
4644
                this->jlf_line_format_init_count
36,090✔
4645
                    += std::count(jfe.jfe_default_value.begin(),
36,090✔
4646
                                  jfe.jfe_default_value.end(),
4647
                                  '\n');
36,090✔
4648
                break;
36,090✔
4649
            default:
×
4650
                break;
×
4651
        }
4652
    }
4653

4654
    for (auto& hd_pair : this->elf_highlighter_patterns) {
52,248✔
4655
        auto& hd = hd_pair.second;
386✔
4656
        text_attrs attrs;
386✔
4657

4658
        if (!hd.hd_color.pp_value.empty()) {
386✔
4659
            attrs.ta_fg_color = vc.match_color(
385✔
4660
                styling::color_unit::from_str(hd.hd_color.pp_value)
770✔
4661
                    .unwrapOrElse([&](const auto& msg) {
1✔
4662
                        errors.emplace_back(
1✔
4663
                            lnav::console::user_message::error(
4664
                                attr_line_t()
1✔
4665
                                    .append_quoted(hd.hd_color.pp_value)
2✔
4666
                                    .append(" is not a valid color value for "
1✔
4667
                                            "property ")
4668
                                    .append_quoted(lnav::roles::symbol(
2✔
4669
                                        hd.hd_color.pp_path.to_string())))
1✔
4670
                                .with_reason(msg)
2✔
4671
                                .with_snippet(hd.hd_color.to_snippet()));
1✔
4672
                        return styling::color_unit::EMPTY;
1✔
4673
                    }));
4674
        }
4675

4676
        if (!hd.hd_background_color.pp_value.empty()) {
386✔
4677
            attrs.ta_bg_color = vc.match_color(
1✔
4678
                styling::color_unit::from_str(hd.hd_background_color.pp_value)
2✔
4679
                    .unwrapOrElse([&](const auto& msg) {
1✔
4680
                        errors.emplace_back(
1✔
4681
                            lnav::console::user_message::error(
4682
                                attr_line_t()
1✔
4683
                                    .append_quoted(
2✔
4684
                                        hd.hd_background_color.pp_value)
1✔
4685
                                    .append(" is not a valid color value for "
1✔
4686
                                            "property ")
4687
                                    .append_quoted(lnav::roles::symbol(
2✔
4688
                                        hd.hd_background_color.pp_path
1✔
4689
                                            .to_string())))
4690
                                .with_reason(msg)
2✔
4691
                                .with_snippet(
4692
                                    hd.hd_background_color.to_snippet()));
1✔
4693
                        return styling::color_unit::EMPTY;
1✔
4694
                    }));
4695
        }
4696

4697
        if (hd.hd_underline) {
386✔
4698
            attrs |= text_attrs::style::underline;
96✔
4699
        }
4700
        if (hd.hd_blink) {
386✔
4701
            attrs |= text_attrs::style::blink;
×
4702
        }
4703

4704
        if (hd.hd_pattern.pp_value != nullptr) {
386✔
4705
            this->lf_highlighters.emplace_back(hd.hd_pattern.pp_value);
384✔
4706
            this->lf_highlighters.back()
384✔
4707
                .with_name(hd_pair.first.to_string())
768✔
4708
                .with_format_name(this->elf_name)
384✔
4709
                .with_attrs(attrs)
384✔
4710
                .with_nestable(hd.hd_nestable);
384✔
4711
        }
4712
    }
4713
}
4714

4715
void
4716
external_log_format::register_vtabs(
43,604✔
4717
    log_vtab_manager* vtab_manager,
4718
    std::vector<lnav::console::user_message>& errors)
4719
{
4720
    for (auto& elf_search_table : this->elf_search_tables) {
52,467✔
4721
        if (elf_search_table.second.std_pattern.pp_value == nullptr) {
8,863✔
4722
            continue;
1✔
4723
        }
4724

4725
        auto lst = std::make_shared<log_search_table>(
4726
            elf_search_table.second.std_pattern.pp_value,
8,862✔
4727
            elf_search_table.first);
8,862✔
4728
        lst->lst_format = this;
8,862✔
4729
        lst->lst_log_path_glob = elf_search_table.second.std_glob;
8,862✔
4730
        if (elf_search_table.second.std_level != LEVEL_UNKNOWN) {
8,862✔
4731
            lst->lst_log_level = elf_search_table.second.std_level;
3,165✔
4732
        }
4733
        auto errmsg = vtab_manager->register_vtab(lst);
8,862✔
4734
        if (!errmsg.empty()) {
8,862✔
4735
#if 0
4736
            errors.push_back("error:" + this->elf_name.to_string() + ":"
4737
                             + search_iter->first.to_string()
4738
                             + ":unable to register table -- " + errmsg);
4739
#endif
4740
        }
4741
    }
8,862✔
4742
}
43,604✔
4743

4744
bool
4745
external_log_format::match_samples(const std::vector<sample_t>& samples) const
3,558,926✔
4746
{
4747
    for (const auto& sample_iter : samples) {
16,065,038✔
4748
        for (const auto& pat_iter : this->elf_pattern_order) {
34,466,188✔
4749
            auto& pat = *pat_iter;
21,960,076✔
4750

4751
            if (!pat.p_pcre.pp_value) {
21,960,076✔
4752
                continue;
×
4753
            }
4754

4755
            if (pat.p_pcre.pp_value
43,920,152✔
4756
                    ->find_in(sample_iter.s_line.pp_value, PCRE2_NO_UTF_CHECK)
43,920,152✔
4757
                    .ignore_error())
43,920,152✔
4758
            {
4759
                return true;
15,557✔
4760
            }
4761
        }
4762
    }
4763

4764
    return false;
3,543,369✔
4765
}
4766

4767
class external_log_table : public log_format_vtab_impl {
4768
public:
4769
    explicit external_log_table(std::shared_ptr<const log_format> elf)
43,604✔
4770
        : log_format_vtab_impl(elf),
43,604✔
4771
          elt_format(dynamic_cast<const external_log_format*>(elf.get()))
43,604✔
4772
    {
4773
    }
43,604✔
4774

4775
    void get_columns(std::vector<vtab_column>& cols) const override
43,996✔
4776
    {
4777
        const auto& elf = this->elt_format;
43,996✔
4778

4779
        cols.resize(elf->elf_column_count);
43,996✔
4780
        for (const auto& vd : elf->elf_value_def_order) {
434,681✔
4781
            auto type_pair = logline_value_to_sqlite_type(vd->vd_meta.lvm_kind);
390,685✔
4782

4783
            if (!vd->vd_meta.lvm_column.is<logline_value_meta::table_column>())
390,685✔
4784
            {
4785
                continue;
39,265✔
4786
            }
4787

4788
            auto col
4789
                = vd->vd_meta.lvm_column.get<logline_value_meta::table_column>()
351,420✔
4790
                      .value;
351,420✔
4791
            require(0 <= col && col < elf->elf_column_count);
351,420✔
4792

4793
            cols[col].vc_name = vd->vd_meta.lvm_name.get();
351,420✔
4794
            cols[col].vc_type = type_pair.first;
351,420✔
4795
            cols[col].vc_subtype = type_pair.second;
351,420✔
4796
            cols[col].vc_collator = vd->vd_collate;
351,420✔
4797
            cols[col].vc_comment = vd->vd_description;
351,420✔
4798
        }
4799
    }
43,996✔
4800

4801
    void get_foreign_keys(
35,478✔
4802
        std::unordered_set<std::string>& keys_inout) const override
4803
    {
4804
        log_vtab_impl::get_foreign_keys(keys_inout);
35,478✔
4805

4806
        for (const auto& elf_value_def : this->elt_format->elf_value_defs) {
511,272✔
4807
            if (elf_value_def.second->vd_meta.lvm_foreign_key
475,794✔
4808
                || elf_value_def.second->vd_meta.lvm_identifier)
475,794✔
4809
            {
4810
                keys_inout.emplace(elf_value_def.first.to_string());
173,691✔
4811
            }
4812
        }
4813
    }
35,478✔
4814

4815
    bool next(log_cursor& lc, logfile_sub_source& lss) override
3,476✔
4816
    {
4817
        if (lc.is_eof()) {
3,476✔
4818
            return true;
×
4819
        }
4820

4821
        content_line_t cl(lss.at(lc.lc_curr_line));
3,476✔
4822
        auto* lf = lss.find_file_ptr(cl);
3,476✔
4823
        auto lf_iter = lf->begin() + cl;
3,476✔
4824
        if (lf_iter->is_continued()) {
3,476✔
4825
            return false;
×
4826
        }
4827

4828
        if (lf->get_format_name() == this->lfvi_format->get_name()) {
3,476✔
4829
            return true;
3,470✔
4830
        }
4831

4832
        return false;
6✔
4833
    }
4834

4835
    void extract(logfile* lf,
3,385✔
4836
                 uint64_t line_number,
4837
                 string_attrs_t& sa,
4838
                 logline_value_vector& values) override
4839
    {
4840
        auto format = lf->get_format();
3,385✔
4841

4842
        sa.clear();
3,385✔
4843
        format->annotate(lf, line_number, sa, values);
3,385✔
4844
    }
3,385✔
4845

4846
    const external_log_format* elt_format;
4847
    line_range elt_container_body;
4848
};
4849

4850
std::shared_ptr<log_vtab_impl>
4851
external_log_format::get_vtab_impl() const
43,604✔
4852
{
4853
    return std::make_shared<external_log_table>(this->shared_from_this());
43,604✔
4854
}
4855

4856
std::shared_ptr<log_format>
4857
external_log_format::specialized(int fmt_lock)
504✔
4858
{
4859
    auto retval = std::make_shared<external_log_format>(*this);
504✔
4860

4861
    retval->lf_specialized = true;
504✔
4862
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
504✔
4863
        this->jlf_parse_context
4864
            = std::make_shared<yajlpp_parse_context>(this->elf_name);
47✔
4865
        this->jlf_yajl_handle.reset(
47✔
4866
            yajl_alloc(&this->jlf_parse_context->ypc_callbacks,
47✔
4867
                       nullptr,
4868
                       this->jlf_parse_context.get()),
47✔
4869
            yajl_handle_deleter());
4870
        yajl_config(this->jlf_yajl_handle.get(), yajl_dont_validate_strings, 1);
47✔
4871
        this->jlf_cached_line.reserve(16 * 1024);
47✔
4872
    }
4873

4874
    this->elf_specialized_value_defs_state = *this->elf_value_defs_state;
504✔
4875

4876
    return retval;
1,008✔
4877
}
504✔
4878

4879
log_format::match_name_result
4880
external_log_format::match_name(const std::string& filename)
846,480✔
4881
{
4882
    if (this->elf_filename_pcre.pp_value == nullptr) {
846,480✔
4883
        return name_matched{};
845,101✔
4884
    }
4885

4886
    if (this->elf_filename_pcre.pp_value->find_in(filename)
2,758✔
4887
            .ignore_error()
2,758✔
4888
            .has_value())
1,379✔
4889
    {
4890
        return name_matched{};
238✔
4891
    }
4892

4893
    return name_mismatched{
2,282✔
4894
        this->elf_filename_pcre.pp_value->match_partial(filename),
2,282✔
4895
        this->elf_filename_pcre.pp_value->get_pattern(),
1,141✔
4896
    };
1,141✔
4897
}
4898

4899
auto
4900
external_log_format::value_line_count(scan_batch_context& sbc,
223,576✔
4901
                                      const value_def* vd,
4902
                                      bool top_level,
4903
                                      std::optional<double> val,
4904
                                      const unsigned char* str,
4905
                                      ssize_t len,
4906
                                      yajl_string_props_t* props)
4907
    -> value_line_count_result
4908
{
4909
    value_line_count_result retval;
223,576✔
4910

4911
    if (vd == nullptr) {
223,576✔
4912
        if (this->jlf_hide_extra || !top_level) {
208,074✔
4913
            retval.vlcr_count = 0;
194,245✔
4914
        }
4915

4916
        return retval;
208,074✔
4917
    }
4918

4919
    if (str != nullptr && props != nullptr && !val) {
15,502✔
4920
        auto frag = string_fragment::from_bytes(str, len);
13,845✔
4921
        while (frag.endswith("\n")) {
14,014✔
4922
            frag.pop_back();
169✔
4923
            props->line_feeds -= 1;
169✔
4924
        }
4925
        retval.vlcr_has_ansi |= props->has_ansi;
13,845✔
4926
        retval.vlcr_count += props->line_feeds;
13,845✔
4927
    }
4928

4929
    if (vd->vd_meta.lvm_values_index) {
15,502✔
4930
        auto& lvs = sbc.sbc_value_stats[vd->vd_meta.lvm_values_index.value()];
6,538✔
4931
        if (len > lvs.lvs_width) {
6,538✔
4932
            lvs.lvs_width = len;
3,428✔
4933
        }
4934
        if (val) {
6,538✔
4935
            lvs.add_value(val.value());
168✔
4936
        }
4937
    }
4938

4939
    if (vd->vd_line_format_index) {
15,502✔
4940
        retval.vlcr_line_format_count += 1;
3,205✔
4941
        retval.vlcr_count -= 1;
3,205✔
4942
        retval.vlcr_line_format_index = vd->vd_line_format_index;
3,205✔
4943
    }
4944
    if (vd->vd_meta.is_hidden()) {
15,502✔
4945
        retval.vlcr_count = 0;
3,090✔
4946
        return retval;
3,090✔
4947
    }
4948

4949
    return retval;
12,412✔
4950
}
4951

4952
log_level_t
4953
external_log_format::convert_level(string_fragment sf,
191,810✔
4954
                                   scan_batch_context* sbc) const
4955
{
4956
    auto retval = LEVEL_INFO;
191,810✔
4957

4958
    if (sf.is_valid()) {
191,810✔
4959
        if (sbc != nullptr) {
150,314✔
4960
            auto ssm_res = sbc->sbc_level_cache.lookup(sf);
9,297✔
4961
            if (ssm_res.has_value()) {
9,297✔
4962
                return static_cast<log_level_t>(ssm_res.value());
4,106✔
4963
            }
4964
        }
4965

4966
        if (this->elf_level_patterns.empty()) {
146,208✔
4967
            retval = string2level(sf.data(), sf.length());
32,515✔
4968
        } else {
4969
            for (const auto& elf_level_pattern : this->elf_level_patterns) {
306,484✔
4970
                if (elf_level_pattern.second.lp_pcre.pp_value
560,978✔
4971
                        ->find_in(sf, PCRE2_NO_UTF_CHECK)
560,978✔
4972
                        .ignore_error()
560,978✔
4973
                        .has_value())
280,489✔
4974
                {
4975
                    retval = elf_level_pattern.first;
87,698✔
4976
                    break;
87,698✔
4977
                }
4978
            }
4979
        }
4980

4981
        if (sbc != nullptr
146,208✔
4982
            && sf.length() <= lnav::small_string_map::MAX_KEY_SIZE)
146,208✔
4983
        {
4984
            sbc->sbc_level_cache.insert(sf, retval);
4,547✔
4985
        }
4986
    }
4987

4988
    return retval;
187,704✔
4989
}
4990

4991
logline_value_meta
4992
external_log_format::get_value_meta(intern_string_t field_name,
15,182✔
4993
                                    value_kind_t kind)
4994
{
4995
    const auto iter = this->elf_value_defs.find(field_name);
15,182✔
4996
    if (iter == this->elf_value_defs.end()) {
15,182✔
4997
        auto retval = logline_value_meta(
4998
            field_name, kind, logline_value_meta::external_column{}, this);
976✔
4999

5000
        retval.lvm_hidden = this->jlf_hide_extra;
976✔
5001
        return retval;
976✔
5002
    }
976✔
5003

5004
    auto lvm = iter->second->vd_meta;
14,206✔
5005

5006
    lvm.lvm_kind = kind;
14,206✔
5007
    return lvm;
14,206✔
5008
}
14,206✔
5009

5010
logline_value_meta
5011
external_log_format::get_value_meta(yajlpp_parse_context* ypc,
2,363✔
5012
                                    const value_def* vd,
5013
                                    value_kind_t kind)
5014
{
5015
    if (vd == nullptr) {
2,363✔
5016
        auto retval = logline_value_meta(
5017
            ypc->get_path(), kind, logline_value_meta::external_column{}, this);
57✔
5018

5019
        retval.lvm_hidden = this->jlf_hide_extra;
57✔
5020
        return retval;
57✔
5021
    }
57✔
5022

5023
    auto lvm = vd->vd_meta;
2,306✔
5024

5025
    lvm.lvm_kind = kind;
2,306✔
5026
    return lvm;
2,306✔
5027
}
2,306✔
5028

5029
void
5030
external_log_format::json_append(const log_format_file_state& lffs,
8,859✔
5031
                                 const json_format_element& jfe,
5032
                                 const value_def* vd,
5033
                                 const string_fragment& sf)
5034
{
5035
    if (jfe.jfe_align == json_format_element::align_t::RIGHT) {
8,859✔
5036
        auto sf_width = sf.column_width();
330✔
5037
        if (sf_width < jfe.jfe_min_width) {
330✔
5038
            this->json_append_to_cache(jfe.jfe_min_width - sf_width);
×
5039
        } else if (jfe.jfe_auto_width && vd != nullptr
32✔
5040
                   && sf_width
362✔
5041
                       < lffs.lffs_value_stats[vd->vd_meta.lvm_values_index
32✔
5042
                                                   .value()]
32✔
5043
                             .lvs_width)
32✔
5044
        {
5045
            this->json_append_to_cache(
8✔
5046
                lffs.lffs_value_stats[vd->vd_meta.lvm_values_index.value()]
8✔
5047
                    .lvs_width
8✔
5048
                - sf_width);
8✔
5049
        }
5050
    }
5051
    this->json_append_to_cache(sf.data(), sf.length());
8,859✔
5052
    if ((jfe.jfe_align == json_format_element::align_t::LEFT
8,859✔
5053
         || jfe.jfe_align == json_format_element::align_t::NONE)
8,796✔
5054
        && (jfe.jfe_min_width > 0 || jfe.jfe_auto_width))
8,529✔
5055
    {
5056
        auto sf_width = sf.column_width();
1,241✔
5057
        if (sf_width < jfe.jfe_min_width) {
1,241✔
5058
            this->json_append_to_cache(jfe.jfe_min_width - sf_width);
378✔
5059
        } else if (jfe.jfe_auto_width && vd != nullptr
732✔
5060
                   && sf_width
1,595✔
5061
                       < lffs.lffs_value_stats[vd->vd_meta.lvm_values_index
644✔
5062
                                                   .value()]
644✔
5063
                             .lvs_width)
644✔
5064
        {
5065
            this->json_append_to_cache(
×
5066
                lffs.lffs_value_stats[vd->vd_meta.lvm_values_index.value()]
×
5067
                    .lvs_width
×
5068
                - sf_width);
×
5069
        }
5070
    }
5071
}
8,859✔
5072

5073
intern_string_t
5074
external_log_format::get_pattern_name(const pattern_locks& pl,
50✔
5075
                                      uint64_t line_number) const
5076
{
5077
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
50✔
5078
        static auto structured = intern_string::lookup("structured");
5079

5080
        return structured;
×
5081
    }
5082
    auto pat_index = pl.pattern_index_for_line(line_number);
50✔
5083
    return this->elf_pattern_order[pat_index]->p_name;
50✔
5084
}
5085

5086
std::string
5087
log_format::get_pattern_path(const pattern_locks& pl,
×
5088
                             uint64_t line_number) const
5089
{
5090
    auto pat_index = pl.pattern_index_for_line(line_number);
×
5091
    return fmt::format(FMT_STRING("builtin ({})"), pat_index);
×
5092
}
5093

5094
intern_string_t
5095
log_format::get_pattern_name(const pattern_locks& pl,
6✔
5096
                             uint64_t line_number) const
5097
{
5098
    char pat_str[128];
5099

5100
    auto pat_index = pl.pattern_index_for_line(line_number);
6✔
5101
    auto to_n_res = fmt::format_to_n(
×
5102
        pat_str, sizeof(pat_str) - 1, FMT_STRING("builtin ({})"), pat_index);
18✔
5103
    pat_str[to_n_res.size] = '\0';
6✔
5104
    return intern_string::lookup(pat_str);
12✔
5105
}
5106

5107
std::shared_ptr<log_format>
5108
log_format::find_root_format(const char* name)
1,276✔
5109
{
5110
    auto& fmts = get_root_formats();
1,276✔
5111
    for (auto& lf : fmts) {
49,458✔
5112
        if (lf->get_name() == name) {
49,458✔
5113
            return lf;
1,276✔
5114
        }
5115
    }
5116
    return nullptr;
×
5117
}
5118

5119
exttm
5120
log_format::tm_for_display(logfile::iterator ll, string_fragment sf)
957✔
5121
{
5122
    auto adjusted_time = ll->get_timeval();
957✔
5123
    exttm retval;
957✔
5124

5125
    retval.et_nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(
957✔
5126
                         std::chrono::microseconds{adjusted_time.tv_usec})
×
5127
                         .count();
957✔
5128
    if (this->lf_timestamp_flags & ETF_NANOS_SET) {
957✔
5129
        timeval actual_tv;
5130
        exttm tm;
×
5131
        if (this->lf_date_time.scan(sf.data(),
×
5132
                                    sf.length(),
×
5133
                                    this->get_timestamp_formats(),
5134
                                    &tm,
5135
                                    actual_tv,
5136
                                    false))
5137
        {
5138
            adjusted_time.tv_usec = actual_tv.tv_usec;
×
5139
            retval.et_nsec = tm.et_nsec;
×
5140
        }
5141
    }
5142
    gmtime_r(&adjusted_time.tv_sec, &retval.et_tm);
957✔
5143
    retval.et_flags = this->lf_timestamp_flags;
957✔
5144
    if (this->lf_timestamp_flags & ETF_ZONE_SET
957✔
5145
        && this->lf_date_time.dts_zoned_to_local)
867✔
5146
    {
5147
        retval.et_flags &= ~ETF_Z_IS_UTC;
867✔
5148
    }
5149
    retval.et_gmtoff = this->lf_date_time.dts_local_offset_cache;
957✔
5150

5151
    return retval;
1,914✔
5152
}
5153

5154
pattern_for_lines::pattern_for_lines(uint32_t pfl_line, uint32_t pfl_pat_index)
2,888✔
5155
    : pfl_line(pfl_line), pfl_pat_index(pfl_pat_index)
2,888✔
5156
{
5157
}
2,888✔
5158

5159
void
5160
logline_value_stats::merge(const logline_value_stats& other)
15,065✔
5161
{
5162
    if (other.lvs_count == 0) {
15,065✔
5163
        return;
13,948✔
5164
    }
5165

5166
    require(other.lvs_min_value <= other.lvs_max_value);
1,117✔
5167

5168
    if (other.lvs_width > this->lvs_width) {
1,117✔
5169
        this->lvs_width = other.lvs_width;
736✔
5170
    }
5171
    if (other.lvs_min_value < this->lvs_min_value) {
1,117✔
5172
        this->lvs_min_value = other.lvs_min_value;
763✔
5173
    }
5174
    if (other.lvs_max_value > this->lvs_max_value) {
1,117✔
5175
        this->lvs_max_value = other.lvs_max_value;
1,046✔
5176
    }
5177
    this->lvs_count += other.lvs_count;
1,117✔
5178
    this->lvs_total += other.lvs_total;
1,117✔
5179
    this->lvs_tdigest.insert(other.lvs_tdigest);
1,117✔
5180
    ensure(this->lvs_count >= 0);
1,117✔
5181
    ensure(this->lvs_min_value <= this->lvs_max_value);
1,117✔
5182
}
5183

5184
void
5185
logline_value_stats::add_value(double value)
31,405✔
5186
{
5187
    if (value < this->lvs_min_value) {
31,405✔
5188
        this->lvs_min_value = value;
1,640✔
5189
    }
5190
    if (value > this->lvs_max_value) {
31,405✔
5191
        this->lvs_max_value = value;
2,332✔
5192
    }
5193
    this->lvs_count += 1;
31,405✔
5194
    this->lvs_total += value;
31,405✔
5195
    this->lvs_tdigest.insert(value);
31,405✔
5196
}
31,405✔
5197

5198
std::vector<logline_value_meta>
5199
external_log_format::get_value_metadata() const
8,862✔
5200
{
5201
    std::vector<logline_value_meta> retval;
8,862✔
5202

5203
    for (const auto& vd : this->elf_value_def_order) {
93,051✔
5204
        retval.emplace_back(vd->vd_meta);
84,189✔
5205
    }
5206

5207
    return retval;
8,862✔
5208
}
×
5209

5210
std::optional<size_t>
5211
external_log_format::stats_index_for_value(const intern_string_t& name) const
72✔
5212
{
5213
    const auto iter = this->elf_value_defs.find(name);
72✔
5214
    if (iter != this->elf_value_defs.end()
72✔
5215
        && iter->second->vd_meta.lvm_values_index)
72✔
5216
    {
5217
        return iter->second->vd_meta.lvm_values_index.value();
72✔
5218
    }
5219

5220
    return std::nullopt;
×
5221
}
5222

5223
std::string
5224
external_log_format::get_pattern_regex(const pattern_locks& pl,
9✔
5225
                                       uint64_t line_number) const
5226
{
5227
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
9✔
5228
        return "";
2✔
5229
    }
5230
    auto pat_index = pl.pattern_index_for_line(line_number);
8✔
5231
    return this->elf_pattern_order[pat_index]->p_pcre.pp_value->get_pattern();
8✔
5232
}
5233

5234
bool
5235
external_log_format::hide_field(const intern_string_t field_name, bool val)
12✔
5236
{
5237
    const auto vd_iter = this->elf_value_defs.find(field_name);
12✔
5238
    if (vd_iter == this->elf_value_defs.end()) {
12✔
5239
        log_warning("field to hide not found: %s.%s",
1✔
5240
                    this->elf_name.c_str(),
5241
                    field_name.c_str());
5242
        return false;
1✔
5243
    }
5244

5245
    vd_iter->second->vd_meta.lvm_user_hidden = val;
11✔
5246
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
11✔
5247
        bool found = false;
2✔
5248

5249
        if (!field_name.to_string_fragment().find('#')) {
2✔
5250
            for (const auto& jfe : this->jlf_line_format) {
18✔
5251
                if (jfe.jfe_value.pp_value == field_name) {
17✔
5252
                    log_debug(
×
5253
                        "hide-field not triggering rebuild since it is in "
5254
                        "line-format: %s.%s",
5255
                        this->elf_name.c_str(),
5256
                        field_name.c_str());
5257
                    found = true;
×
5258
                    break;
×
5259
                }
5260
            }
5261
        }
5262
        if (!found) {
2✔
5263
            log_info("format field %s.%s changed, rebuilding",
2✔
5264
                     this->elf_name.get(),
5265
                     field_name.get());
5266
            this->elf_value_defs_state->vds_generation += 1;
2✔
5267
        }
5268
    }
5269
    return true;
11✔
5270
}
5271

5272
bool
5273
external_log_format::format_changed()
2,575✔
5274
{
5275
    if (this->elf_specialized_value_defs_state.vds_generation
5,150✔
5276
        != this->elf_value_defs_state->vds_generation)
2,575✔
5277
    {
5278
        this->elf_specialized_value_defs_state = *this->elf_value_defs_state;
2✔
5279
        this->jlf_cached_offset = -1;
2✔
5280
        return true;
2✔
5281
    }
5282

5283
    return false;
2,573✔
5284
}
5285

5286
bool
5287
format_tag_def::path_restriction::matches(const char* fn) const
5✔
5288
{
5289
    return fnmatch(this->p_glob.c_str(), fn, 0) == 0;
5✔
5290
}
5291

5292
bool
5293
format_partition_def::path_restriction::matches(const char* fn) const
5✔
5294
{
5295
    return fnmatch(this->p_glob.c_str(), fn, 0) == 0;
5✔
5296
}
5297

5298
int
5299
pattern_locks::pattern_index_for_line(uint64_t line_number) const
6,786✔
5300
{
5301
    if (this->pl_lines.empty()) {
6,786✔
5302
        return -1;
×
5303
    }
5304

5305
    auto iter
5306
        = std::lower_bound(this->pl_lines.cbegin(),
6,786✔
5307
                           this->pl_lines.cend(),
5308
                           line_number,
5309
                           [](const pattern_for_lines& pfl, uint32_t line) {
6,845✔
5310
                               return pfl.pfl_line < line;
6,845✔
5311
                           });
5312

5313
    if (iter == this->pl_lines.end() || iter->pfl_line != line_number) {
6,786✔
5314
        --iter;
6,154✔
5315
    }
5316

5317
    return iter->pfl_pat_index;
6,786✔
5318
}
5319

5320
/* XXX */
5321
#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