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

tstack / lnav / 19833402571-2724

01 Dec 2025 06:33PM UTC coverage: 68.86% (-0.001%) from 68.861%
19833402571-2724

push

github

tstack
[breadcrumb] add thread ID to breadcrumb bar

173 of 219 new or added lines in 14 files covered. (79.0%)

4 existing lines in 3 files now uncovered.

51293 of 74489 relevant lines covered (68.86%)

435674.56 hits per line

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

85.35
/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)
859✔
98
{
99
    this->lls_error_count += rhs.lls_error_count;
859✔
100
    this->lls_warning_count += rhs.lls_warning_count;
859✔
101
    this->lls_total_count += rhs.lls_total_count;
859✔
102

103
    return *this;
859✔
104
}
105

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

116
    return *this;
385✔
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)
385✔
129
{
130
    this->otr_range |= rhs.otr_range;
385✔
131
    this->otr_description |= rhs.otr_description;
385✔
132
    this->otr_level_stats |= rhs.otr_level_stats;
385✔
133
    for (const auto& rhs_sub : rhs.otr_sub_ops) {
390✔
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());
385✔
147

148
    return *this;
385✔
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)
24,238✔
169
{
170
    switch (lvl) {
24,238✔
171
        case LEVEL_FATAL:
1,234✔
172
        case LEVEL_CRITICAL:
173
        case LEVEL_ERROR:
174
            this->lls_error_count += amount;
1,234✔
175
            break;
1,234✔
176
        case LEVEL_WARNING:
111✔
177
            this->lls_warning_count += amount;
111✔
178
            break;
111✔
179
        default:
22,893✔
180
            break;
22,893✔
181
    }
182
    this->lls_total_count += amount;
24,238✔
183
}
24,238✔
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,482✔
197
                                const string_fragment& tid,
198
                                const std::chrono::microseconds& us)
199
{
200
    auto retval = this->ltis_tid_ranges.find(tid);
11,482✔
201
    if (retval == this->ltis_tid_ranges.end()) {
11,482✔
202
        auto tid_copy = tid.to_owned(alloc);
6,318✔
203
        auto titr = thread_id_time_range{time_range{us, us}};
6,318✔
204
        auto emplace_res = this->ltis_tid_ranges.emplace(tid_copy, titr);
6,318✔
205
        retval = emplace_res.first;
6,318✔
206
    } else {
207
        retval->second.titr_range.extend_to(us);
5,164✔
208
    }
209

210
    return retval;
11,482✔
211
}
212

213
log_opid_map::iterator
214
log_opid_state::insert_op(ArenaAlloc::Alloc<char>& alloc,
12,692✔
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,692✔
221
    if (retval == this->los_opid_ranges.end()) {
12,692✔
222
        auto opid_copy = opid.to_owned(alloc);
6,468✔
223
        auto otr = opid_time_range{time_range{us, us}};
6,468✔
224
        auto emplace_res = this->los_opid_ranges.emplace(opid_copy, otr);
6,468✔
225
        retval = emplace_res.first;
6,468✔
226
    } else {
6,468✔
227
        retval->second.otr_range.extend_to(us);
6,224✔
228
    }
229
    if (duration > 0us) {
12,692✔
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,692✔
243
}
244

245
opid_sub_time_range*
246
log_opid_state::sub_op_in_use(ArenaAlloc::Alloc<char>& alloc,
64✔
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;
64✔
253
    auto sub_iter = this->los_sub_in_use.find(subid);
64✔
254
    if (sub_iter == this->los_sub_in_use.end()) {
64✔
255
        auto emp_res
256
            = this->los_sub_in_use.emplace(subid.to_owned(alloc), opid);
43✔
257

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

261
    auto retval = sub_iter->first;
64✔
262
    if (sub_iter->second != opid) {
64✔
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;
64✔
270

271
    auto& otr = op_iter->second;
64✔
272
    auto sub_op_iter = otr.otr_sub_ops.rbegin();
64✔
273
    for (; sub_op_iter != otr.otr_sub_ops.rend(); ++sub_op_iter) {
64✔
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()) {
64✔
279
        otr.otr_sub_ops.emplace_back(opid_sub_time_range{
43✔
280
            retval,
281
            time_range{us, us},
282
        });
283
        otr.otr_sub_ops.back().ostr_level_stats.update_msg_count(level);
43✔
284

285
        return &otr.otr_sub_ops.back();
43✔
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,640✔
295
{
296
    if (this->od_extractor.pp_value) {
2,640✔
297
        thread_local auto desc_md = lnav::pcre2pp::match_data::unitialized();
859✔
298

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

307
        return std::nullopt;
793✔
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,
633,891✔
417
                             shared_buffer_ref& sbr,
418
                             struct line_range origin)
633,891✔
419
    : lv_meta(std::move(lvm)), lv_origin(origin)
633,891✔
420
{
421
    if (sbr.get_data() == nullptr) {
633,891✔
422
        this->lv_meta.lvm_kind = value_kind_t::VALUE_NULL;
×
423
    }
424

425
    switch (this->lv_meta.lvm_kind) {
633,891✔
426
        case value_kind_t::VALUE_JSON:
322,230✔
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);
322,230✔
434
            this->lv_frag = string_fragment::from_byte_range(
322,230✔
435
                sbr.get_data(), origin.lr_start, origin.lr_end);
322,230✔
436
            break;
322,230✔
437

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

441
        case value_kind_t::VALUE_INTEGER: {
281,364✔
442
            auto scan_res
443
                = scn::scan_value<int64_t>(sbr.to_string_view(origin));
281,364✔
444
            if (scan_res) {
281,364✔
445
                this->lv_value.i = scan_res->value();
281,362✔
446
            } else {
447
                this->lv_value.i = 0;
2✔
448
            }
449
            break;
281,364✔
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
}
633,891✔
482

483
void
484
logline_value::apply_scaling(const scaling_factor* sf)
42,841✔
485
{
486
    if (sf != nullptr) {
42,841✔
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,841✔
499

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

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

509
        case value_kind_t::VALUE_JSON:
9,463✔
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,463✔
515
                return this->lv_str.value();
1,418✔
516
            }
517
            if (this->lv_frag.empty()) {
8,045✔
518
                return this->lv_intern_string.to_string();
55✔
519
            }
520
            return this->lv_frag.to_string();
7,990✔
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:
538✔
551
            snprintf(buffer, sizeof(buffer), "%" PRId64, this->lv_value.i);
538✔
552
            break;
538✔
553

554
        case value_kind_t::VALUE_FLOAT:
32✔
555
            snprintf(buffer, sizeof(buffer), "%lf", this->lv_value.d);
32✔
556
            break;
32✔
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,140✔
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()
41,603✔
686
{
687
    this->lvv_values.clear();
41,603✔
688
    this->lvv_sbr.disown();
41,603✔
689
    this->lvv_opid_value = std::nullopt;
41,603✔
690
    this->lvv_opid_provenance = opid_provenance::none;
41,603✔
691
    this->lvv_thread_id_value = std::nullopt;
41,603✔
692
}
41,603✔
693

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

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

711
    return *this;
407✔
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,431✔
718
{
719
    return lf_root_formats;
17,431✔
720
}
721

722
void
723
external_log_format::update_op_description(
5,450✔
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;
5,450✔
730
    if (!lod.lod_index) {
5,450✔
731
        for (const auto& desc_defs : desc_defs_vec) {
4,015✔
732
            if (lod.lod_index) {
1,763✔
733
                break;
26✔
734
            }
735
            for (const auto& desc_def : *desc_defs->od_descriptors) {
2,570✔
736
                auto desc_field_index_iter = fpat->p_value_name_to_index.find(
1,835✔
737
                    desc_def.od_field.pp_value);
1,835✔
738

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

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

749
                desc_elem_str = desc_def.matches(desc_cap_opt.value());
1,792✔
750
                if (desc_elem_str) {
1,792✔
751
                    lod.lod_index = desc_defs->od_index;
1,002✔
752
                    break;
1,002✔
753
                }
754
            }
755
        }
756
    }
757
    if (lod.lod_index) {
5,450✔
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
}
5,450✔
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,301,082✔
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,301,082✔
869

870
    if (locked_index == -1) {
2,301,082✔
871
        index += 1;
2,293,828✔
872
        if (index >= (int) patterns.size()) {
2,293,828✔
873
            retval = false;
694,870✔
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,301,082✔
882
}
883

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

889
    if (locked_index == -1) {
179,678✔
890
        index += 1;
179,507✔
891
        if (fmt[index].name == nullptr) {
179,507✔
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,678✔
901
}
902

903
const char*
904
log_format::log_scanf(scan_batch_context& sbc,
12,529✔
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,529✔
916
    const char* retval = nullptr;
12,529✔
917
    bool done = false;
12,529✔
918
    int pat_index = sbc.sbc_pattern_locks.last_pattern_index();
12,529✔
919

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

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

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

936
            if (retval == nullptr) {
23,730✔
937
                auto ls = this->lf_date_time.unlock();
21,345✔
938
                retval = this->lf_date_time.scan(
21,345✔
939
                    ts->data(), ts->length(), nullptr, tm_out, *tv_out);
21,345✔
940
                if (retval != nullptr) {
21,345✔
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,345✔
952
                    this->lf_date_time.relock(ls);
21,345✔
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,730✔
964
                *ts_out = ts.value();
2,385✔
965
                if (md[2]) {
2,385✔
966
                    *level_out = md[2];
246✔
967
                } else {
968
                    *level_out = line.substr(md[0]->sf_end);
2,139✔
969
                }
970
                if (curr_fmt != pat_index) {
2,385✔
971
                    uint32_t lock_line;
972

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

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

988
    return retval;
12,529✔
989
}
990

991
void
992
log_format::annotate(logfile* lf,
37,172✔
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,172✔
998
        const auto& bm = lf->get_bookmark_metadata();
2,462✔
999
        auto bm_iter = bm.find(line_number);
2,462✔
1000
        if (bm_iter != bm.end() && !bm_iter->second.bm_opid.empty()) {
2,462✔
1001
            values.lvv_opid_value = bm_iter->second.bm_opid;
18✔
1002
            values.lvv_opid_provenance
1003
                = logline_value_vector::opid_provenance::user;
18✔
1004
        }
1005
    }
1006
}
37,172✔
1007

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

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

1022
    if (diff <= 0) {
1,261✔
1023
        return;
1,202✔
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,150✔
1077
        : jlu_shared_buffer(sbr), jlu_batch_context(sbc)
24,300✔
1078
    {
1079
    }
12,150✔
1080

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

1087
        if (this->jlu_read_order_index < format->elf_value_def_read_order.size()
314,909✔
1088
            && format->elf_value_def_read_order[this->jlu_read_order_index]
424,100✔
1089
                    .first
1090
                == field_frag)
109,191✔
1091
        {
1092
            return format
1093
                ->elf_value_def_read_order[this->jlu_read_order_index++]
104,463✔
1094
                .second;
104,463✔
1095
        }
1096

1097
        format->elf_value_def_read_order.resize(this->jlu_read_order_index);
210,446✔
1098
        auto vd_iter = format->elf_value_def_frag_map.find(field_frag);
210,446✔
1099
        if (vd_iter != format->elf_value_def_frag_map.end()) {
210,446✔
1100
            format->elf_value_def_read_order.emplace_back(vd_iter->first,
182,102✔
1101
                                                          vd_iter->second);
182,102✔
1102
            this->jlu_read_order_index += 1;
182,102✔
1103
            return vd_iter->second;
182,102✔
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,150✔
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,523✔
1339
{
1340
    auto* ypc = (yajlpp_parse_context*) ctx;
13,523✔
1341
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
13,523✔
1342

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

1347
    return 1;
13,523✔
1348
}
1349

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

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

1370
    return 1;
13,503✔
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,858✔
1437
{
1438
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
10,858✔
1439
    const auto* vd = jlu->get_field_def(ypc);
10,858✔
1440

1441
    if (vd != nullptr) {
10,858✔
1442
        const intern_string_t field_name = vd->vd_meta.lvm_name;
835✔
1443
        if (jlu->jlu_format->lf_timestamp_field == field_name) {
835✔
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) {
810✔
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,858✔
1482
        return 1;
9,976✔
1483
    }
1484
    if (vd != nullptr
882✔
1485
        && vd->vd_meta.lvm_name == jlu->jlu_format->elf_thread_id_field)
882✔
1486
    {
1487
        jlu->jlu_tid_number = val;
142✔
1488
    }
1489
    jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
882✔
1490
        jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_INTEGER),
882✔
1491
        (int64_t) val);
882✔
1492
    return 1;
882✔
1493
}
1494

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

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

1507
            tv.tv_sec = val / divisor;
130✔
1508
            tv.tv_usec = fmod(val, divisor) * (1000000.0 / divisor);
130✔
1509
            jlu->jlu_format->lf_date_time.to_localtime(tv.tv_sec,
130✔
1510
                                                       jlu->jlu_exttm);
130✔
1511
            jlu->jlu_exttm.et_gmtoff
1512
                = jlu->jlu_format->lf_date_time.dts_local_offset_cache;
130✔
1513
            jlu->jlu_exttm.et_flags |= ETF_MACHINE_ORIENTED
130✔
1514
                | ETF_SUB_NOT_IN_FORMAT | ETF_ZONE_SET | ETF_Z_FOR_UTC;
1515
            if (divisor == 1) {
130✔
1516
                jlu->jlu_exttm.et_flags |= ETF_MICROS_SET;
118✔
1517
            } else {
1518
                jlu->jlu_exttm.et_flags |= ETF_MILLIS_SET;
12✔
1519
            }
1520
            jlu->jlu_exttm.et_nsec = tv.tv_usec * 1000;
130✔
1521
        } else if (jlu->jlu_format->lf_subsecond_field == field_name) {
28✔
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) {
28✔
1539
            jlu->jlu_duration = std::chrono::microseconds(
56✔
1540
                static_cast<int64_t>(val * 1000000.0));
28✔
1541
        }
1542
    }
1543

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

1551
    return 1;
162✔
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,272✔
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,272✔
1610
    auto line_frag = sbr.to_string_fragment();
153,272✔
1611

1612
    if (!line_frag.startswith("{")) {
153,272✔
1613
        if (!this->lf_specialized) {
143,573✔
1614
            return scan_no_match{"line is not a JSON object"};
143,568✔
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,775✔
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,775✔
1858
        auto file_options = lf.get_file_options();
33,192✔
1859

1860
        if (file_options) {
33,192✔
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,900✔
1865
        }
1866
    }
33,192✔
1867

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

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

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

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

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

1902
        if (fpat->p_time_field_index != -1) {
5,878✔
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,878✔
1918
            level_cap.value_or(string_fragment::invalid()), &sbc);
5,878✔
1919

1920
        if (!ts) {
5,878✔
1921
            level = log_level_t::LEVEL_INVALID;
×
1922
        } else if ((last
5,878✔
1923
                    = this->lf_date_time.scan(ts->data(),
11,756✔
1924
                                              ts->length(),
5,878✔
1925
                                              this->get_timestamp_formats(),
1926
                                              &log_time_tm,
1927
                                              log_tv))
1928
                   == nullptr)
5,878✔
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,875✔
1959

1960
        if (!(this->lf_timestamp_flags
11,750✔
1961
              & (ETF_MILLIS_SET | ETF_MICROS_SET | ETF_NANOS_SET))
5,875✔
1962
            && !dst.empty()
5,287✔
1963
            && dst.back().get_time<std::chrono::seconds>().count()
4,548✔
1964
                == log_tv.tv_sec
4,548✔
1965
            && dst.back()
14,598✔
1966
                    .get_subsecond_time<std::chrono::milliseconds>()
9,311✔
1967
                    .count()
3,436✔
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,875✔
1982
              && (log_time_tm.et_flags & ETF_MONTH_SET)
5,834✔
1983
              && (log_time_tm.et_flags & ETF_YEAR_SET)))
5,834✔
1984
        {
1985
            this->check_for_new_year(dst, log_time_tm, log_tv);
794✔
1986
        }
1987

1988
        auto log_us = to_us(log_tv);
5,875✔
1989
        if (!fpat->p_opid_description_field_indexes.empty()) {
5,875✔
1990
            hasher h;
4,526✔
1991
            for (auto& fidx : fpat->p_opid_description_field_indexes) {
13,053✔
1992
                auto desc_cap = md[fidx];
8,527✔
1993
                if (desc_cap) {
8,527✔
1994
                    h.update(desc_cap.value());
8,480✔
1995
                }
1996
            }
1997
            h.to_string(tmp_opid_buf);
4,526✔
1998
            opid_cap = string_fragment::from_bytes(tmp_opid_buf,
9,052✔
1999
                                                   sizeof(tmp_opid_buf) - 1);
4,526✔
2000
        }
2001

2002
        auto duration_cap = md[fpat->p_duration_field_index];
5,875✔
2003
        if (duration_cap && !opid_cap) {
5,875✔
2004
            hasher h;
86✔
2005
            h.update(line_sf);
86✔
2006
            h.to_string(tmp_opid_buf);
86✔
2007
            opid_cap = string_fragment::from_bytes(tmp_opid_buf,
172✔
2008
                                                   sizeof(tmp_opid_buf) - 1);
86✔
2009
        }
2010
        if (opid_cap && !opid_cap->empty()) {
5,875✔
2011
            auto duration = std::chrono::microseconds{0};
5,407✔
2012
            if (duration_cap) {
5,407✔
2013
                auto from_res
2014
                    = humanize::try_from<double>(duration_cap.value());
86✔
2015
                if (from_res) {
86✔
2016
                    duration = std::chrono::microseconds(
×
2017
                        static_cast<int64_t>(from_res.value() * 1000000));
86✔
2018
                }
2019
            }
2020
            auto opid_iter
2021
                = sbc.sbc_opids.insert_op(sbc.sbc_allocator,
10,814✔
2022
                                          opid_cap.value(),
5,407✔
2023
                                          log_us,
2024
                                          this->lf_timestamp_point_of_reference,
2025
                                          duration);
2026
            auto& otr = opid_iter->second;
5,407✔
2027

2028
            otr.otr_level_stats.update_msg_count(level);
5,407✔
2029
            if (fpat->p_subid_field_index != -1) {
5,407✔
2030
                auto subid_cap = md[fpat->p_subid_field_index];
64✔
2031
                if (subid_cap && !subid_cap->empty()) {
64✔
2032
                    auto* ostr = sbc.sbc_opids.sub_op_in_use(sbc.sbc_allocator,
192✔
2033
                                                             opid_iter,
2034
                                                             subid_cap.value(),
64✔
2035
                                                             log_us,
2036
                                                             level);
2037
                    if (ostr != nullptr && ostr->ostr_description.empty()) {
64✔
2038
                        log_op_description sub_desc;
43✔
2039
                        this->update_op_description(
43✔
2040
                            *this->lf_subid_description_def_vec,
43✔
2041
                            sub_desc,
2042
                            fpat,
2043
                            md);
2044
                        if (!sub_desc.lod_elements.empty()) {
43✔
2045
                            auto& sub_desc_def
2046
                                = this->lf_subid_description_def_vec->at(
39✔
2047
                                    sub_desc.lod_index.value());
39✔
2048
                            ostr->ostr_description = sub_desc_def->to_string(
78✔
2049
                                sub_desc.lod_elements);
39✔
2050
                        }
2051
                    }
43✔
2052
                }
2053
            }
2054
            this->update_op_description(*this->lf_opid_description_def_vec,
5,407✔
2055
                                        otr.otr_description,
5,407✔
2056
                                        fpat,
2057
                                        md);
2058
            opid_bloom = opid_cap->bloom_bits();
5,407✔
2059
        }
2060

2061
        for (const auto& ivd : fpat->p_value_by_index) {
66,461✔
2062
            if (!ivd.ivd_value_def->vd_meta.lvm_values_index) {
60,586✔
2063
                continue;
11,044✔
2064
            }
2065

2066
            ssize_t cap_size = md.capture_size(ivd.ivd_index);
49,542✔
2067
            auto& lvs = sbc.sbc_value_stats[ivd.ivd_value_def->vd_meta
49,542✔
2068
                                                .lvm_values_index.value()];
49,542✔
2069

2070
            if (cap_size > lvs.lvs_width) {
49,542✔
2071
                lvs.lvs_width = cap_size;
6,433✔
2072
            }
2073
        }
2074

2075
        for (auto value_index : fpat->p_numeric_value_indexes) {
10,744✔
2076
            const indexed_value_def& ivd = fpat->p_value_by_index[value_index];
4,869✔
2077
            const value_def& vd = *ivd.ivd_value_def;
4,869✔
2078
            auto num_cap = md[ivd.ivd_index];
4,869✔
2079

2080
            if (num_cap && num_cap->is_valid()) {
4,869✔
2081
                const struct scaling_factor* scaling = nullptr;
4,803✔
2082

2083
                if (ivd.ivd_unit_field_index >= 0) {
4,803✔
2084
                    auto unit_cap = md[ivd.ivd_unit_field_index];
80✔
2085

2086
                    if (unit_cap && unit_cap->is_valid()) {
80✔
2087
                        intern_string_t unit_val
2088
                            = intern_string::lookup(unit_cap.value());
80✔
2089

2090
                        auto unit_iter = vd.vd_unit_scaling.find(unit_val);
80✔
2091
                        if (unit_iter != vd.vd_unit_scaling.end()) {
80✔
2092
                            const auto& sf = unit_iter->second;
80✔
2093

2094
                            scaling = &sf;
80✔
2095
                        }
2096
                    }
2097
                }
2098

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

2131
        dst.emplace_back(li.li_file_range.fr_offset, log_us, level);
5,875✔
2132
        auto& new_line = dst.back();
5,875✔
2133
        new_line.merge_bloom_bits(opid_bloom);
5,875✔
2134

2135
        auto src_file_cap = md[fpat->p_src_file_field_index];
5,875✔
2136
        auto src_line_cap = md[fpat->p_src_line_field_index];
5,875✔
2137
        if (src_file_cap && src_line_cap) {
5,875✔
2138
            auto h = hasher();
94✔
2139
            h.update(this->get_name().c_str());
94✔
2140
            h.update(src_file_cap.value());
94✔
2141
            h.update(src_line_cap.value());
94✔
2142
            new_line.merge_bloom_bits(h.to_bloom_bits());
94✔
2143
            new_line.set_schema_computed(true);
94✔
2144
        }
2145
        auto thread_id_cap = md[fpat->p_thread_id_field_index];
5,875✔
2146
        if (thread_id_cap) {
5,875✔
2147
            auto tid_iter = sbc.sbc_tids.insert_tid(
2,082✔
2148
                sbc.sbc_allocator, thread_id_cap.value(), log_us);
1,041✔
2149
            tid_iter->second.titr_level_stats.update_msg_count(level);
1,041✔
2150
            new_line.merge_bloom_bits(thread_id_cap->bloom_bits());
1,041✔
2151
        } else {
2152
            auto tid_iter = sbc.sbc_tids.insert_tid(
4,834✔
2153
                sbc.sbc_allocator, string_fragment{}, log_us);
×
2154
            tid_iter->second.titr_level_stats.update_msg_count(level);
4,834✔
2155
        }
2156

2157
        if (orig_lock != curr_fmt) {
5,875✔
2158
            uint32_t lock_line;
2159

2160
            if (!this->lf_specialized && orig_lock != -1) {
624✔
2161
                log_debug("%s:%zu: changing pattern lock %d -> (%d)%s",
×
2162
                          lf.get_unique_path().c_str(),
2163
                          dst.size() - 1,
2164
                          orig_lock,
2165
                          curr_fmt,
2166
                          this->elf_pattern_order[curr_fmt]->p_name.c_str());
2167
            }
2168
            if (sbc.sbc_pattern_locks.empty()) {
624✔
2169
                lock_line = 0;
598✔
2170
            } else {
2171
                lock_line = dst.size() - 1;
26✔
2172
            }
2173
            sbc.sbc_pattern_locks.pl_lines.emplace_back(lock_line, curr_fmt);
624✔
2174
        }
2175
        return scan_match{1000};
5,875✔
2176
    }
2177

2178
    if (this->lf_specialized && !this->lf_multiline && !dst.empty()) {
694,871✔
2179
        const auto& last_line = dst.back();
1✔
2180

2181
        log_debug("%s: invalid line %zu file_offset=%" PRIu64,
1✔
2182
                  lf.get_filename().c_str(),
2183
                  dst.size(),
2184
                  li.li_file_range.fr_offset);
2185
        dst.emplace_back(li.li_file_range.fr_offset,
1✔
NEW
2186
                         last_line.get_time<std::chrono::microseconds>(),
×
2187
                         log_level_t::LEVEL_INVALID);
1✔
2188

2189
        return scan_match{0};
1✔
2190
    }
2191

2192
    return scan_no_match{"no patterns matched"};
694,870✔
2193
}
2194

2195
void
2196
external_log_format::annotate(logfile* lf,
7,407✔
2197
                              uint64_t line_number,
2198
                              string_attrs_t& sa,
2199
                              logline_value_vector& values) const
2200
{
2201
    thread_local auto md = lnav::pcre2pp::match_data::unitialized();
7,407✔
2202

2203
    auto& line = values.lvv_sbr;
7,407✔
2204
    line_range lr;
7,407✔
2205

2206
    line.erase_ansi();
7,407✔
2207
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
7,407✔
2208
        if (this->jlf_cached_opts.full_message) {
763✔
2209
            values = this->jlf_line_values;
319✔
2210
            sa = this->jlf_line_attrs;
319✔
2211
        } else {
2212
            values.lvv_sbr = this->jlf_line_values.lvv_sbr.clone();
444✔
2213
            for (const auto& llv : this->jlf_line_values.lvv_values) {
4,533✔
2214
                if (this->jlf_cached_sub_range.contains(llv.lv_origin)) {
4,089✔
2215
                    values.lvv_values.emplace_back(llv);
947✔
2216
                    values.lvv_values.back().lv_origin.shift(
947✔
2217
                        this->jlf_cached_sub_range.lr_start,
947✔
2218
                        -this->jlf_cached_sub_range.lr_start);
947✔
2219
                }
2220
            }
2221
            for (const auto& attr : this->jlf_line_attrs) {
2,504✔
2222
                if (this->jlf_cached_sub_range.contains(attr.sa_range)) {
2,060✔
2223
                    sa.emplace_back(attr);
709✔
2224
                    sa.back().sa_range.shift(
709✔
2225
                        this->jlf_cached_sub_range.lr_start,
709✔
2226
                        -this->jlf_cached_sub_range.lr_start);
709✔
2227
                }
2228
            }
2229
            values.lvv_opid_value = this->jlf_line_values.lvv_opid_value;
444✔
2230
            values.lvv_opid_provenance
2231
                = this->jlf_line_values.lvv_opid_provenance;
444✔
2232
            values.lvv_thread_id_value
2233
                = this->jlf_line_values.lvv_thread_id_value;
444✔
2234
        }
2235
        log_format::annotate(lf, line_number, sa, values);
763✔
2236
        return;
2,386✔
2237
    }
2238

2239
    if (line.empty()) {
6,644✔
2240
        return;
5✔
2241
    }
2242

2243
    values.lvv_values.reserve(this->elf_value_defs.size());
6,639✔
2244

2245
    auto lffs = lf->get_format_file_state();
6,639✔
2246
    int pat_index = lffs.lffs_pattern_locks.pattern_index_for_line(line_number);
6,639✔
2247
    const auto& pat = *this->elf_pattern_order[pat_index];
6,639✔
2248
    char tmp_opid_buf[hasher::STRING_SIZE];
2249

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

2271
    auto duration_cap = md[pat.p_duration_field_index];
5,021✔
2272

2273
    auto ts_cap = md[pat.p_timestamp_field_index];
5,021✔
2274
    if (ts_cap) {
5,021✔
2275
        sa.emplace_back(to_line_range(ts_cap.value()), L_TIMESTAMP.value());
5,021✔
2276
    }
2277

2278
    auto opid_cap = md[pat.p_opid_field_index];
5,021✔
2279

2280
    if (!pat.p_opid_description_field_indexes.empty()) {
5,021✔
2281
        hasher h;
4,203✔
2282
        for (auto& fidx : pat.p_opid_description_field_indexes) {
12,169✔
2283
            auto desc_cap = md[fidx];
7,966✔
2284
            if (desc_cap) {
7,966✔
2285
                h.update(desc_cap.value());
7,938✔
2286
            }
2287
        }
2288
        h.to_string(tmp_opid_buf);
4,203✔
2289
        opid_cap = string_fragment::from_bytes(tmp_opid_buf,
8,406✔
2290
                                               sizeof(tmp_opid_buf) - 1);
4,203✔
2291
    } else if (duration_cap && !opid_cap) {
818✔
2292
        hasher h;
3✔
2293
        h.update(line.to_string_fragment());
3✔
2294
        h.to_string(tmp_opid_buf);
3✔
2295
        opid_cap = string_fragment::from_bytes(tmp_opid_buf,
6✔
2296
                                               sizeof(tmp_opid_buf) - 1);
3✔
2297
    }
2298
    if (opid_cap && !opid_cap->empty()) {
5,021✔
2299
        sa.emplace_back(to_line_range(opid_cap.value()), L_OPID.value());
4,647✔
2300
        values.lvv_opid_value = opid_cap->to_string();
4,647✔
2301
        values.lvv_opid_provenance
2302
            = logline_value_vector::opid_provenance::file;
4,647✔
2303
    }
2304

2305
    auto body_cap = md[pat.p_body_field_index];
5,021✔
2306
    auto level_cap = md[pat.p_level_field_index];
5,021✔
2307
    auto src_file_cap = md[pat.p_src_file_field_index];
5,021✔
2308
    auto src_line_cap = md[pat.p_src_line_field_index];
5,021✔
2309
    auto thread_id_cap = md[pat.p_thread_id_field_index];
5,021✔
2310

2311
    if (level_cap
5,021✔
2312
        && (!body_cap
9,996✔
2313
            || (body_cap && level_cap->sf_begin != body_cap->sf_begin)))
9,996✔
2314
    {
2315
        sa.emplace_back(to_line_range(level_cap.value()), L_LEVEL.value());
4,586✔
2316
    }
2317

2318
    if (src_file_cap) {
5,021✔
2319
        sa.emplace_back(to_line_range(src_file_cap.value()),
105✔
2320
                        SA_SRC_FILE.value());
210✔
2321
    }
2322
    if (src_line_cap) {
5,021✔
2323
        sa.emplace_back(to_line_range(src_line_cap.value()),
105✔
2324
                        SA_SRC_LINE.value());
210✔
2325
    }
2326
    if (thread_id_cap) {
5,021✔
2327
        sa.emplace_back(to_line_range(thread_id_cap.value()),
611✔
2328
                        SA_THREAD_ID.value());
1,222✔
2329
        values.lvv_thread_id_value = thread_id_cap->to_string();
611✔
2330
    }
2331
    if (duration_cap) {
5,021✔
2332
        sa.emplace_back(to_line_range(duration_cap.value()),
3✔
2333
                        SA_DURATION.value());
6✔
2334
    }
2335

2336
    for (size_t lpc = 0; lpc < pat.p_value_by_index.size(); lpc++) {
57,518✔
2337
        const auto& ivd = pat.p_value_by_index[lpc];
52,497✔
2338
        const scaling_factor* scaling = nullptr;
52,497✔
2339
        auto cap = md[ivd.ivd_index];
52,497✔
2340
        const auto& vd = *ivd.ivd_value_def;
52,497✔
2341

2342
        if (ivd.ivd_unit_field_index >= 0) {
52,497✔
2343
            auto unit_cap = md[ivd.ivd_unit_field_index];
10✔
2344

2345
            if (unit_cap) {
10✔
2346
                intern_string_t unit_val
2347
                    = intern_string::lookup(unit_cap.value());
10✔
2348
                auto unit_iter = vd.vd_unit_scaling.find(unit_val);
10✔
2349
                if (unit_iter != vd.vd_unit_scaling.end()) {
10✔
2350
                    const auto& sf = unit_iter->second;
10✔
2351

2352
                    scaling = &sf;
10✔
2353
                }
2354
            }
2355
        }
2356

2357
        if (cap) {
52,497✔
2358
            values.lvv_values.emplace_back(
85,682✔
2359
                vd.vd_meta, line, to_line_range(cap.value()));
42,841✔
2360
            values.lvv_values.back().apply_scaling(scaling);
42,841✔
2361
        } else {
2362
            values.lvv_values.emplace_back(vd.vd_meta);
9,656✔
2363
        }
2364
    }
2365

2366
    if (body_cap && body_cap->is_valid()) {
5,021✔
2367
        lr = to_line_range(body_cap.value());
5,009✔
2368
    } else {
2369
        lr.lr_start = line.length();
12✔
2370
        lr.lr_end = line.length();
12✔
2371
    }
2372
    sa.emplace_back(lr, SA_BODY.value());
5,021✔
2373

2374
    log_format::annotate(lf, line_number, sa, values);
5,021✔
2375
}
2376

2377
void
2378
external_log_format::rewrite(exec_context& ec,
43✔
2379
                             shared_buffer_ref& line,
2380
                             string_attrs_t& sa,
2381
                             std::string& value_out)
2382
{
2383
    auto& values = *ec.ec_line_values;
43✔
2384

2385
    value_out.assign(line.get_data(), line.length());
43✔
2386

2387
    for (auto iter = values.lvv_values.begin(); iter != values.lvv_values.end();
259✔
2388
         ++iter)
216✔
2389
    {
2390
        if (!iter->lv_origin.is_valid()) {
216✔
2391
            log_debug("%d: not rewriting value with invalid origin -- %s",
24✔
2392
                      (int) ec.ec_top_line,
2393
                      iter->lv_meta.lvm_name.get());
2394
            continue;
184✔
2395
        }
2396

2397
        auto vd_iter = this->elf_value_defs.find(iter->lv_meta.lvm_name);
192✔
2398
        if (vd_iter == this->elf_value_defs.end()) {
192✔
2399
            log_debug("%d: not rewriting undefined value -- %s",
×
2400
                      (int) ec.ec_top_line,
2401
                      iter->lv_meta.lvm_name.get());
2402
            continue;
×
2403
        }
2404

2405
        const auto& vd = *vd_iter->second;
192✔
2406

2407
        if (vd.vd_rewriter.empty()) {
192✔
2408
            continue;
160✔
2409
        }
2410

2411
        auto _sg = ec.enter_source(
2412
            vd_iter->second->vd_rewrite_src_name, 1, vd.vd_rewriter);
32✔
2413
        std::string field_value;
32✔
2414

2415
        auto_mem<FILE> tmpout(fclose);
32✔
2416

2417
        tmpout = std::tmpfile();
32✔
2418
        if (!tmpout) {
32✔
2419
            log_error("unable to create temporary file");
×
2420
            return;
×
2421
        }
2422
        fcntl(fileno(tmpout), F_SETFD, FD_CLOEXEC);
32✔
2423
        auto fd_copy = auto_fd::dup_of(fileno(tmpout));
32✔
2424
        fd_copy.close_on_exec();
32✔
2425
        auto ec_out = std::make_pair(tmpout.release(), fclose);
32✔
2426
        {
2427
            exec_context::output_guard og(ec, "tmp", ec_out);
64✔
2428

2429
            auto exec_res = execute_any(ec, vd.vd_rewriter);
32✔
2430
            if (exec_res.isOk()) {
32✔
2431
                field_value = exec_res.unwrap();
32✔
2432
            } else {
2433
                field_value = exec_res.unwrapErr().to_attr_line().get_string();
×
2434
            }
2435
        }
32✔
2436
        struct stat st;
2437
        fstat(fd_copy.get(), &st);
32✔
2438
        if (st.st_size > 0) {
32✔
2439
            auto buf = auto_buffer::alloc(st.st_size);
2✔
2440

2441
            buf.resize(st.st_size);
2✔
2442
            pread(fd_copy.get(), buf.in(), st.st_size, 0);
2✔
2443
            field_value = buf.to_string();
2✔
2444
        }
2✔
2445
        value_out.erase(iter->lv_origin.lr_start, iter->lv_origin.length());
32✔
2446

2447
        int32_t shift_amount
2448
            = ((int32_t) field_value.length()) - iter->lv_origin.length();
32✔
2449
        auto orig_lr = iter->lv_origin;
32✔
2450
        value_out.insert(iter->lv_origin.lr_start, field_value);
32✔
2451
        for (auto shift_iter = values.lvv_values.begin();
32✔
2452
             shift_iter != values.lvv_values.end();
180✔
2453
             ++shift_iter)
148✔
2454
        {
2455
            shift_iter->lv_origin.shift_range(orig_lr, shift_amount);
148✔
2456
        }
2457
        shift_string_attrs(sa, orig_lr, shift_amount);
32✔
2458
    }
32✔
2459
}
2460

2461
static int
2462
read_json_field(yajlpp_parse_context* ypc,
164,048✔
2463
                const unsigned char* str,
2464
                size_t len,
2465
                yajl_string_props_t* props)
2466
{
2467
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
164,048✔
2468
    timeval tv_out;
2469
    const auto frag = string_fragment::from_bytes(str, len);
164,048✔
2470
    intern_string_t field_name;
164,048✔
2471
    const auto* vd = jlu->get_field_def(ypc);
164,048✔
2472

2473
    if (vd != nullptr) {
164,048✔
2474
        field_name = vd->vd_meta.lvm_name;
13,845✔
2475
    }
2476

2477
    if (field_name.empty()) {
164,048✔
2478
        if (!jlu->jlu_format->elf_opid_field.empty()) {
150,203✔
2479
            auto path_sf = ypc->get_path_as_string_fragment();
46,466✔
2480
            if (path_sf.startswith(jlu->jlu_format->elf_opid_field.c_str())) {
46,466✔
2481
                jlu->jlu_opid_hasher.update(path_sf);
8,985✔
2482
                jlu->jlu_opid_hasher.update(frag);
8,985✔
2483
            }
2484
        }
2485
    } else if (jlu->jlu_format->lf_timestamp_field == field_name) {
13,845✔
2486
        const auto* last = jlu->jlu_format->lf_date_time.scan(
3,115✔
2487
            (const char*) str,
2488
            len,
2489
            jlu->jlu_format->get_timestamp_formats(),
3,115✔
2490
            &jlu->jlu_exttm,
2491
            tv_out);
2492
        if (last == nullptr) {
3,115✔
2493
            auto ls = jlu->jlu_format->lf_date_time.unlock();
22✔
2494
            if ((last = jlu->jlu_format->lf_date_time.scan(
22✔
2495
                     (const char*) str,
2496
                     len,
2497
                     jlu->jlu_format->get_timestamp_formats(),
22✔
2498
                     &jlu->jlu_exttm,
2499
                     tv_out))
2500
                == nullptr)
22✔
2501
            {
2502
                jlu->jlu_format->lf_date_time.relock(ls);
×
2503
            }
2504
            if (last != nullptr) {
22✔
2505
                auto old_flags
22✔
2506
                    = jlu->jlu_format->lf_timestamp_flags & DATE_TIME_SET_FLAGS;
22✔
2507
                auto new_flags = jlu->jlu_exttm.et_flags & DATE_TIME_SET_FLAGS;
22✔
2508

2509
                // It is unlikely a valid timestamp would lose much
2510
                // precision.
2511
                if (new_flags != old_flags) {
22✔
2512
                    last = nullptr;
×
2513
                }
2514
            }
2515
        }
2516
        if (last != nullptr) {
3,115✔
2517
            jlu->jlu_format->lf_timestamp_flags = jlu->jlu_exttm.et_flags;
3,115✔
2518
            jlu->jlu_base_line->set_time(tv_out);
3,115✔
2519
        }
2520
    } else if (jlu->jlu_format->elf_level_pointer.pp_value != nullptr) {
10,730✔
2521
        if (jlu->jlu_format->elf_level_pointer.pp_value
230✔
2522
                ->find_in(field_name.to_string_fragment(), PCRE2_NO_UTF_CHECK)
230✔
2523
                .ignore_error()
230✔
2524
                .has_value())
115✔
2525
        {
2526
            jlu->jlu_base_line->set_level(
×
2527
                jlu->jlu_format->convert_level(frag, jlu->jlu_batch_context));
×
2528
        }
2529
    }
2530
    if (!field_name.empty() && jlu->jlu_format->elf_level_field == field_name) {
164,048✔
2531
        jlu->jlu_base_line->set_level(
3,375✔
2532
            jlu->jlu_format->convert_level(frag, jlu->jlu_batch_context));
3,375✔
2533
    }
2534
    if (!field_name.empty() && jlu->jlu_format->elf_opid_field == field_name) {
164,048✔
2535
        jlu->jlu_base_line->merge_bloom_bits(frag.bloom_bits());
164✔
2536

2537
        auto& sbc = *jlu->jlu_batch_context;
164✔
2538
        auto opid_iter = sbc.sbc_opids.los_opid_ranges.find(frag);
164✔
2539
        if (opid_iter == sbc.sbc_opids.los_opid_ranges.end()) {
164✔
2540
            jlu->jlu_opid_frag = frag.to_owned(sbc.sbc_allocator);
141✔
2541
        } else {
2542
            jlu->jlu_opid_frag = opid_iter->first;
23✔
2543
        }
2544
    }
2545
    if (!field_name.empty()
164,048✔
2546
        && jlu->jlu_format->elf_thread_id_field == field_name)
164,048✔
2547
    {
2548
        auto& sbc = *jlu->jlu_batch_context;
×
2549
        auto tid_iter = sbc.sbc_tids.ltis_tid_ranges.find(frag);
×
2550
        if (tid_iter == sbc.sbc_tids.ltis_tid_ranges.end()) {
×
2551
            jlu->jlu_tid_frag = frag.to_owned(sbc.sbc_allocator);
×
2552
        } else {
2553
            jlu->jlu_tid_frag = tid_iter->first;
×
2554
        }
2555
    }
2556
    if (!jlu->jlu_format->elf_subid_field.empty()
164,048✔
2557
        && jlu->jlu_format->elf_subid_field == field_name)
164,048✔
2558
    {
2559
        jlu->jlu_subid = frag.to_string();
×
2560
    }
2561
    if (!field_name.empty()
164,048✔
2562
        && jlu->jlu_format->elf_duration_field == field_name)
164,048✔
2563
    {
2564
        auto from_res = humanize::try_from<double>(frag);
×
2565
        if (from_res) {
×
2566
            jlu->jlu_duration = std::chrono::microseconds(
×
2567
                static_cast<int64_t>(from_res.value() * 1000000));
2568
        }
2569
    }
2570

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

2574
        jlu->jlu_format->lf_desc_captures.emplace(field_name, frag_copy);
42✔
2575
    }
2576

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

2579
    return 1;
164,048✔
2580
}
2581

2582
static int
2583
rewrite_json_field(yajlpp_parse_context* ypc,
69,547✔
2584
                   const unsigned char* str,
2585
                   size_t len,
2586
                   yajl_string_props_t* props)
2587
{
2588
    static const intern_string_t body_name = intern_string::lookup("body", -1);
69,547✔
2589
    auto* jlu = (json_log_userdata*) ypc->ypc_userdata;
69,547✔
2590
    intern_string_t field_name;
69,547✔
2591
    const auto* vd = jlu->get_field_def(ypc);
69,547✔
2592
    auto frag = string_fragment::from_bytes(str, len);
69,547✔
2593

2594
    if (!ypc->is_level(1) && vd == nullptr) {
69,547✔
2595
        if (!jlu->jlu_format->elf_opid_field.empty()) {
57,531✔
2596
            auto path_sf = ypc->get_path_as_string_fragment();
56,725✔
2597
            if (path_sf.startswith(jlu->jlu_format->elf_opid_field.c_str())) {
56,725✔
2598
                jlu->jlu_opid_hasher.update(path_sf);
43✔
2599
                jlu->jlu_opid_hasher.update(frag);
43✔
2600
            }
2601
        }
2602
        return 1;
57,531✔
2603
    }
2604
    if (vd != nullptr) {
12,016✔
2605
        field_name = vd->vd_meta.lvm_name;
11,456✔
2606
    } else {
2607
        field_name = ypc->get_path();
560✔
2608
    }
2609

2610
    if (jlu->jlu_format->elf_opid_field == field_name) {
12,016✔
2611
        jlu->jlu_format->jlf_line_values.lvv_opid_value = frag.to_string();
967✔
2612
        jlu->jlu_format->jlf_line_values.lvv_opid_provenance
967✔
2613
            = logline_value_vector::opid_provenance::file;
967✔
2614
    }
2615
    if (jlu->jlu_format->lf_timestamp_field == field_name) {
12,016✔
2616
        char time_buf[64];
2617

2618
        // TODO add a timeval kind to logline_value
2619
        if (jlu->jlu_line->is_time_skewed()
2,224✔
2620
            || (jlu->jlu_format->lf_timestamp_flags
4,448✔
2621
                & (ETF_MICROS_SET | ETF_NANOS_SET | ETF_ZONE_SET)))
2,224✔
2622
        {
2623
            timeval tv;
2624

2625
            const auto* last = jlu->jlu_format->lf_date_time.scan(
2,224✔
2626
                (const char*) str,
2627
                len,
2628
                jlu->jlu_format->get_timestamp_formats(),
2,224✔
2629
                &jlu->jlu_exttm,
2630
                tv);
2631
            if (last == nullptr) {
2,224✔
2632
                auto ls = jlu->jlu_format->lf_date_time.unlock();
58✔
2633
                if ((last = jlu->jlu_format->lf_date_time.scan(
58✔
2634
                         (const char*) str,
2635
                         len,
2636
                         jlu->jlu_format->get_timestamp_formats(),
58✔
2637
                         &jlu->jlu_exttm,
2638
                         tv))
2639
                    == nullptr)
58✔
2640
                {
2641
                    jlu->jlu_format->lf_date_time.relock(ls);
×
2642
                }
2643
            }
2644
            if (!jlu->jlu_subline_opts.hash_hack) {
2,224✔
2645
                if (jlu->jlu_exttm.et_flags & ETF_ZONE_SET
2,224✔
2646
                    && jlu->jlu_format->lf_date_time.dts_zoned_to_local)
2,224✔
2647
                {
2648
                    jlu->jlu_exttm.et_flags &= ~ETF_Z_IS_UTC;
2,224✔
2649
                }
2650
                jlu->jlu_exttm.et_gmtoff
2651
                    = jlu->jlu_format->lf_date_time.dts_local_offset_cache;
2,224✔
2652
            }
2653
            jlu->jlu_format->lf_date_time.ftime(
2,224✔
2654
                time_buf,
2655
                sizeof(time_buf),
2656
                jlu->jlu_format->get_timestamp_formats(),
2,224✔
2657
                jlu->jlu_exttm);
2,224✔
2658
        } else {
2659
            sql_strftime(
×
2660
                time_buf, sizeof(time_buf), jlu->jlu_line->get_timeval(), 'T');
×
2661
        }
2662
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
4,448✔
2663
            jlu->jlu_format->get_value_meta(field_name,
4,448✔
2664
                                            value_kind_t::VALUE_TEXT),
2665
            std::string{time_buf});
6,672✔
2666
    } else if (jlu->jlu_shared_buffer.contains((const char*) str)) {
9,792✔
2667
        auto str_offset = (int) ((const char*) str - jlu->jlu_line_value);
9,386✔
2668
        if (field_name == jlu->jlu_format->elf_body_field) {
9,386✔
2669
            jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
848✔
2670
                logline_value_meta(body_name,
1,696✔
2671
                                   value_kind_t::VALUE_TEXT,
2672
                                   logline_value_meta::internal_column{},
×
2673
                                   jlu->jlu_format),
848✔
2674
                string_fragment::from_byte_range(
1,696✔
2675
                    jlu->jlu_shared_buffer.get_data(),
848✔
2676
                    str_offset,
2677
                    str_offset + len));
848✔
2678
        }
2679

2680
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
9,386✔
2681
            jlu->jlu_format->get_value_meta(field_name,
18,772✔
2682
                                            value_kind_t::VALUE_TEXT),
2683
            string_fragment::from_byte_range(jlu->jlu_shared_buffer.get_data(),
18,772✔
2684
                                             str_offset,
2685
                                             str_offset + len));
9,386✔
2686
    } else {
2687
        if (field_name == jlu->jlu_format->elf_body_field) {
406✔
2688
            jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
315✔
2689
                logline_value_meta(body_name,
630✔
2690
                                   value_kind_t::VALUE_TEXT,
2691
                                   logline_value_meta::internal_column{},
×
2692
                                   jlu->jlu_format),
315✔
2693
                std::string{(const char*) str, len});
1,260✔
2694
        }
2695

2696
        jlu->jlu_format->jlf_line_values.lvv_values.emplace_back(
406✔
2697
            jlu->jlu_format->get_value_meta(ypc, vd, value_kind_t::VALUE_TEXT),
812✔
2698
            std::string{(const char*) str, len});
1,624✔
2699
    }
2700
    if (vd != nullptr && vd->vd_is_desc_field
11,456✔
2701
        && jlu->jlu_format->elf_opid_field.empty())
23,472✔
2702
    {
2703
        auto frag_copy = frag.to_owned(jlu->jlu_format->lf_desc_allocator);
62✔
2704

2705
        jlu->jlu_format->lf_desc_captures.emplace(field_name, frag_copy);
62✔
2706
    }
2707

2708
    return 1;
12,016✔
2709
}
2710

2711
void
2712
external_log_format::get_subline(const log_format_file_state& lffs,
23,811✔
2713
                                 const logline& ll,
2714
                                 shared_buffer_ref& sbr,
2715
                                 subline_options opts)
2716
{
2717
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT) {
23,811✔
2718
        return;
19,148✔
2719
    }
2720

2721
    if (this->jlf_cached_offset != ll.get_offset()
4,663✔
2722
        || this->jlf_cached_opts != opts)
4,663✔
2723
    {
2724
        auto& ypc = *(this->jlf_parse_context);
2,451✔
2725
        yajl_handle handle = this->jlf_yajl_handle.get();
2,451✔
2726
        json_log_userdata jlu(sbr, nullptr);
2,451✔
2727

2728
        jlu.jlu_subline_opts = opts;
2,451✔
2729

2730
        this->lf_desc_captures.clear();
2,451✔
2731
        this->lf_desc_allocator.reset();
2,451✔
2732
        this->jlf_share_manager.invalidate_refs();
2,451✔
2733
        this->jlf_cached_line.clear();
2,451✔
2734
        this->jlf_line_values.clear();
2,451✔
2735
        this->jlf_line_offsets.clear();
2,451✔
2736
        this->jlf_line_attrs.clear();
2,451✔
2737

2738
        auto line_frag = sbr.to_string_fragment();
2,451✔
2739

2740
        if (!line_frag.startswith("{")) {
2,451✔
2741
            this->jlf_cached_line.resize(line_frag.length());
72✔
2742
            memcpy(this->jlf_cached_line.data(),
72✔
2743
                   line_frag.data(),
72✔
2744
                   line_frag.length());
72✔
2745
            this->jlf_line_values.clear();
72✔
2746
            sbr.share(this->jlf_share_manager,
144✔
2747
                      &this->jlf_cached_line[0],
72✔
2748
                      this->jlf_cached_line.size());
2749
            this->jlf_line_values.lvv_sbr = sbr.clone();
72✔
2750
            this->jlf_line_attrs.emplace_back(
72✔
2751
                line_range{0, -1},
×
2752
                SA_INVALID.value(fmt::format(
144✔
2753
                    FMT_STRING("line at offset {} is not a JSON-line"),
144✔
2754
                    ll.get_offset())));
72✔
2755
            return;
72✔
2756
        }
2757

2758
        yajl_reset(handle);
2,379✔
2759
        ypc.set_static_handler(json_log_rewrite_handlers.jpc_children[0]);
2,379✔
2760
        ypc.ypc_userdata = &jlu;
2,379✔
2761
        ypc.ypc_ignore_unused = true;
2,379✔
2762
        ypc.ypc_alt_callbacks.yajl_start_array = json_array_start_const;
2,379✔
2763
        ypc.ypc_alt_callbacks.yajl_end_array = json_array_end;
2,379✔
2764
        ypc.ypc_alt_callbacks.yajl_start_map = json_array_start_const;
2,379✔
2765
        ypc.ypc_alt_callbacks.yajl_end_map = json_array_end;
2,379✔
2766
        jlu.jlu_format = this;
2,379✔
2767
        jlu.jlu_line = &ll;
2,379✔
2768
        jlu.jlu_handle = handle;
2,379✔
2769
        jlu.jlu_line_value = sbr.get_data();
2,379✔
2770
        jlu.jlu_format_hits.resize(this->jlf_line_format.size());
2,379✔
2771

2772
        yajl_status parse_status = yajl_parse(
4,758✔
2773
            handle, (const unsigned char*) sbr.get_data(), sbr.length());
2,379✔
2774
        if (parse_status != yajl_status_ok
2,379✔
2775
            || yajl_complete_parse(handle) != yajl_status_ok)
2,379✔
2776
        {
2777
            unsigned char* msg;
2778
            std::string full_msg;
14✔
2779

2780
            msg = yajl_get_error(
28✔
2781
                handle, 1, (const unsigned char*) sbr.get_data(), sbr.length());
14✔
2782
            if (msg != nullptr) {
14✔
2783
                full_msg = fmt::format(
14✔
2784
                    FMT_STRING("[offset: {}] {}\n{}"),
28✔
2785
                    ll.get_offset(),
14✔
2786
                    fmt::string_view{sbr.get_data(), sbr.length()},
14✔
2787
                    reinterpret_cast<char*>(msg));
28✔
2788
                yajl_free_error(handle, msg);
14✔
2789
            }
2790

2791
            this->jlf_cached_line.resize(full_msg.size());
14✔
2792
            memcpy(
14✔
2793
                this->jlf_cached_line.data(), full_msg.data(), full_msg.size());
14✔
2794
            this->jlf_line_values.clear();
14✔
2795
            this->jlf_line_attrs.emplace_back(
14✔
2796
                line_range{0, -1},
×
2797
                SA_INVALID.value("JSON line failed to parse"));
28✔
2798
        } else {
14✔
2799
            std::vector<logline_value>::iterator lv_iter;
2,365✔
2800
            bool used_values[this->jlf_line_values.lvv_values.size()];
4,730✔
2801
            struct line_range lr;
2,365✔
2802

2803
            memset(used_values, 0, sizeof(used_values));
2,365✔
2804
            for (lv_iter = this->jlf_line_values.lvv_values.begin();
2,365✔
2805
                 lv_iter != this->jlf_line_values.lvv_values.end();
21,142✔
2806
                 ++lv_iter)
18,777✔
2807
            {
2808
                lv_iter->lv_meta.lvm_format = this;
18,777✔
2809
            }
2810

2811
            if (jlu.jlu_tid_number) {
2,365✔
2812
                this->jlf_line_values.lvv_thread_id_value
2813
                    = fmt::to_string(jlu.jlu_tid_number.value());
142✔
2814
            } else if (jlu.jlu_tid_frag) {
2,223✔
2815
                this->jlf_line_values.lvv_thread_id_value
2816
                    = jlu.jlu_tid_frag->to_string();
×
2817
            }
2818

2819
            if (this->elf_opid_field.empty()
2,365✔
2820
                && this->lf_opid_source.value_or(
1,358✔
2821
                       opid_source_t::from_description)
1,358✔
2822
                    == opid_source_t::from_description
2823
                && this->lf_opid_description_def->size() == 1)
3,723✔
2824
            {
2825
                auto found_opid_desc = false;
217✔
2826
                const auto& od = this->lf_opid_description_def->begin()->second;
217✔
2827
                for (const auto& desc : *od.od_descriptors) {
651✔
2828
                    auto desc_iter
2829
                        = this->lf_desc_captures.find(desc.od_field.pp_value);
434✔
2830
                    if (desc_iter == this->lf_desc_captures.end()) {
434✔
2831
                        continue;
372✔
2832
                    }
2833
                    found_opid_desc = true;
62✔
2834
                    jlu.jlu_opid_hasher.update(desc_iter->second);
62✔
2835
                }
2836
                if (found_opid_desc) {
217✔
2837
                    this->jlf_line_values.lvv_opid_value
2838
                        = jlu.jlu_opid_hasher.to_string();
31✔
2839
                    this->jlf_line_values.lvv_opid_provenance
2840
                        = logline_value_vector::opid_provenance::file;
31✔
2841
                }
2842
            } else if (!jlu.jlu_opid_desc_frag && !jlu.jlu_opid_frag
4,268✔
2843
                       && jlu.jlu_duration > 0us)
4,268✔
2844
            {
2845
                jlu.jlu_opid_hasher.update(line_frag);
×
2846
                this->jlf_line_values.lvv_opid_value
2847
                    = jlu.jlu_opid_hasher.to_string();
×
2848
                this->jlf_line_values.lvv_opid_provenance
2849
                    = logline_value_vector::opid_provenance::file;
×
2850
            }
2851
            if (jlu.jlu_opid_desc_frag) {
2,365✔
2852
                this->jlf_line_values.lvv_opid_value
2853
                    = jlu.jlu_opid_hasher.to_string();
28✔
2854
                this->jlf_line_values.lvv_opid_provenance
2855
                    = logline_value_vector::opid_provenance::file;
28✔
2856
            }
2857
            if (jlu.jlu_opid_frag) {
2,365✔
2858
                this->jlf_line_values.lvv_opid_value
2859
                    = jlu.jlu_opid_frag->to_string();
×
2860
                this->jlf_line_values.lvv_opid_provenance
2861
                    = logline_value_vector::opid_provenance::file;
×
2862
            }
2863

2864
            int sub_offset = this->jlf_line_format_init_count;
2,365✔
2865
            for (const auto& jfe : this->jlf_line_format) {
30,622✔
2866
                static const intern_string_t ts_field
2867
                    = intern_string::lookup("__timestamp__", -1);
28,257✔
2868
                static const intern_string_t level_field
2869
                    = intern_string::lookup("__level__");
28,351✔
2870
                size_t begin_size = this->jlf_cached_line.size();
28,257✔
2871

2872
                switch (jfe.jfe_type) {
28,257✔
2873
                    case json_log_field::CONSTANT:
3,823✔
2874
                        this->json_append_to_cache(
3,823✔
2875
                            jfe.jfe_default_value.c_str(),
2876
                            jfe.jfe_default_value.size());
3,823✔
2877
                        break;
3,823✔
2878
                    case json_log_field::VARIABLE:
24,434✔
2879
                        lv_iter = find_if(
24,434✔
2880
                            this->jlf_line_values.lvv_values.begin(),
2881
                            this->jlf_line_values.lvv_values.end(),
2882
                            logline_value_name_cmp(&jfe.jfe_value.pp_value));
2883
                        if (lv_iter != this->jlf_line_values.lvv_values.end()) {
24,434✔
2884
                            auto str = lv_iter->to_string();
8,733✔
2885
                            value_def* vd = nullptr;
8,733✔
2886

2887
                            if (lv_iter->lv_meta.lvm_values_index) {
8,733✔
2888
                                vd = this->elf_value_def_order
2889
                                         [lv_iter->lv_meta.lvm_values_index
8,733✔
2890
                                              .value()]
8,733✔
2891
                                             .get();
8,733✔
2892
                            }
2893
                            while (endswith(str, "\n")) {
8,995✔
2894
                                str.pop_back();
262✔
2895
                            }
2896
                            size_t nl_pos = str.find('\n');
8,733✔
2897

2898
                            if (!jfe.jfe_prefix.empty()) {
8,733✔
2899
                                this->json_append_to_cache(jfe.jfe_prefix);
4,994✔
2900
                            }
2901
                            lr.lr_start = this->jlf_cached_line.size();
8,733✔
2902

2903
                            if ((int) str.size() > jfe.jfe_max_width) {
8,733✔
2904
                                switch (jfe.jfe_overflow) {
233✔
2905
                                    case json_format_element::overflow_t::
165✔
2906
                                        ABBREV: {
2907
                                        size_t new_size
2908
                                            = abbreviate_str(&str[0],
165✔
2909
                                                             str.size(),
2910
                                                             jfe.jfe_max_width);
165✔
2911
                                        str.resize(new_size);
165✔
2912
                                        this->json_append(lffs, jfe, vd, str);
165✔
2913
                                        break;
165✔
2914
                                    }
2915
                                    case json_format_element::overflow_t::
62✔
2916
                                        TRUNCATE: {
2917
                                        this->json_append_to_cache(
62✔
2918
                                            str.c_str(), jfe.jfe_max_width);
62✔
2919
                                        break;
62✔
2920
                                    }
2921
                                    case json_format_element::overflow_t::
6✔
2922
                                        DOTDOT: {
2923
                                        size_t middle
6✔
2924
                                            = (jfe.jfe_max_width / 2) - 1;
6✔
2925
                                        this->json_append_to_cache(str.c_str(),
6✔
2926
                                                                   middle);
2927
                                        this->json_append_to_cache("..", 2);
6✔
2928
                                        size_t rest
6✔
2929
                                            = (jfe.jfe_max_width - middle - 2);
6✔
2930
                                        this->json_append_to_cache(
12✔
2931
                                            str.c_str() + str.size() - rest,
6✔
2932
                                            rest);
2933
                                        break;
6✔
2934
                                    }
2935
                                    case json_format_element::overflow_t::
×
2936
                                        LASTWORD: {
2937
                                        size_t new_size
2938
                                            = last_word_str(&str[0],
×
2939
                                                            str.size(),
2940
                                                            jfe.jfe_max_width);
×
2941
                                        str.resize(new_size);
×
2942
                                        this->json_append(lffs, jfe, vd, str);
×
2943
                                        break;
×
2944
                                    }
2945
                                }
2946
                            } else {
2947
                                sub_offset
2948
                                    += std::count(str.begin(), str.end(), '\n');
8,500✔
2949
                                this->json_append(lffs, jfe, vd, str);
8,500✔
2950
                            }
2951

2952
                            if (nl_pos == std::string::npos
8,733✔
2953
                                || opts.full_message)
3✔
2954
                            {
2955
                                lr.lr_end = this->jlf_cached_line.size();
8,730✔
2956
                            } else {
2957
                                lr.lr_end = lr.lr_start + nl_pos;
3✔
2958
                            }
2959

2960
                            if (lv_iter->lv_meta.lvm_name
8,733✔
2961
                                == this->lf_timestamp_field)
8,733✔
2962
                            {
2963
                                this->jlf_line_attrs.emplace_back(
1,003✔
2964
                                    lr, L_TIMESTAMP.value());
2,006✔
2965
                            } else if (lv_iter->lv_meta.lvm_name
7,730✔
2966
                                       == this->elf_body_field)
7,730✔
2967
                            {
2968
                                this->jlf_line_attrs.emplace_back(
1,163✔
2969
                                    lr, SA_BODY.value());
2,326✔
2970
                            } else if (lv_iter->lv_meta.lvm_name
6,567✔
2971
                                       == this->elf_src_file_field)
6,567✔
2972
                            {
2973
                                this->jlf_line_attrs.emplace_back(
11✔
2974
                                    lr, SA_SRC_FILE.value());
22✔
2975
                            } else if (lv_iter->lv_meta.lvm_name
6,556✔
2976
                                       == this->elf_src_line_field)
6,556✔
2977
                            {
2978
                                this->jlf_line_attrs.emplace_back(
11✔
2979
                                    lr, SA_SRC_LINE.value());
22✔
2980
                            } else if (lv_iter->lv_meta.lvm_name
6,545✔
2981
                                       == this->elf_thread_id_field)
6,545✔
2982
                            {
2983
                                this->jlf_line_attrs.emplace_back(
88✔
2984
                                    lr, SA_THREAD_ID.value());
176✔
2985
                            } else if (lv_iter->lv_meta.lvm_name
6,457✔
2986
                                       == this->elf_duration_field)
6,457✔
2987
                            {
2988
                                this->jlf_line_attrs.emplace_back(
×
2989
                                    lr, SA_DURATION.value());
×
2990
                            } else if (lv_iter->lv_meta.lvm_name
6,457✔
2991
                                       == this->elf_level_field)
6,457✔
2992
                            {
2993
                                this->jlf_line_attrs.emplace_back(
1,077✔
2994
                                    lr, L_LEVEL.value());
2,154✔
2995
                            } else if (lv_iter->lv_meta.lvm_name
10,760✔
2996
                                           == this->elf_opid_field
5,380✔
2997
                                       && !lr.empty())
5,380✔
2998
                            {
2999
                                this->jlf_line_attrs.emplace_back(
967✔
3000
                                    lr, L_OPID.value());
1,934✔
3001
                            }
3002
                            lv_iter->lv_origin = lr;
8,733✔
3003
                            lv_iter->lv_sub_offset = sub_offset;
8,733✔
3004
                            used_values[std::distance(
8,733✔
3005
                                this->jlf_line_values.lvv_values.begin(),
3006
                                lv_iter)]
3007
                                = true;
8,733✔
3008

3009
                            if (!jfe.jfe_suffix.empty()) {
8,733✔
3010
                                this->json_append_to_cache(jfe.jfe_suffix);
1,325✔
3011
                            }
3012
                        } else if (jfe.jfe_value.pp_value == ts_field) {
24,434✔
3013
                            line_range lr;
1,507✔
3014
                            ssize_t ts_len;
3015
                            char ts[64];
3016
                            exttm et;
1,507✔
3017

3018
                            ll.to_exttm(et);
1,507✔
3019
                            et.et_nsec += jlu.jlu_exttm.et_nsec % 1000;
1,507✔
3020
                            et.et_gmtoff = jlu.jlu_exttm.et_gmtoff;
1,507✔
3021
                            et.et_flags |= jlu.jlu_exttm.et_flags;
1,507✔
3022
                            if (!jfe.jfe_prefix.empty()) {
1,507✔
3023
                                this->json_append_to_cache(jfe.jfe_prefix);
3✔
3024
                            }
3025
                            if (jfe.jfe_ts_format.empty()) {
1,507✔
3026
                                ts_len = this->lf_date_time.ftime(
1,348✔
3027
                                    ts,
3028
                                    sizeof(ts),
3029
                                    this->get_timestamp_formats(),
3030
                                    et);
3031
                            } else {
3032
                                ts_len = ftime_fmt(ts,
159✔
3033
                                                   sizeof(ts),
3034
                                                   jfe.jfe_ts_format.c_str(),
3035
                                                   et);
3036
                            }
3037
                            lr.lr_start = this->jlf_cached_line.size();
1,507✔
3038
                            this->json_append_to_cache(ts, ts_len);
1,507✔
3039
                            lr.lr_end = this->jlf_cached_line.size();
1,507✔
3040
                            this->jlf_line_attrs.emplace_back(
1,507✔
3041
                                lr, L_TIMESTAMP.value());
3,014✔
3042

3043
                            lv_iter = find_if(
1,507✔
3044
                                this->jlf_line_values.lvv_values.begin(),
3045
                                this->jlf_line_values.lvv_values.end(),
3046
                                logline_value_name_cmp(
3047
                                    &this->lf_timestamp_field));
1,507✔
3048
                            if (lv_iter
1,507✔
3049
                                != this->jlf_line_values.lvv_values.end())
1,507✔
3050
                            {
3051
                                used_values[distance(
1,507✔
3052
                                    this->jlf_line_values.lvv_values.begin(),
3053
                                    lv_iter)]
3054
                                    = true;
1,507✔
3055
                            }
3056
                            if (!jfe.jfe_suffix.empty()) {
1,507✔
3057
                                this->json_append_to_cache(jfe.jfe_suffix);
3✔
3058
                            }
3059
                        } else if (jfe.jfe_value.pp_value == level_field
14,194✔
3060
                                   || jfe.jfe_value.pp_value
28,266✔
3061
                                       == this->elf_level_field)
14,072✔
3062
                        {
3063
                            auto level_name = ll.get_level_name();
122✔
3064
                            lr.lr_start = this->jlf_cached_line.size();
122✔
3065
                            this->json_append(lffs, jfe, nullptr, level_name);
122✔
3066
                            if (jfe.jfe_auto_width) {
122✔
3067
                                this->json_append_to_cache(
88✔
3068
                                    MAX_LEVEL_NAME_LEN - level_name.length());
88✔
3069
                            }
3070
                            lr.lr_end = this->jlf_cached_line.size();
122✔
3071
                            this->jlf_line_attrs.emplace_back(lr,
122✔
3072
                                                              L_LEVEL.value());
244✔
3073
                        } else if (!jfe.jfe_default_value.empty()) {
14,072✔
3074
                            if (!jfe.jfe_prefix.empty()) {
124✔
3075
                                this->json_append_to_cache(jfe.jfe_prefix);
×
3076
                            }
3077
                            this->json_append(
124✔
3078
                                lffs, jfe, nullptr, jfe.jfe_default_value);
124✔
3079
                            if (!jfe.jfe_suffix.empty()) {
124✔
3080
                                this->json_append_to_cache(jfe.jfe_suffix);
×
3081
                            }
3082
                        }
3083

3084
                        switch (jfe.jfe_text_transform) {
24,434✔
3085
                            case json_format_element::transform_t::NONE:
24,312✔
3086
                                break;
24,312✔
3087
                            case json_format_element::transform_t::UPPERCASE:
122✔
3088
                                for (size_t cindex = begin_size;
122✔
3089
                                     cindex < this->jlf_cached_line.size();
965✔
3090
                                     cindex++)
3091
                                {
3092
                                    this->jlf_cached_line[cindex] = toupper(
843✔
3093
                                        this->jlf_cached_line[cindex]);
843✔
3094
                                }
3095
                                break;
122✔
3096
                            case json_format_element::transform_t::LOWERCASE:
×
3097
                                for (size_t cindex = begin_size;
×
3098
                                     cindex < this->jlf_cached_line.size();
×
3099
                                     cindex++)
3100
                                {
3101
                                    this->jlf_cached_line[cindex] = tolower(
×
3102
                                        this->jlf_cached_line[cindex]);
×
3103
                                }
3104
                                break;
×
3105
                            case json_format_element::transform_t::CAPITALIZE:
×
3106
                                for (size_t cindex = begin_size;
×
3107
                                     cindex < begin_size + 1;
×
3108
                                     cindex++)
3109
                                {
3110
                                    this->jlf_cached_line[cindex] = toupper(
×
3111
                                        this->jlf_cached_line[cindex]);
×
3112
                                }
3113
                                for (size_t cindex = begin_size + 1;
×
3114
                                     cindex < this->jlf_cached_line.size();
×
3115
                                     cindex++)
3116
                                {
3117
                                    this->jlf_cached_line[cindex] = tolower(
×
3118
                                        this->jlf_cached_line[cindex]);
×
3119
                                }
3120
                                break;
×
3121
                        }
3122
                        break;
24,434✔
3123
                }
3124
            }
3125
            this->json_append_to_cache("\n", 1);
2,365✔
3126
            sub_offset += 1;
2,365✔
3127

3128
            for (size_t lpc = 0; lpc < this->jlf_line_values.lvv_values.size();
21,142✔
3129
                 lpc++)
3130
            {
3131
                static const intern_string_t body_name
3132
                    = intern_string::lookup("body", -1);
18,777✔
3133
                auto& lv = this->jlf_line_values.lvv_values[lpc];
18,777✔
3134

3135
                if (lv.lv_meta.is_hidden() || used_values[lpc]
28,822✔
3136
                    || body_name == lv.lv_meta.lvm_name)
28,822✔
3137
                {
3138
                    continue;
17,609✔
3139
                }
3140

3141
                auto str = lv.to_string();
1,168✔
3142
                while (endswith(str, "\n")) {
1,168✔
3143
                    str.pop_back();
×
3144
                }
3145

3146
                lv.lv_sub_offset = sub_offset;
1,168✔
3147
                lv.lv_origin.lr_start = this->jlf_cached_line.size() + 2
1,168✔
3148
                    + lv.lv_meta.lvm_name.size() + 2;
1,168✔
3149
                auto frag = string_fragment::from_str(str);
1,168✔
3150
                while (true) {
3151
                    auto utf_scan_res = is_utf8(frag, '\n');
1,174✔
3152

3153
                    this->json_append_to_cache("  ", 2);
1,174✔
3154
                    this->json_append_to_cache(
1,174✔
3155
                        lv.lv_meta.lvm_name.to_string_fragment());
1,174✔
3156
                    this->json_append_to_cache(": ", 2);
1,174✔
3157
                    lr.lr_start = this->jlf_cached_line.size();
1,174✔
3158
                    this->json_append_to_cache(utf_scan_res.usr_valid_frag);
1,174✔
3159
                    lr.lr_end = this->jlf_cached_line.size();
1,174✔
3160
                    if (lv.lv_meta.lvm_name == this->elf_body_field) {
1,174✔
3161
                        this->jlf_line_attrs.emplace_back(lr, SA_BODY.value());
×
3162
                    } else {
3163
                        this->jlf_line_attrs.emplace_back(
1,174✔
3164
                            lr, SA_EXTRA_CONTENT.value());
2,348✔
3165
                    }
3166
                    this->json_append_to_cache("\n", 1);
1,174✔
3167
                    sub_offset += 1;
1,174✔
3168
                    if (utf_scan_res.usr_remaining) {
1,174✔
3169
                        frag = utf_scan_res.usr_remaining.value();
6✔
3170
                    } else {
3171
                        break;
1,168✔
3172
                    }
3173
                }
6✔
3174
                lv.lv_origin.lr_end = this->jlf_cached_line.size() - 1;
1,168✔
3175
                if (lv.lv_meta.lvm_name == this->elf_opid_field
1,168✔
3176
                    && !lv.lv_origin.empty())
1,168✔
3177
                {
3178
                    this->jlf_line_attrs.emplace_back(lv.lv_origin,
×
3179
                                                      L_OPID.value());
×
3180
                }
3181
            }
1,168✔
3182
        }
2,365✔
3183

3184
        this->jlf_line_offsets.push_back(0);
2,379✔
3185
        for (size_t lpc = 0; lpc < this->jlf_cached_line.size(); lpc++) {
269,189✔
3186
            if (this->jlf_cached_line[lpc] == '\n') {
266,810✔
3187
                this->jlf_line_offsets.push_back(lpc + 1);
4,333✔
3188
            }
3189
        }
3190
        this->jlf_line_offsets.push_back(this->jlf_cached_line.size());
2,379✔
3191
        this->jlf_cached_offset = ll.get_offset();
2,379✔
3192
        this->jlf_cached_opts = opts;
2,379✔
3193
    }
2,451✔
3194

3195
    off_t this_off = 0, next_off = 0;
4,591✔
3196

3197
    if (!this->jlf_line_offsets.empty()
4,591✔
3198
        && ll.get_sub_offset() < this->jlf_line_offsets.size())
4,591✔
3199
    {
3200
        require(ll.get_sub_offset() < this->jlf_line_offsets.size());
4,591✔
3201

3202
        this_off = this->jlf_line_offsets[ll.get_sub_offset()];
4,591✔
3203
        if ((ll.get_sub_offset() + 1) < (int) this->jlf_line_offsets.size()) {
4,591✔
3204
            next_off = this->jlf_line_offsets[ll.get_sub_offset() + 1];
4,591✔
3205
        } else {
3206
            next_off = this->jlf_cached_line.size();
×
3207
        }
3208
        if (next_off > 0 && this->jlf_cached_line[next_off - 1] == '\n'
4,591✔
3209
            && this_off != next_off)
9,182✔
3210
        {
3211
            next_off -= 1;
4,591✔
3212
        }
3213
    }
3214

3215
    if (opts.full_message) {
4,591✔
3216
        sbr.share(this->jlf_share_manager,
644✔
3217
                  &this->jlf_cached_line[0],
322✔
3218
                  this->jlf_cached_line.size());
3219
    } else {
3220
        sbr.share(this->jlf_share_manager,
8,538✔
3221
                  this->jlf_cached_line.data() + this_off,
4,269✔
3222
                  next_off - this_off);
4,269✔
3223
    }
3224
    sbr.get_metadata().m_valid_utf = ll.is_valid_utf();
4,591✔
3225
    sbr.get_metadata().m_has_ansi = ll.has_ansi();
4,591✔
3226
    this->jlf_cached_sub_range.lr_start = this_off;
4,591✔
3227
    this->jlf_cached_sub_range.lr_end = next_off;
4,591✔
3228
    this->jlf_line_values.lvv_sbr = sbr.clone();
4,591✔
3229
}
3230

3231
struct compiled_header_expr {
3232
    auto_mem<sqlite3_stmt> che_stmt{sqlite3_finalize};
3233
    bool che_enabled{true};
3234
};
3235

3236
struct format_header_expressions : public lnav_config_listener {
3237
    format_header_expressions() : lnav_config_listener(__FILE__) {}
1,167✔
3238

3239
    auto_sqlite3 e_db;
3240
    std::map<intern_string_t, std::map<std::string, compiled_header_expr>>
3241
        e_header_exprs;
3242
};
3243

3244
using safe_format_header_expressions = safe::Safe<format_header_expressions>;
3245

3246
static safe_format_header_expressions format_header_exprs;
3247

3248
std::optional<external_file_format>
3249
detect_mime_type(const std::filesystem::path& filename)
613✔
3250
{
3251
    uint8_t buffer[1024];
3252
    size_t buffer_size = 0;
613✔
3253

3254
    {
3255
        auto_fd fd;
613✔
3256

3257
        if ((fd = lnav::filesystem::openp(filename, O_RDONLY)) == -1) {
613✔
3258
            return std::nullopt;
×
3259
        }
3260

3261
        ssize_t rc;
3262

3263
        if ((rc = read(fd, buffer, sizeof(buffer))) == -1) {
613✔
3264
            return std::nullopt;
×
3265
        }
3266
        buffer_size = rc;
613✔
3267
    }
613✔
3268

3269
    auto hexbuf = auto_buffer::alloc(buffer_size * 2);
613✔
3270

3271
    for (size_t lpc = 0; lpc < buffer_size; lpc++) {
328,815✔
3272
        fmt::format_to(
328,202✔
3273
            std::back_inserter(hexbuf), FMT_STRING("{:02x}"), buffer[lpc]);
1,312,808✔
3274
    }
3275

3276
    safe::WriteAccess<safe_format_header_expressions> in(format_header_exprs);
613✔
3277

3278
    for (const auto& format : log_format::get_root_formats()) {
45,868✔
3279
        auto elf = std::dynamic_pointer_cast<external_log_format>(format);
45,255✔
3280
        if (elf == nullptr) {
45,255✔
3281
            continue;
3,065✔
3282
        }
3283

3284
        if (elf->elf_converter.c_header.h_exprs.he_exprs.empty()) {
42,190✔
3285
            continue;
41,577✔
3286
        }
3287

3288
        if (buffer_size < elf->elf_converter.c_header.h_size) {
613✔
3289
            log_debug(
21✔
3290
                "%s: file content too small (%zu) for header detection: %s",
3291
                filename.c_str(),
3292
                buffer_size,
3293
                elf->get_name().get());
3294
            continue;
21✔
3295
        }
3296
        for (const auto& hpair : elf->elf_converter.c_header.h_exprs.he_exprs) {
2,960✔
3297
            auto& he = in->e_header_exprs[elf->get_name()][hpair.first];
2,368✔
3298

3299
            if (!he.che_enabled) {
2,368✔
3300
                continue;
×
3301
            }
3302

3303
            auto* stmt = he.che_stmt.in();
2,368✔
3304

3305
            if (stmt == nullptr) {
2,368✔
3306
                continue;
×
3307
            }
3308
            sqlite3_reset(stmt);
2,368✔
3309
            auto count = sqlite3_bind_parameter_count(stmt);
2,368✔
3310
            for (int lpc = 0; lpc < count; lpc++) {
4,736✔
3311
                const auto* name = sqlite3_bind_parameter_name(stmt, lpc + 1);
2,368✔
3312

3313
                if (name[0] == '$') {
2,368✔
3314
                    const char* env_value;
3315

3316
                    if ((env_value = getenv(&name[1])) != nullptr) {
×
3317
                        sqlite3_bind_text(
×
3318
                            stmt, lpc + 1, env_value, -1, SQLITE_STATIC);
3319
                    }
3320
                    continue;
×
3321
                }
3322
                if (strcmp(name, ":header") == 0) {
2,368✔
3323
                    sqlite3_bind_text(stmt,
2,368✔
3324
                                      lpc + 1,
3325
                                      hexbuf.in(),
2,368✔
3326
                                      hexbuf.size(),
2,368✔
3327
                                      SQLITE_STATIC);
3328
                    continue;
2,368✔
3329
                }
3330
                if (strcmp(name, ":filepath") == 0) {
×
3331
                    sqlite3_bind_text(
×
3332
                        stmt, lpc + 1, filename.c_str(), -1, SQLITE_STATIC);
3333
                    continue;
×
3334
                }
3335
            }
3336

3337
            auto step_res = sqlite3_step(stmt);
2,368✔
3338

3339
            switch (step_res) {
2,368✔
3340
                case SQLITE_OK:
2,368✔
3341
                case SQLITE_DONE:
3342
                    continue;
2,368✔
3343
                case SQLITE_ROW:
×
3344
                    break;
×
3345
                default: {
×
3346
                    log_error(
×
3347
                        "failed to execute file-format header expression: "
3348
                        "%s:%s -- %s",
3349
                        elf->get_name().get(),
3350
                        hpair.first.c_str(),
3351
                        sqlite3_errmsg(in->e_db));
3352
                    he.che_enabled = false;
×
3353
                    continue;
×
3354
                }
3355
            }
3356

3357
            log_info("detected format for: %s -- %s (header-expr: %s)",
×
3358
                     filename.c_str(),
3359
                     elf->get_name().get(),
3360
                     hpair.first.c_str());
3361
            return external_file_format{
×
3362
                elf->get_name().to_string(),
×
3363
                elf->elf_converter.c_command.pp_value,
×
3364
                elf->elf_converter.c_command.pp_location.sl_source.to_string(),
×
3365
            };
3366
        }
3367
    }
45,255✔
3368

3369
    return std::nullopt;
613✔
3370
}
613✔
3371

3372
log_format::scan_result_t
3373
log_format::test_line(sample_t& sample,
×
3374
                      std::vector<lnav::console::user_message>& msgs)
3375
{
3376
    return scan_no_match{};
×
3377
}
3378

3379
log_format::scan_result_t
3380
external_log_format::test_line(sample_t& sample,
184,544✔
3381
                               std::vector<lnav::console::user_message>& msgs)
3382
{
3383
    auto lines
3384
        = string_fragment::from_str(sample.s_line.pp_value).split_lines();
184,544✔
3385

3386
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
184,544✔
3387
        auto alloc = ArenaAlloc::Alloc<char>{};
2,243✔
3388
        pattern_locks pats;
2,243✔
3389
        auto sbc = scan_batch_context{
2,243✔
3390
            alloc,
3391
            pats,
3392
        };
2,243✔
3393
        sbc.sbc_value_stats.resize(this->elf_value_defs.size());
2,243✔
3394
        std::vector<logline> dst;
2,243✔
3395
        auto li = line_info{
2,243✔
3396
            {0, lines[0].length()},
2,243✔
3397
        };
2,243✔
3398
        shared_buffer sb;
2,243✔
3399
        shared_buffer_ref sbr;
2,243✔
3400
        sbr.share(sb, lines[0].data(), (size_t) lines[0].length());
2,243✔
3401

3402
        return this->scan_json(dst, li, sbr, sbc);
2,243✔
3403
    }
2,243✔
3404

3405
    scan_result_t retval = scan_no_match{"no patterns matched"};
182,301✔
3406
    auto found = false;
182,301✔
3407

3408
    for (auto pat_iter = this->elf_pattern_order.begin();
182,301✔
3409
         pat_iter != this->elf_pattern_order.end();
1,371,768✔
3410
         ++pat_iter)
1,189,467✔
3411
    {
3412
        auto& pat = *(*pat_iter);
1,189,467✔
3413

3414
        if (!pat.p_pcre.pp_value) {
1,189,467✔
3415
            continue;
1,007,168✔
3416
        }
3417

3418
        auto md = pat.p_pcre.pp_value->create_match_data();
1,189,467✔
3419
        auto match_res = pat.p_pcre.pp_value->capture_from(lines[0])
1,189,467✔
3420
                             .into(md)
1,189,467✔
3421
                             .matches(PCRE2_NO_UTF_CHECK)
2,378,934✔
3422
                             .ignore_error();
1,189,467✔
3423
        if (!match_res) {
1,189,467✔
3424
            continue;
1,007,168✔
3425
        }
3426
        retval = scan_match{1000};
182,299✔
3427
        found = true;
182,299✔
3428

3429
        sample.s_matched_regexes.insert(pat.p_name.to_string());
182,299✔
3430

3431
        const auto ts_cap = md[pat.p_timestamp_field_index];
182,299✔
3432
        const auto level_cap = md[pat.p_level_field_index];
182,299✔
3433
        const char* const* custom_formats = this->get_timestamp_formats();
182,299✔
3434
        date_time_scanner dts;
182,299✔
3435
        timeval tv;
3436
        exttm tm;
182,299✔
3437

3438
        if (ts_cap && ts_cap->sf_begin == 0) {
182,299✔
3439
            pat.p_timestamp_end = ts_cap->sf_end;
111,692✔
3440
        }
3441
        const char* dts_scan_res = nullptr;
182,299✔
3442

3443
        if (ts_cap) {
182,299✔
3444
            dts_scan_res = dts.scan(
182,297✔
3445
                ts_cap->data(), ts_cap->length(), custom_formats, &tm, tv);
182,297✔
3446
        }
3447
        if (dts_scan_res != nullptr) {
182,299✔
3448
            if (dts_scan_res != ts_cap->data() + ts_cap->length()) {
182,296✔
3449
                auto match_len = dts_scan_res - ts_cap->data();
×
3450
                auto notes = attr_line_t("the used timestamp format: ");
×
3451
                if (custom_formats == nullptr) {
×
3452
                    notes.append(PTIMEC_FORMATS[dts.dts_fmt_lock].pf_fmt);
×
3453
                } else {
3454
                    notes.append(custom_formats[dts.dts_fmt_lock]);
×
3455
                }
3456
                notes.append("\n  ")
×
3457
                    .append(ts_cap.value())
×
3458
                    .append("\n")
×
3459
                    .append(2 + match_len, ' ')
×
3460
                    .append("^ matched up to here"_snippet_border);
×
3461
                auto um = lnav::console::user_message::warning(
×
3462
                              attr_line_t("timestamp was not fully matched: ")
×
3463
                                  .append_quoted(ts_cap.value()))
×
3464
                              .with_snippet(sample.s_line.to_snippet())
×
3465
                              .with_note(notes)
×
3466
                              .move();
×
3467

3468
                msgs.emplace_back(um);
×
3469
            }
3470
        } else if (!ts_cap) {
3✔
3471
            msgs.emplace_back(
2✔
3472
                lnav::console::user_message::error(
×
3473
                    attr_line_t("invalid sample log message: ")
4✔
3474
                        .append(lnav::to_json(sample.s_line.pp_value)))
4✔
3475
                    .with_reason(attr_line_t("timestamp was not captured"))
4✔
3476
                    .with_snippet(sample.s_line.to_snippet())
4✔
3477
                    .with_help(attr_line_t(
4✔
3478
                        "A timestamp needs to be captured in order for a "
3479
                        "line to be recognized as a log message")));
3480
        } else {
3481
            attr_line_t notes;
1✔
3482

3483
            if (custom_formats == nullptr) {
1✔
3484
                notes.append("the following built-in formats were tried:");
×
3485
                for (int lpc = 0; PTIMEC_FORMATS[lpc].pf_fmt != nullptr; lpc++)
×
3486
                {
3487
                    off_t off = 0;
×
3488

3489
                    PTIMEC_FORMATS[lpc].pf_func(
×
3490
                        &tm, ts_cap->data(), off, ts_cap->length());
×
3491
                    notes.append("\n  ")
×
3492
                        .append(ts_cap.value())
×
3493
                        .append("\n")
×
3494
                        .append(2 + off, ' ')
×
3495
                        .append("^ "_snippet_border)
×
3496
                        .append_quoted(
×
3497
                            lnav::roles::symbol(PTIMEC_FORMATS[lpc].pf_fmt))
×
3498
                        .append(" matched up to here"_snippet_border);
×
3499
                }
3500
            } else {
3501
                notes.append("the following custom formats were tried:");
1✔
3502
                for (int lpc = 0; custom_formats[lpc] != nullptr; lpc++) {
2✔
3503
                    off_t off = 0;
1✔
3504

3505
                    ptime_fmt(custom_formats[lpc],
1✔
3506
                              &tm,
3507
                              ts_cap->data(),
3508
                              off,
3509
                              ts_cap->length());
1✔
3510
                    notes.append("\n  ")
1✔
3511
                        .append(ts_cap.value())
1✔
3512
                        .append("\n")
1✔
3513
                        .append(2 + off, ' ')
1✔
3514
                        .append("^ "_snippet_border)
1✔
3515
                        .append_quoted(lnav::roles::symbol(custom_formats[lpc]))
2✔
3516
                        .append(" matched up to here"_snippet_border);
1✔
3517
                }
3518
            }
3519

3520
            msgs.emplace_back(
1✔
3521
                lnav::console::user_message::error(
×
3522
                    attr_line_t("invalid sample log message: ")
1✔
3523
                        .append(lnav::to_json(sample.s_line.pp_value)))
2✔
3524
                    .with_reason(attr_line_t("unrecognized timestamp -- ")
2✔
3525
                                     .append(ts_cap.value()))
1✔
3526
                    .with_snippet(sample.s_line.to_snippet())
2✔
3527
                    .with_note(notes)
1✔
3528
                    .with_help(attr_line_t("If the timestamp format is not "
2✔
3529
                                           "supported by default, you can "
3530
                                           "add a custom format with the ")
3531
                                   .append_quoted("timestamp-format"_symbol)
1✔
3532
                                   .append(" property")));
1✔
3533
        }
1✔
3534

3535
        auto level = this->convert_level(
182,299✔
3536
            level_cap.value_or(string_fragment::invalid()), nullptr);
182,299✔
3537

3538
        if (sample.s_level != LEVEL_UNKNOWN && sample.s_level != level) {
182,299✔
3539
            attr_line_t note_al;
1✔
3540

3541
            note_al.append("matched regex = ")
1✔
3542
                .append(lnav::roles::symbol(pat.p_name.to_string()))
2✔
3543
                .append("\n")
1✔
3544
                .append("captured level = ")
1✔
3545
                .append_quoted(level_cap->to_string());
1✔
3546
            if (level_cap && !this->elf_level_patterns.empty()) {
1✔
3547
                thread_local auto md = lnav::pcre2pp::match_data::unitialized();
1✔
3548

3549
                note_al.append("\nlevel regular expression match results:");
1✔
3550
                for (const auto& level_pattern : this->elf_level_patterns) {
3✔
3551
                    attr_line_t regex_al
3552
                        = level_pattern.second.lp_pcre.pp_value->get_pattern();
2✔
3553
                    lnav::snippets::regex_highlighter(
2✔
3554
                        regex_al, -1, line_range{0, (int) regex_al.length()});
2✔
3555
                    note_al.append("\n  ")
2✔
3556
                        .append(lnav::roles::symbol(
4✔
3557
                            level_pattern.second.lp_pcre.pp_path.to_string()))
4✔
3558
                        .append(" = ")
2✔
3559
                        .append(regex_al)
2✔
3560
                        .append("\n    ");
2✔
3561
                    auto match_res = level_pattern.second.lp_pcre.pp_value
2✔
3562
                                         ->capture_from(level_cap.value())
2✔
3563
                                         .into(md)
2✔
3564
                                         .matches(PCRE2_NO_UTF_CHECK)
4✔
3565
                                         .ignore_error();
2✔
3566
                    if (!match_res) {
2✔
3567
                        note_al.append(lnav::roles::warning("no match"));
1✔
3568
                        continue;
1✔
3569
                    }
3570

3571
                    note_al.append(level_cap.value())
1✔
3572
                        .append("\n    ")
1✔
3573
                        .append(md.leading().length(), ' ')
1✔
3574
                        .append("^"_snippet_border);
1✔
3575
                    if (match_res->f_all.length() > 2) {
1✔
3576
                        note_al.append(lnav::roles::snippet_border(
1✔
3577
                            std::string(match_res->f_all.length() - 2, '-')));
3✔
3578
                    }
3579
                    if (match_res->f_all.length() > 1) {
1✔
3580
                        note_al.append("^"_snippet_border);
1✔
3581
                    }
3582
                }
2✔
3583
            }
3584
            auto um
3585
                = lnav::console::user_message::error(
×
3586
                      attr_line_t("invalid sample log message: ")
1✔
3587
                          .append(lnav::to_json(sample.s_line.pp_value)))
2✔
3588
                      .with_reason(attr_line_t()
2✔
3589
                                       .append_quoted(lnav::roles::symbol(
2✔
3590
                                           level_names[level]))
1✔
3591
                                       .append(" does not match the expected "
1✔
3592
                                               "level of ")
3593
                                       .append_quoted(lnav::roles::symbol(
2✔
3594
                                           level_names[sample.s_level])))
1✔
3595
                      .with_snippet(sample.s_line.to_snippet())
2✔
3596
                      .with_note(note_al)
1✔
3597
                      .move();
1✔
3598
            if (!this->elf_level_patterns.empty()) {
1✔
3599
                um.with_help(
1✔
3600
                    attr_line_t("Level regexes are not anchored to the "
2✔
3601
                                "start/end of the string.  Prepend ")
3602
                        .append_quoted("^"_symbol)
1✔
3603
                        .append(" to the expression to match from the "
1✔
3604
                                "start of the string and append ")
3605
                        .append_quoted("$"_symbol)
1✔
3606
                        .append(" to match up to the end of the string."));
1✔
3607
            }
3608
            msgs.emplace_back(um);
1✔
3609
        }
1✔
3610

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

3671
    if (!found && !this->elf_pattern_order.empty()) {
182,301✔
3672
        std::vector<std::pair<ssize_t, intern_string_t>> partial_indexes;
2✔
3673
        attr_line_t notes;
2✔
3674
        size_t max_name_width = 0;
2✔
3675

3676
        for (const auto& pat_iter : this->elf_pattern_order) {
10✔
3677
            auto& pat = *pat_iter;
8✔
3678

3679
            if (!pat.p_pcre.pp_value) {
8✔
3680
                continue;
×
3681
            }
3682

3683
            partial_indexes.emplace_back(
8✔
3684
                pat.p_pcre.pp_value->match_partial(lines[0]), pat.p_name);
8✔
3685
            max_name_width = std::max(max_name_width, pat.p_name.size());
8✔
3686
        }
3687
        for (const auto& line_frag : lines) {
4✔
3688
            auto src_line = attr_line_t(line_frag.to_string());
2✔
3689
            if (!line_frag.endswith("\n")) {
2✔
3690
                src_line.append("\n");
2✔
3691
            }
3692
            src_line.with_attr_for_all(VC_ROLE.value(role_t::VCR_QUOTED_CODE));
2✔
3693
            notes.append("   ").append(src_line);
2✔
3694
            for (auto& part_pair : partial_indexes) {
10✔
3695
                if (part_pair.first >= 0
16✔
3696
                    && part_pair.first < line_frag.length())
8✔
3697
                {
3698
                    notes.append("   ")
8✔
3699
                        .append(part_pair.first, ' ')
8✔
3700
                        .append("^ "_snippet_border)
8✔
3701
                        .append(
8✔
3702
                            lnav::roles::symbol(part_pair.second.to_string()))
16✔
3703
                        .append(" matched up to here"_snippet_border)
8✔
3704
                        .append("\n");
8✔
3705
                }
3706
                part_pair.first -= line_frag.length();
8✔
3707
            }
3708
        }
2✔
3709
        notes.add_header(
2✔
3710
            "the following shows how each pattern matched this sample:\n");
3711

3712
        attr_line_t regex_note;
2✔
3713
        for (const auto& pat_iter : this->elf_pattern_order) {
10✔
3714
            if (!pat_iter->p_pcre.pp_value) {
8✔
3715
                regex_note
3716
                    .append(lnav::roles::symbol(fmt::format(
×
3717
                        FMT_STRING("{:{}}"), pat_iter->p_name, max_name_width)))
×
3718
                    .append(" is invalid");
×
3719
                continue;
×
3720
            }
3721

3722
            attr_line_t regex_al = pat_iter->p_pcre.pp_value->get_pattern();
8✔
3723
            lnav::snippets::regex_highlighter(
8✔
3724
                regex_al, -1, line_range{0, (int) regex_al.length()});
8✔
3725

3726
            regex_note
3727
                .append(lnav::roles::symbol(fmt::format(
16✔
3728
                    FMT_STRING("{:{}}"), pat_iter->p_name, max_name_width)))
24✔
3729
                .append(" = ")
8✔
3730
                .append_quoted(regex_al)
16✔
3731
                .append("\n");
8✔
3732
        }
8✔
3733

3734
        msgs.emplace_back(
2✔
3735
            lnav::console::user_message::error(
×
3736
                attr_line_t("invalid sample log message: ")
2✔
3737
                    .append(lnav::to_json(sample.s_line.pp_value)))
4✔
3738
                .with_reason("sample does not match any patterns")
4✔
3739
                .with_snippet(sample.s_line.to_snippet())
4✔
3740
                .with_note(notes.rtrim())
4✔
3741
                .with_note(regex_note));
3742
    }
2✔
3743

3744
    return retval;
182,301✔
3745
}
184,544✔
3746

3747
void
3748
external_log_format::build(std::vector<lnav::console::user_message>& errors)
51,862✔
3749
{
3750
    auto& vc = view_colors::singleton();
51,862✔
3751

3752
    if (!this->lf_timestamp_field.empty()) {
51,862✔
3753
        auto& vd = this->elf_value_defs[this->lf_timestamp_field];
51,862✔
3754
        if (vd.get() == nullptr) {
51,862✔
3755
            vd = std::make_shared<value_def>(
37,573✔
3756
                this->lf_timestamp_field,
37,573✔
3757
                value_kind_t::VALUE_TEXT,
×
3758
                logline_value_meta::internal_column{},
×
3759
                this);
37,573✔
3760
            if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
37,573✔
3761
                this->elf_value_def_order.emplace_back(vd);
5,711✔
3762
            }
3763
        }
3764
        vd->vd_meta.lvm_name = this->lf_timestamp_field;
51,862✔
3765
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
51,862✔
3766
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
51,862✔
3767
        vd->vd_internal = true;
51,862✔
3768

3769
        this->elf_value_defs[LOG_TIME_STR] = vd;
51,862✔
3770
    }
3771

3772
    if (!this->lf_subsecond_field.empty()) {
51,862✔
3773
        if (!this->lf_subsecond_unit.has_value()) {
97✔
3774
            errors.emplace_back(
1✔
3775
                lnav::console::user_message::error(
×
3776
                    attr_line_t()
2✔
3777
                        .append_quoted(
1✔
3778
                            lnav::roles::symbol(this->elf_name.to_string()))
2✔
3779
                        .append(" is not a valid log format"))
1✔
3780
                    .with_reason(attr_line_t()
2✔
3781
                                     .append_quoted("subsecond-units"_symbol)
1✔
3782
                                     .append(" must be set when ")
1✔
3783
                                     .append_quoted("subsecond-field"_symbol)
1✔
3784
                                     .append(" is used"))
1✔
3785
                    .with_snippets(this->get_snippets()));
2✔
3786
        } else {
3787
            auto& vd = this->elf_value_defs[this->lf_subsecond_field];
96✔
3788
            if (vd.get() == nullptr) {
96✔
3789
                vd = std::make_shared<value_def>(
96✔
3790
                    this->lf_subsecond_field,
96✔
3791
                    value_kind_t::VALUE_INTEGER,
×
3792
                    logline_value_meta::internal_column{},
×
3793
                    this);
96✔
3794
                if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
96✔
3795
                    this->elf_value_def_order.emplace_back(vd);
96✔
3796
                }
3797
            }
3798
            vd->vd_meta.lvm_name = this->lf_subsecond_field;
96✔
3799
            vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
96✔
3800
            vd->vd_meta.lvm_hidden = true;
96✔
3801
            vd->vd_internal = true;
96✔
3802
        }
3803
    }
3804

3805
    if (startswith(this->elf_level_field.get(), "/")) {
51,862✔
3806
        this->elf_level_field
3807
            = intern_string::lookup(this->elf_level_field.get() + 1);
192✔
3808
    }
3809
    if (!this->elf_level_field.empty()) {
51,862✔
3810
        auto level_iter = this->elf_value_defs.find(this->elf_level_field);
51,862✔
3811
        if (level_iter == this->elf_value_defs.end()) {
51,862✔
3812
            auto& vd = this->elf_value_defs[this->elf_level_field];
25,524✔
3813
            vd = std::make_shared<value_def>(
25,524✔
3814
                this->elf_level_field,
25,524✔
3815
                value_kind_t::VALUE_TEXT,
×
3816
                logline_value_meta::internal_column{},
×
3817
                this);
25,524✔
3818
            if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
25,524✔
3819
                this->elf_value_def_order.emplace_back(vd);
2,627✔
3820
            }
3821
            vd->vd_meta.lvm_name = this->elf_level_field;
25,524✔
3822
            vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
25,524✔
3823
            vd->vd_internal = true;
25,524✔
3824

3825
            if (this->elf_level_field != this->elf_body_field) {
25,524✔
3826
                this->elf_value_defs[LOG_LEVEL_STR] = vd;
24,681✔
3827
            }
3828
        } else {
3829
            if (level_iter->second->vd_meta.lvm_kind
26,338✔
3830
                != value_kind_t::VALUE_TEXT)
26,338✔
3831
            {
3832
                this->lf_level_hideable = false;
5,325✔
3833
            }
3834
            this->elf_value_defs[LOG_LEVEL_STR] = level_iter->second;
26,338✔
3835
        }
3836
    }
3837

3838
    auto opid_field_iter = this->elf_value_defs.find(LOG_OPID_STR);
51,862✔
3839
    if (opid_field_iter == this->elf_value_defs.end()) {
51,862✔
3840
        auto vd
3841
            = std::make_shared<value_def>(this->elf_opid_field,
51,862✔
3842
                                          value_kind_t::VALUE_TEXT,
×
3843
                                          logline_value_meta::internal_column{},
×
3844
                                          this);
51,862✔
3845
        if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
51,862✔
3846
            this->elf_value_def_order.emplace_back(vd);
9,542✔
3847
        }
3848
        vd->vd_meta.lvm_name = LOG_OPID_STR;
51,862✔
3849
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
51,862✔
3850
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
51,862✔
3851
        vd->vd_internal = true;
51,862✔
3852

3853
        this->elf_value_defs[LOG_OPID_STR] = vd;
51,862✔
3854
    }
51,862✔
3855

3856
    if (!this->elf_body_field.empty()) {
51,862✔
3857
        auto& vd = this->elf_value_defs[this->elf_body_field];
51,862✔
3858
        if (vd.get() == nullptr) {
51,862✔
3859
            vd = std::make_shared<value_def>(
42,705✔
3860
                this->elf_body_field,
42,705✔
3861
                value_kind_t::VALUE_TEXT,
×
3862
                logline_value_meta::internal_column{},
×
3863
                this);
42,705✔
3864
            if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
42,705✔
3865
                this->elf_value_def_order.emplace_back(vd);
6,457✔
3866
            }
3867
        }
3868
        vd->vd_meta.lvm_name = this->elf_body_field;
51,862✔
3869
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
51,862✔
3870
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
51,862✔
3871
        vd->vd_internal = true;
51,862✔
3872
    }
3873

3874
    if (!this->elf_src_file_field.empty()) {
51,862✔
3875
        auto& vd = this->elf_value_defs[this->elf_src_file_field];
7,471✔
3876
        if (vd.get() == nullptr) {
7,471✔
3877
            vd = std::make_shared<value_def>(
1✔
3878
                this->elf_src_file_field,
1✔
3879
                value_kind_t::VALUE_TEXT,
×
3880
                logline_value_meta::internal_column{},
×
3881
                this);
2✔
3882
        }
3883
        vd->vd_meta.lvm_name = this->elf_src_file_field;
7,471✔
3884
        vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
7,471✔
3885
        vd->vd_meta.lvm_column = logline_value_meta::internal_column{};
7,471✔
3886
    }
3887

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

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

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

3930
    for (auto& od_pair : *this->lf_opid_description_def) {
74,274✔
3931
        od_pair.second.od_index = this->lf_opid_description_def_vec->size();
22,412✔
3932
        this->lf_opid_description_def_vec->emplace_back(&od_pair.second);
22,412✔
3933
    }
3934

3935
    for (auto& od_pair : *this->lf_subid_description_def) {
52,609✔
3936
        od_pair.second.od_index = this->lf_subid_description_def_vec->size();
747✔
3937
        this->lf_subid_description_def_vec->emplace_back(&od_pair.second);
747✔
3938
    }
3939

3940
    if (!this->lf_timestamp_format.empty()) {
51,862✔
3941
        this->lf_timestamp_format.push_back(nullptr);
5,329✔
3942
    }
3943
    auto src_file_found = 0;
51,862✔
3944
    auto src_line_found = 0;
51,862✔
3945
    auto thread_id_found = 0;
51,862✔
3946
    auto duration_found = 0;
51,862✔
3947
    for (auto& elf_pattern : this->elf_patterns) {
148,813✔
3948
        auto& pat = *elf_pattern.second;
96,951✔
3949

3950
        if (pat.p_pcre.pp_value == nullptr) {
96,951✔
3951
            continue;
1✔
3952
        }
3953

3954
        if (pat.p_opid_field_index == -1
193,900✔
3955
            && this->lf_opid_source.value_or(opid_source_t::from_description)
96,950✔
3956
                == opid_source_t::from_description
3957
            && this->lf_opid_description_def->size() == 1)
193,900✔
3958
        {
3959
            const auto& opid_def
3960
                = this->lf_opid_description_def->begin()->second;
24,651✔
3961
            for (const auto& desc : *opid_def.od_descriptors) {
55,278✔
3962
                for (auto named_cap : pat.p_pcre.pp_value->get_named_captures())
357,066✔
3963
                {
3964
                    const intern_string_t name
3965
                        = intern_string::lookup(named_cap.get_name());
326,439✔
3966

3967
                    if (name == desc.od_field.pp_value) {
326,439✔
3968
                        pat.p_opid_description_field_indexes.emplace_back(
56,772✔
3969
                            named_cap.get_index());
28,386✔
3970
                    }
3971
                }
3972
            }
3973
        }
3974

3975
        for (auto named_cap : pat.p_pcre.pp_value->get_named_captures()) {
837,676✔
3976
            const intern_string_t name
3977
                = intern_string::lookup(named_cap.get_name());
740,726✔
3978

3979
            if (name == this->lf_timestamp_field) {
740,726✔
3980
                pat.p_timestamp_field_index = named_cap.get_index();
96,948✔
3981
            }
3982
            if (name == this->lf_time_field) {
740,726✔
3983
                pat.p_time_field_index = named_cap.get_index();
747✔
3984
            }
3985
            if (name == this->elf_level_field) {
740,726✔
3986
                pat.p_level_field_index = named_cap.get_index();
73,592✔
3987
            }
3988
            if (name == this->elf_opid_field) {
740,726✔
3989
                pat.p_opid_field_index = named_cap.get_index();
20,169✔
3990
            }
3991
            if (name == this->elf_subid_field) {
740,726✔
3992
                pat.p_subid_field_index = named_cap.get_index();
11,205✔
3993
            }
3994
            if (name == this->elf_body_field) {
740,726✔
3995
                pat.p_body_field_index = named_cap.get_index();
83,502✔
3996
            }
3997
            if (name == this->elf_src_file_field) {
740,726✔
3998
                pat.p_src_file_field_index = named_cap.get_index();
11,952✔
3999
                src_file_found += 1;
11,952✔
4000
            }
4001
            if (name == this->elf_src_line_field) {
740,726✔
4002
                pat.p_src_line_field_index = named_cap.get_index();
13,446✔
4003
                src_line_found += 1;
13,446✔
4004
            }
4005
            if (name == this->elf_thread_id_field) {
740,726✔
4006
                pat.p_thread_id_field_index = named_cap.get_index();
41,832✔
4007
                thread_id_found += 1;
41,832✔
4008
            }
4009
            if (name == this->elf_duration_field) {
740,726✔
4010
                pat.p_duration_field_index = named_cap.get_index();
4,482✔
4011
                duration_found += 1;
4,482✔
4012
            }
4013

4014
            auto value_iter = this->elf_value_defs.find(name);
740,726✔
4015
            if (value_iter != this->elf_value_defs.end()) {
740,726✔
4016
                auto vd = value_iter->second;
729,423✔
4017
                indexed_value_def ivd;
729,423✔
4018

4019
                ivd.ivd_index = named_cap.get_index();
729,423✔
4020
                if (!vd->vd_unit_field.empty()) {
729,423✔
4021
                    ivd.ivd_unit_field_index = pat.p_pcre.pp_value->name_index(
1,494✔
4022
                        vd->vd_unit_field.get());
747✔
4023
                } else {
4024
                    ivd.ivd_unit_field_index = -1;
728,676✔
4025
                }
4026
                if (!vd->vd_internal
729,423✔
4027
                    && !vd->vd_meta.lvm_column
1,254,203✔
4028
                            .is<logline_value_meta::table_column>())
524,780✔
4029
                {
4030
                    vd->vd_meta.lvm_column = logline_value_meta::table_column{
293,957✔
4031
                        this->elf_column_count++};
293,957✔
4032
                }
4033
                ivd.ivd_value_def = vd;
729,423✔
4034
                pat.p_value_by_index.push_back(ivd);
729,423✔
4035
            }
729,423✔
4036
            pat.p_value_name_to_index[name] = named_cap.get_index();
740,726✔
4037
        }
4038

4039
        stable_sort(pat.p_value_by_index.begin(), pat.p_value_by_index.end());
96,950✔
4040

4041
        for (int lpc = 0; lpc < (int) pat.p_value_by_index.size(); lpc++) {
826,373✔
4042
            auto& ivd = pat.p_value_by_index[lpc];
729,423✔
4043
            auto vd = ivd.ivd_value_def;
729,423✔
4044

4045
            if (!vd->vd_meta.lvm_foreign_key && !vd->vd_meta.lvm_identifier) {
729,423✔
4046
                switch (vd->vd_meta.lvm_kind) {
369,923✔
4047
                    case value_kind_t::VALUE_INTEGER:
51,639✔
4048
                    case value_kind_t::VALUE_FLOAT:
4049
                        pat.p_numeric_value_indexes.push_back(lpc);
51,639✔
4050
                        break;
51,639✔
4051
                    default:
318,284✔
4052
                        break;
318,284✔
4053
                }
4054
            }
4055
        }
729,423✔
4056

4057
        if (pat.p_timestamp_field_index == -1) {
96,950✔
4058
            errors.emplace_back(
2✔
4059
                lnav::console::user_message::error(
×
4060
                    attr_line_t("invalid pattern: ")
4✔
4061
                        .append_quoted(lnav::roles::symbol(pat.p_config_path)))
4✔
4062
                    .with_reason("no timestamp capture found in the pattern")
4✔
4063
                    .with_snippets(this->get_snippets())
4✔
4064
                    .with_help("all log messages need a timestamp"));
4065
        }
4066

4067
        if (!this->elf_level_field.empty() && pat.p_level_field_index == -1) {
96,950✔
4068
            log_warning("%s:level field '%s' not found in pattern",
23,358✔
4069
                        pat.p_config_path.c_str(),
4070
                        this->elf_level_field.get());
4071
        }
4072
        if (!this->elf_body_field.empty() && pat.p_body_field_index == -1) {
96,950✔
4073
            log_warning("%s:body field '%s' not found in pattern",
13,448✔
4074
                        pat.p_config_path.c_str(),
4075
                        this->elf_body_field.get());
4076
        }
4077

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

4139
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
51,862✔
4140
        if (!this->elf_patterns.empty()) {
9,542✔
4141
            errors.emplace_back(
1✔
4142
                lnav::console::user_message::error(
×
4143
                    attr_line_t()
2✔
4144
                        .append_quoted(
1✔
4145
                            lnav::roles::symbol(this->elf_name.to_string()))
2✔
4146
                        .append(" is not a valid log format"))
1✔
4147
                    .with_reason("structured logs cannot have regexes")
2✔
4148
                    .with_snippets(this->get_snippets()));
2✔
4149
        }
4150
        if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
9,542✔
4151
            this->lf_multiline = true;
9,542✔
4152
            this->lf_structured = true;
9,542✔
4153
            this->lf_formatted_lines = true;
9,542✔
4154
            this->jlf_parse_context
4155
                = std::make_shared<yajlpp_parse_context>(this->elf_name);
9,542✔
4156
            this->jlf_yajl_handle.reset(
9,542✔
4157
                yajl_alloc(&this->jlf_parse_context->ypc_callbacks,
9,542✔
4158
                           nullptr,
4159
                           this->jlf_parse_context.get()),
9,542✔
4160
                yajl_handle_deleter());
4161
            yajl_config(
9,542✔
4162
                this->jlf_yajl_handle.get(), yajl_dont_validate_strings, 1);
4163
        }
4164
    } else {
4165
        if (this->elf_patterns.empty()) {
42,320✔
4166
            errors.emplace_back(lnav::console::user_message::error(
2✔
4167
                                    attr_line_t()
4✔
4168
                                        .append_quoted(lnav::roles::symbol(
4✔
4169
                                            this->elf_name.to_string()))
4✔
4170
                                        .append(" is not a valid log format"))
2✔
4171
                                    .with_reason("no regexes specified")
4✔
4172
                                    .with_snippets(this->get_snippets()));
4✔
4173
        }
4174
    }
4175

4176
    stable_sort(this->elf_level_pairs.begin(), this->elf_level_pairs.end());
51,862✔
4177

4178
    {
4179
        safe::WriteAccess<safe_format_header_expressions> hexprs(
4180
            format_header_exprs);
51,862✔
4181

4182
        if (hexprs->e_db.in() == nullptr) {
51,862✔
4183
            if (sqlite3_open(":memory:", hexprs->e_db.out()) != SQLITE_OK) {
747✔
4184
                log_error("unable to open memory DB");
×
4185
                return;
×
4186
            }
4187
            register_sqlite_funcs(hexprs->e_db.in(), sqlite_registration_funcs);
747✔
4188
        }
4189

4190
        for (const auto& hpair : this->elf_converter.c_header.h_exprs.he_exprs)
54,851✔
4191
        {
4192
            auto stmt_str
4193
                = fmt::format(FMT_STRING("SELECT 1 WHERE {}"), hpair.second);
8,967✔
4194
            compiled_header_expr che;
2,989✔
4195

4196
            log_info("preparing file-format header expression: %s",
2,989✔
4197
                     stmt_str.c_str());
4198
            auto retcode = sqlite3_prepare_v2(hexprs->e_db.in(),
5,978✔
4199
                                              stmt_str.c_str(),
4200
                                              stmt_str.size(),
2,989✔
4201
                                              che.che_stmt.out(),
4202
                                              nullptr);
4203
            if (retcode != SQLITE_OK) {
2,989✔
4204
                auto sql_al = attr_line_t(hpair.second)
2✔
4205
                                  .with_attr_for_all(SA_PREFORMATTED.value())
2✔
4206
                                  .with_attr_for_all(
1✔
4207
                                      VC_ROLE.value(role_t::VCR_QUOTED_CODE))
2✔
4208
                                  .move();
1✔
4209
                readline_sql_highlighter(
1✔
4210
                    sql_al, lnav::sql::dialect::sqlite, std::nullopt);
4211
                intern_string_t watch_expr_path = intern_string::lookup(
4212
                    fmt::format(FMT_STRING("/{}/converter/header/expr/{}"),
3✔
4213
                                this->elf_name,
1✔
4214
                                hpair.first));
2✔
4215
                auto snippet = lnav::console::snippet::from(
4216
                    source_location(watch_expr_path), sql_al);
1✔
4217

4218
                auto um = lnav::console::user_message::error(
2✔
4219
                              "SQL expression is invalid")
4220
                              .with_reason(sqlite3_errmsg(hexprs->e_db.in()))
2✔
4221
                              .with_snippet(snippet)
1✔
4222
                              .move();
1✔
4223

4224
                errors.emplace_back(um);
1✔
4225
                continue;
1✔
4226
            }
1✔
4227

4228
            hexprs->e_header_exprs[this->elf_name][hpair.first]
2,988✔
4229
                = std::move(che);
5,976✔
4230
        }
2,990✔
4231

4232
        if (!this->elf_converter.c_header.h_exprs.he_exprs.empty()
51,862✔
4233
            && this->elf_converter.c_command.pp_value.empty())
51,862✔
4234
        {
4235
            auto um = lnav::console::user_message::error(
2✔
4236
                          "A command is required when a converter is defined")
4237
                          .with_help(
2✔
4238
                              "The converter command transforms the file "
4239
                              "into a format that can be consumed by lnav")
4240
                          .with_snippets(this->get_snippets())
2✔
4241
                          .move();
1✔
4242
            errors.emplace_back(um);
1✔
4243
        }
1✔
4244
    }
51,862✔
4245

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

4249
        if (!vd->vd_internal
458,242✔
4250
            && log_vtab_impl::RESERVED_COLUMNS.count(
869,448✔
4251
                vd->vd_meta.lvm_name.to_string_fragment()))
869,448✔
4252
        {
4253
            auto um = lnav::console::user_message::error(
×
4254
                          attr_line_t("value name ")
1✔
4255
                              .append_quoted(lnav::roles::symbol(
2✔
4256
                                  fmt::format(FMT_STRING("/{}/value/{}"),
4✔
4257
                                              this->elf_name,
1✔
4258
                                              vd->vd_meta.lvm_name)))
1✔
4259
                              .append(" is reserved and cannot be used"))
1✔
4260
                          .with_reason(
2✔
4261
                              "lnav automatically defines several columns in "
4262
                              "the log virtual table")
4263
                          .with_snippets(this->get_snippets())
2✔
4264
                          .with_help("Choose another name")
2✔
4265
                          .move();
1✔
4266
            errors.emplace_back(um);
1✔
4267
        }
1✔
4268

4269
        vd->vd_meta.lvm_format = this;
458,242✔
4270
        if (!vd->vd_internal
458,242✔
4271
            && !vd->vd_meta.lvm_column.is<logline_value_meta::table_column>())
458,242✔
4272
        {
4273
            vd->vd_meta.lvm_column
117,249✔
4274
                = logline_value_meta::table_column{this->elf_column_count++};
117,249✔
4275
        }
4276

4277
        if (vd->vd_meta.lvm_kind == value_kind_t::VALUE_UNKNOWN) {
458,242✔
4278
            vd->vd_meta.lvm_kind = value_kind_t::VALUE_TEXT;
×
4279
        }
4280

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

4284
            bool found_in_pattern = false;
309,646✔
4285
            for (const auto& pat : this->elf_patterns) {
522,545✔
4286
                if (pat.second->p_pcre.pp_value == nullptr) {
522,543✔
4287
                    continue;
×
4288
                }
4289

4290
                auto cap_index = pat.second->p_pcre.pp_value->name_index(
1,045,086✔
4291
                    vd->vd_meta.lvm_name.get());
522,543✔
4292
                if (cap_index >= 0) {
522,543✔
4293
                    found_in_pattern = true;
309,644✔
4294
                    break;
309,644✔
4295
                }
4296

4297
                for (auto named_cap :
212,899✔
4298
                     pat.second->p_pcre.pp_value->get_named_captures())
1,942,965✔
4299
                {
4300
                    available_captures.insert(named_cap.get_name().to_string());
1,517,167✔
4301
                }
4302
            }
4303
            if (!found_in_pattern) {
309,646✔
4304
                auto notes
4305
                    = attr_line_t("the following captures are available:\n  ")
2✔
4306
                          .join(available_captures,
2✔
4307
                                VC_ROLE.value(role_t::VCR_SYMBOL),
4✔
4308
                                ", ")
4309
                          .move();
2✔
4310
                errors.emplace_back(
2✔
4311
                    lnav::console::user_message::warning(
×
4312
                        attr_line_t("invalid value ")
2✔
4313
                            .append_quoted(lnav::roles::symbol(
4✔
4314
                                fmt::format(FMT_STRING("/{}/value/{}"),
8✔
4315
                                            this->elf_name,
2✔
4316
                                            vd->vd_meta.lvm_name.get()))))
4✔
4317
                        .with_reason(
4✔
4318
                            attr_line_t("no patterns have a capture named ")
4✔
4319
                                .append_quoted(vd->vd_meta.lvm_name.get()))
2✔
4320
                        .with_note(notes)
2✔
4321
                        .with_snippets(this->get_snippets())
4✔
4322
                        .with_help("values are populated from captures in "
4323
                                   "patterns, so at least one pattern must "
4324
                                   "have a capture with this value name"));
4325
            }
2✔
4326
        }
309,646✔
4327

4328
        for (act_iter = vd->vd_action_list.begin();
458,242✔
4329
             act_iter != vd->vd_action_list.end();
458,989✔
4330
             ++act_iter)
747✔
4331
        {
4332
            if (this->lf_action_defs.find(*act_iter)
747✔
4333
                == this->lf_action_defs.end())
1,494✔
4334
            {
4335
#if 0
4336
                errors.push_back("error:" + this->elf_name.to_string() + ":"
4337
                                 + vd->vd_meta.lvm_name.get()
4338
                                 + ": cannot find action -- " + (*act_iter));
4339
#endif
4340
            }
4341
        }
4342

4343
        vd->set_rewrite_src_name();
458,242✔
4344
    }
4345

4346
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
51,862✔
4347
        for (const auto& vd : this->elf_value_def_order) {
158,138✔
4348
            this->elf_value_def_frag_map[vd->vd_meta.lvm_name
148,596✔
4349
                                             .to_string_fragment()]
148,596✔
4350
                = vd.get();
297,192✔
4351
        }
4352
    }
4353

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

4357
        if (td->ftd_pattern.pp_value == nullptr
2,340✔
4358
            || td->ftd_pattern.pp_value->get_pattern().empty())
2,340✔
4359
        {
4360
            errors.emplace_back(
3✔
4361
                lnav::console::user_message::error(
×
4362
                    attr_line_t("invalid tag definition ")
6✔
4363
                        .append_quoted(lnav::roles::symbol(
6✔
4364
                            fmt::format(FMT_STRING("/{}/tags/{}"),
12✔
4365
                                        this->elf_name,
3✔
4366
                                        td_pair.first))))
3✔
4367
                    .with_reason(
6✔
4368
                        "tag definitions must have a non-empty pattern")
4369
                    .with_snippets(this->get_snippets()));
6✔
4370
        }
4371
    }
4372

4373
    if (this->elf_opid_field.empty()
51,862✔
4374
        && this->lf_opid_description_def->size() > 1)
51,862✔
4375
    {
4376
        errors.emplace_back(
1✔
4377
            lnav::console::user_message::error(
×
4378
                attr_line_t("too many opid descriptions")
2✔
4379
                    .append_quoted(lnav::roles::symbol(fmt::format(
2✔
4380
                        FMT_STRING("/{}/opid/description"), this->elf_name))))
4✔
4381
                .with_reason(attr_line_t("when no ")
2✔
4382
                                 .append("opid-field"_symbol)
1✔
4383
                                 .append(" is specified, only a single "
1✔
4384
                                         "description is supported"))
4385
                .with_snippets(this->get_snippets()));
2✔
4386
    }
4387

4388
    for (const auto& opid_desc_pair : *this->lf_opid_description_def) {
74,274✔
4389
        for (const auto& opid_desc : *opid_desc_pair.second.od_descriptors) {
53,041✔
4390
            auto iter = this->elf_value_defs.find(opid_desc.od_field.pp_value);
30,629✔
4391
            if (iter == this->elf_value_defs.end()) {
30,629✔
4392
                errors.emplace_back(
2✔
4393
                    lnav::console::user_message::error(
×
4394
                        attr_line_t("invalid opid description field ")
4✔
4395
                            .append_quoted(lnav::roles::symbol(
4✔
4396
                                opid_desc.od_field.pp_path.to_string())))
4✔
4397
                        .with_reason(
4✔
4398
                            attr_line_t("unknown value name ")
4✔
4399
                                .append_quoted(opid_desc.od_field.pp_value))
2✔
4400
                        .with_snippets(this->get_snippets()));
4✔
4401
            } else {
4402
                this->lf_desc_fields.insert(iter->first);
30,627✔
4403
                iter->second->vd_is_desc_field = true;
30,627✔
4404
            }
4405
        }
4406
    }
4407

4408
    for (const auto& subid_desc_pair : *this->lf_subid_description_def) {
52,609✔
4409
        for (const auto& subid_desc : *subid_desc_pair.second.od_descriptors) {
1,494✔
4410
            auto iter = this->elf_value_defs.find(subid_desc.od_field.pp_value);
747✔
4411
            if (iter == this->elf_value_defs.end()) {
747✔
4412
                errors.emplace_back(
×
4413
                    lnav::console::user_message::error(
×
4414
                        attr_line_t("invalid subid description field ")
×
4415
                            .append_quoted(lnav::roles::symbol(
×
4416
                                subid_desc.od_field.pp_path.to_string())))
×
4417
                        .with_reason(
×
4418
                            attr_line_t("unknown value name ")
×
4419
                                .append_quoted(subid_desc.od_field.pp_value))
×
4420
                        .with_snippets(this->get_snippets()));
×
4421
            } else {
4422
                this->lf_desc_fields.insert(iter->first);
747✔
4423
                iter->second->vd_is_desc_field = true;
747✔
4424
            }
4425
        }
4426
    }
4427

4428
    if (this->elf_type == elf_type_t::ELF_TYPE_TEXT
103,724✔
4429
        && this->elf_samples.empty())
51,862✔
4430
    {
4431
        errors.emplace_back(
3✔
4432
            lnav::console::user_message::error(
×
4433
                attr_line_t()
6✔
4434
                    .append_quoted(
3✔
4435
                        lnav::roles::symbol(this->elf_name.to_string()))
6✔
4436
                    .append(" is not a valid log format"))
3✔
4437
                .with_reason("log message samples must be included in a format "
6✔
4438
                             "definition")
4439
                .with_snippets(this->get_snippets()));
6✔
4440
    }
4441

4442
    for (const auto& pat : this->elf_pattern_order) {
148,812✔
4443
        if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
96,950✔
4444
            continue;
1✔
4445
        }
4446
        if (pat->p_pcre.pp_value->name_index(this->lf_timestamp_field.get())
96,949✔
4447
            < 0)
96,949✔
4448
        {
4449
            attr_line_t notes;
1✔
4450
            bool first_note = true;
1✔
4451

4452
            if (pat->p_pcre.pp_value->get_capture_count() > 0) {
1✔
4453
                notes.append("the following captures are available:\n  ");
1✔
4454
            }
4455
            for (auto named_cap : pat->p_pcre.pp_value->get_named_captures()) {
4✔
4456
                if (!first_note) {
3✔
4457
                    notes.append(", ");
2✔
4458
                }
4459
                notes.append(
3✔
4460
                    lnav::roles::symbol(named_cap.get_name().to_string()));
6✔
4461
                first_note = false;
3✔
4462
            }
4463
            errors.emplace_back(
1✔
4464
                lnav::console::user_message::error(
×
4465
                    attr_line_t("invalid value for property ")
1✔
4466
                        .append_quoted(lnav::roles::symbol(
2✔
4467
                            fmt::format(FMT_STRING("/{}/timestamp-field"),
4✔
4468
                                        this->elf_name))))
1✔
4469
                    .with_reason(
2✔
4470
                        attr_line_t()
2✔
4471
                            .append_quoted(this->lf_timestamp_field)
1✔
4472
                            .append(" was not found in the pattern at ")
1✔
4473
                            .append(lnav::roles::symbol(pat->p_config_path)))
2✔
4474
                    .with_note(notes)
1✔
4475
                    .with_snippets(this->get_snippets()));
2✔
4476
        }
1✔
4477
    }
4478

4479
    for (size_t sample_index = 0; sample_index < this->elf_samples.size();
236,402✔
4480
         sample_index += 1)
184,540✔
4481
    {
4482
        auto& elf_sample = this->elf_samples[sample_index];
184,540✔
4483
        auto sample_lines
4484
            = string_fragment(elf_sample.s_line.pp_value).split_lines();
184,540✔
4485

4486
        if (this->test_line(elf_sample, errors).is<scan_match>()) {
184,540✔
4487
            for (const auto& pat_name : elf_sample.s_matched_regexes) {
366,837✔
4488
                this->elf_patterns[pat_name]->p_matched_samples.emplace(
182,298✔
4489
                    sample_index);
4490
            }
4491
        }
4492
    }
184,540✔
4493

4494
    if (!this->elf_samples.empty()) {
51,862✔
4495
        for (const auto& elf_sample : this->elf_samples) {
227,604✔
4496
            if (elf_sample.s_matched_regexes.size() <= 1) {
184,540✔
4497
                continue;
184,540✔
4498
            }
4499

4500
            errors.emplace_back(
×
4501
                lnav::console::user_message::warning(
×
4502
                    attr_line_t("invalid log format: ")
×
4503
                        .append_quoted(
×
4504
                            lnav::roles::symbol(this->elf_name.to_string())))
×
4505
                    .with_reason(
×
4506
                        attr_line_t(
×
4507
                            "sample is matched by more than one regex: ")
4508
                            .join(elf_sample.s_matched_regexes,
×
4509
                                  VC_ROLE.value(role_t::VCR_SYMBOL),
×
4510
                                  ", "))
4511
                    .with_snippet(lnav::console::snippet::from(
×
4512
                        elf_sample.s_line.pp_location,
4513
                        attr_line_t().append(lnav::roles::quoted_code(
×
4514
                            elf_sample.s_line.pp_value))))
×
4515
                    .with_help("log format regexes must match a single type "
4516
                               "of log message"));
4517
        }
4518

4519
        for (const auto& pat : this->elf_pattern_order) {
140,011✔
4520
            if (pat->p_matched_samples.empty()) {
96,947✔
4521
                errors.emplace_back(
2✔
4522
                    lnav::console::user_message::warning(
×
4523
                        attr_line_t("invalid pattern: ")
4✔
4524
                            .append_quoted(
2✔
4525
                                lnav::roles::symbol(pat->p_config_path)))
4✔
4526
                        .with_reason("pattern does not match any samples")
4✔
4527
                        .with_snippet(lnav::console::snippet::from(
6✔
4528
                            pat->p_pcre.pp_location, ""))
2✔
4529
                        .with_help(
4530
                            "every pattern should have at least one sample "
4531
                            "that it matches"));
4532
            }
4533
        }
4534
    }
4535

4536
    size_t value_def_index = 0;
51,862✔
4537
    for (auto& elf_value_def : this->elf_value_def_order) {
510,104✔
4538
        elf_value_def->vd_meta.lvm_values_index
458,242✔
4539
            = std::make_optional(value_def_index++);
458,242✔
4540

4541
        if (elf_value_def->vd_meta.lvm_foreign_key
458,242✔
4542
            || elf_value_def->vd_meta.lvm_identifier)
458,242✔
4543
        {
4544
            continue;
244,771✔
4545
        }
4546

4547
        switch (elf_value_def->vd_meta.lvm_kind) {
213,471✔
4548
            case value_kind_t::VALUE_INTEGER:
53,421✔
4549
            case value_kind_t::VALUE_FLOAT:
4550
                this->elf_numeric_value_defs.push_back(elf_value_def);
53,421✔
4551
                break;
53,421✔
4552
            default:
160,050✔
4553
                break;
160,050✔
4554
        }
4555
    }
4556

4557
    int format_index = 0;
51,862✔
4558
    for (auto iter = this->jlf_line_format.begin();
51,862✔
4559
         iter != this->jlf_line_format.end();
159,730✔
4560
         ++iter, format_index++)
107,868✔
4561
    {
4562
        static const intern_string_t ts
4563
            = intern_string::lookup("__timestamp__");
109,362✔
4564
        static const intern_string_t level_field
4565
            = intern_string::lookup("__level__");
109,362✔
4566
        auto& jfe = *iter;
107,868✔
4567

4568
        if (startswith(jfe.jfe_value.pp_value.get(), "/")) {
107,868✔
4569
            jfe.jfe_value.pp_value
4570
                = intern_string::lookup(jfe.jfe_value.pp_value.get() + 1);
192✔
4571
        }
4572
        if (!jfe.jfe_ts_format.empty()) {
107,868✔
4573
            if (!jfe.jfe_value.pp_value.empty() && jfe.jfe_value.pp_value != ts)
843✔
4574
            {
4575
                log_warning(
96✔
4576
                    "%s:line-format[%d]:ignoring field '%s' since "
4577
                    "timestamp-format was used",
4578
                    this->elf_name.get(),
4579
                    format_index,
4580
                    jfe.jfe_value.pp_value.get());
4581
            }
4582
            jfe.jfe_value.pp_value = ts;
843✔
4583
        }
4584

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

4639
    for (auto& hd_pair : this->elf_highlighter_patterns) {
52,248✔
4640
        auto& hd = hd_pair.second;
386✔
4641
        text_attrs attrs;
386✔
4642

4643
        if (!hd.hd_color.pp_value.empty()) {
386✔
4644
            attrs.ta_fg_color = vc.match_color(
385✔
4645
                styling::color_unit::from_str(hd.hd_color.pp_value)
770✔
4646
                    .unwrapOrElse([&](const auto& msg) {
1✔
4647
                        errors.emplace_back(
1✔
4648
                            lnav::console::user_message::error(
4649
                                attr_line_t()
1✔
4650
                                    .append_quoted(hd.hd_color.pp_value)
2✔
4651
                                    .append(" is not a valid color value for "
1✔
4652
                                            "property ")
4653
                                    .append_quoted(lnav::roles::symbol(
2✔
4654
                                        hd.hd_color.pp_path.to_string())))
1✔
4655
                                .with_reason(msg)
2✔
4656
                                .with_snippet(hd.hd_color.to_snippet()));
1✔
4657
                        return styling::color_unit::EMPTY;
1✔
4658
                    }));
4659
        }
4660

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

4682
        if (hd.hd_underline) {
386✔
4683
            attrs |= text_attrs::style::underline;
96✔
4684
        }
4685
        if (hd.hd_blink) {
386✔
4686
            attrs |= text_attrs::style::blink;
×
4687
        }
4688

4689
        if (hd.hd_pattern.pp_value != nullptr) {
386✔
4690
            this->lf_highlighters.emplace_back(hd.hd_pattern.pp_value);
384✔
4691
            this->lf_highlighters.back()
384✔
4692
                .with_name(hd_pair.first.to_string())
768✔
4693
                .with_format_name(this->elf_name)
384✔
4694
                .with_attrs(attrs)
384✔
4695
                .with_nestable(hd.hd_nestable);
384✔
4696
        }
4697
    }
4698
}
4699

4700
void
4701
external_log_format::register_vtabs(
43,604✔
4702
    log_vtab_manager* vtab_manager,
4703
    std::vector<lnav::console::user_message>& errors)
4704
{
4705
    for (auto& elf_search_table : this->elf_search_tables) {
52,467✔
4706
        if (elf_search_table.second.std_pattern.pp_value == nullptr) {
8,863✔
4707
            continue;
1✔
4708
        }
4709

4710
        auto lst = std::make_shared<log_search_table>(
4711
            elf_search_table.second.std_pattern.pp_value,
8,862✔
4712
            elf_search_table.first);
8,862✔
4713
        lst->lst_format = this;
8,862✔
4714
        lst->lst_log_path_glob = elf_search_table.second.std_glob;
8,862✔
4715
        if (elf_search_table.second.std_level != LEVEL_UNKNOWN) {
8,862✔
4716
            lst->lst_log_level = elf_search_table.second.std_level;
3,165✔
4717
        }
4718
        auto errmsg = vtab_manager->register_vtab(lst);
8,862✔
4719
        if (!errmsg.empty()) {
8,862✔
4720
#if 0
4721
            errors.push_back("error:" + this->elf_name.to_string() + ":"
4722
                             + search_iter->first.to_string()
4723
                             + ":unable to register table -- " + errmsg);
4724
#endif
4725
        }
4726
    }
8,862✔
4727
}
43,604✔
4728

4729
bool
4730
external_log_format::match_samples(const std::vector<sample_t>& samples) const
3,558,926✔
4731
{
4732
    for (const auto& sample_iter : samples) {
16,065,038✔
4733
        for (const auto& pat_iter : this->elf_pattern_order) {
34,466,188✔
4734
            auto& pat = *pat_iter;
21,960,076✔
4735

4736
            if (!pat.p_pcre.pp_value) {
21,960,076✔
4737
                continue;
×
4738
            }
4739

4740
            if (pat.p_pcre.pp_value
43,920,152✔
4741
                    ->find_in(sample_iter.s_line.pp_value, PCRE2_NO_UTF_CHECK)
43,920,152✔
4742
                    .ignore_error())
43,920,152✔
4743
            {
4744
                return true;
15,557✔
4745
            }
4746
        }
4747
    }
4748

4749
    return false;
3,543,369✔
4750
}
4751

4752
class external_log_table : public log_format_vtab_impl {
4753
public:
4754
    explicit external_log_table(std::shared_ptr<const log_format> elf)
43,604✔
4755
        : log_format_vtab_impl(elf),
43,604✔
4756
          elt_format(dynamic_cast<const external_log_format*>(elf.get()))
43,604✔
4757
    {
4758
    }
43,604✔
4759

4760
    void get_columns(std::vector<vtab_column>& cols) const override
43,996✔
4761
    {
4762
        const auto& elf = this->elt_format;
43,996✔
4763

4764
        cols.resize(elf->elf_column_count);
43,996✔
4765
        for (const auto& vd : elf->elf_value_def_order) {
434,681✔
4766
            auto type_pair = logline_value_to_sqlite_type(vd->vd_meta.lvm_kind);
390,685✔
4767

4768
            if (!vd->vd_meta.lvm_column.is<logline_value_meta::table_column>())
390,685✔
4769
            {
4770
                continue;
39,265✔
4771
            }
4772

4773
            auto col
4774
                = vd->vd_meta.lvm_column.get<logline_value_meta::table_column>()
351,420✔
4775
                      .value;
351,420✔
4776
            require(0 <= col && col < elf->elf_column_count);
351,420✔
4777

4778
            cols[col].vc_name = vd->vd_meta.lvm_name.get();
351,420✔
4779
            cols[col].vc_type = type_pair.first;
351,420✔
4780
            cols[col].vc_subtype = type_pair.second;
351,420✔
4781
            cols[col].vc_collator = vd->vd_collate;
351,420✔
4782
            cols[col].vc_comment = vd->vd_description;
351,420✔
4783
        }
4784
    }
43,996✔
4785

4786
    void get_foreign_keys(
35,478✔
4787
        std::unordered_set<std::string>& keys_inout) const override
4788
    {
4789
        log_vtab_impl::get_foreign_keys(keys_inout);
35,478✔
4790

4791
        for (const auto& elf_value_def : this->elt_format->elf_value_defs) {
511,272✔
4792
            if (elf_value_def.second->vd_meta.lvm_foreign_key
475,794✔
4793
                || elf_value_def.second->vd_meta.lvm_identifier)
475,794✔
4794
            {
4795
                keys_inout.emplace(elf_value_def.first.to_string());
173,691✔
4796
            }
4797
        }
4798
    }
35,478✔
4799

4800
    bool next(log_cursor& lc, logfile_sub_source& lss) override
3,476✔
4801
    {
4802
        if (lc.is_eof()) {
3,476✔
4803
            return true;
×
4804
        }
4805

4806
        content_line_t cl(lss.at(lc.lc_curr_line));
3,476✔
4807
        auto* lf = lss.find_file_ptr(cl);
3,476✔
4808
        auto lf_iter = lf->begin() + cl;
3,476✔
4809
        if (lf_iter->is_continued()) {
3,476✔
4810
            return false;
×
4811
        }
4812

4813
        if (lf->get_format_name() == this->lfvi_format->get_name()) {
3,476✔
4814
            return true;
3,470✔
4815
        }
4816

4817
        return false;
6✔
4818
    }
4819

4820
    void extract(logfile* lf,
3,385✔
4821
                 uint64_t line_number,
4822
                 string_attrs_t& sa,
4823
                 logline_value_vector& values) override
4824
    {
4825
        auto format = lf->get_format();
3,385✔
4826

4827
        sa.clear();
3,385✔
4828
        format->annotate(lf, line_number, sa, values);
3,385✔
4829
    }
3,385✔
4830

4831
    const external_log_format* elt_format;
4832
    line_range elt_container_body;
4833
};
4834

4835
std::shared_ptr<log_vtab_impl>
4836
external_log_format::get_vtab_impl() const
43,604✔
4837
{
4838
    return std::make_shared<external_log_table>(this->shared_from_this());
43,604✔
4839
}
4840

4841
std::shared_ptr<log_format>
4842
external_log_format::specialized(int fmt_lock)
508✔
4843
{
4844
    auto retval = std::make_shared<external_log_format>(*this);
508✔
4845

4846
    retval->lf_specialized = true;
508✔
4847
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
508✔
4848
        this->jlf_parse_context
4849
            = std::make_shared<yajlpp_parse_context>(this->elf_name);
47✔
4850
        this->jlf_yajl_handle.reset(
47✔
4851
            yajl_alloc(&this->jlf_parse_context->ypc_callbacks,
47✔
4852
                       nullptr,
4853
                       this->jlf_parse_context.get()),
47✔
4854
            yajl_handle_deleter());
4855
        yajl_config(this->jlf_yajl_handle.get(), yajl_dont_validate_strings, 1);
47✔
4856
        this->jlf_cached_line.reserve(16 * 1024);
47✔
4857
    }
4858

4859
    this->elf_specialized_value_defs_state = *this->elf_value_defs_state;
508✔
4860

4861
    return retval;
1,016✔
4862
}
508✔
4863

4864
log_format::match_name_result
4865
external_log_format::match_name(const std::string& filename)
846,752✔
4866
{
4867
    if (this->elf_filename_pcre.pp_value == nullptr) {
846,752✔
4868
        return name_matched{};
845,369✔
4869
    }
4870

4871
    if (this->elf_filename_pcre.pp_value->find_in(filename)
2,766✔
4872
            .ignore_error()
2,766✔
4873
            .has_value())
1,383✔
4874
    {
4875
        return name_matched{};
238✔
4876
    }
4877

4878
    return name_mismatched{
2,290✔
4879
        this->elf_filename_pcre.pp_value->match_partial(filename),
2,290✔
4880
        this->elf_filename_pcre.pp_value->get_pattern(),
1,145✔
4881
    };
1,145✔
4882
}
4883

4884
auto
4885
external_log_format::value_line_count(scan_batch_context& sbc,
223,576✔
4886
                                      const value_def* vd,
4887
                                      bool top_level,
4888
                                      std::optional<double> val,
4889
                                      const unsigned char* str,
4890
                                      ssize_t len,
4891
                                      yajl_string_props_t* props)
4892
    -> value_line_count_result
4893
{
4894
    value_line_count_result retval;
223,576✔
4895

4896
    if (vd == nullptr) {
223,576✔
4897
        if (this->jlf_hide_extra || !top_level) {
208,074✔
4898
            retval.vlcr_count = 0;
194,245✔
4899
        }
4900

4901
        return retval;
208,074✔
4902
    }
4903

4904
    if (str != nullptr && props != nullptr && !val) {
15,502✔
4905
        auto frag = string_fragment::from_bytes(str, len);
13,845✔
4906
        while (frag.endswith("\n")) {
14,014✔
4907
            frag.pop_back();
169✔
4908
            props->line_feeds -= 1;
169✔
4909
        }
4910
        retval.vlcr_has_ansi |= props->has_ansi;
13,845✔
4911
        retval.vlcr_count += props->line_feeds;
13,845✔
4912
    }
4913

4914
    if (vd->vd_meta.lvm_values_index) {
15,502✔
4915
        auto& lvs = sbc.sbc_value_stats[vd->vd_meta.lvm_values_index.value()];
6,538✔
4916
        if (len > lvs.lvs_width) {
6,538✔
4917
            lvs.lvs_width = len;
3,428✔
4918
        }
4919
        if (val) {
6,538✔
4920
            lvs.add_value(val.value());
168✔
4921
        }
4922
    }
4923

4924
    if (vd->vd_line_format_index) {
15,502✔
4925
        retval.vlcr_line_format_count += 1;
3,205✔
4926
        retval.vlcr_count -= 1;
3,205✔
4927
        retval.vlcr_line_format_index = vd->vd_line_format_index;
3,205✔
4928
    }
4929
    if (vd->vd_meta.is_hidden()) {
15,502✔
4930
        retval.vlcr_count = 0;
3,090✔
4931
        return retval;
3,090✔
4932
    }
4933

4934
    return retval;
12,412✔
4935
}
4936

4937
log_level_t
4938
external_log_format::convert_level(string_fragment sf,
191,818✔
4939
                                   scan_batch_context* sbc) const
4940
{
4941
    auto retval = LEVEL_INFO;
191,818✔
4942

4943
    if (sf.is_valid()) {
191,818✔
4944
        if (sbc != nullptr) {
150,318✔
4945
            auto ssm_res = sbc->sbc_level_cache.lookup(sf);
9,301✔
4946
            if (ssm_res.has_value()) {
9,301✔
4947
                return static_cast<log_level_t>(ssm_res.value());
4,106✔
4948
            }
4949
        }
4950

4951
        if (this->elf_level_patterns.empty()) {
146,212✔
4952
            retval = string2level(sf.data(), sf.length());
32,515✔
4953
        } else {
4954
            for (const auto& elf_level_pattern : this->elf_level_patterns) {
306,496✔
4955
                if (elf_level_pattern.second.lp_pcre.pp_value
560,994✔
4956
                        ->find_in(sf, PCRE2_NO_UTF_CHECK)
560,994✔
4957
                        .ignore_error()
560,994✔
4958
                        .has_value())
280,497✔
4959
                {
4960
                    retval = elf_level_pattern.first;
87,698✔
4961
                    break;
87,698✔
4962
                }
4963
            }
4964
        }
4965

4966
        if (sbc != nullptr
146,212✔
4967
            && sf.length() <= lnav::small_string_map::MAX_KEY_SIZE)
146,212✔
4968
        {
4969
            sbc->sbc_level_cache.insert(sf, retval);
4,547✔
4970
        }
4971
    }
4972

4973
    return retval;
187,712✔
4974
}
4975

4976
logline_value_meta
4977
external_log_format::get_value_meta(intern_string_t field_name,
15,244✔
4978
                                    value_kind_t kind)
4979
{
4980
    const auto iter = this->elf_value_defs.find(field_name);
15,244✔
4981
    if (iter == this->elf_value_defs.end()) {
15,244✔
4982
        auto retval = logline_value_meta(
4983
            field_name, kind, logline_value_meta::external_column{}, this);
967✔
4984

4985
        retval.lvm_hidden = this->jlf_hide_extra;
967✔
4986
        return retval;
967✔
4987
    }
967✔
4988

4989
    auto lvm = iter->second->vd_meta;
14,277✔
4990

4991
    lvm.lvm_kind = kind;
14,277✔
4992
    return lvm;
14,277✔
4993
}
14,277✔
4994

4995
logline_value_meta
4996
external_log_format::get_value_meta(yajlpp_parse_context* ypc,
2,398✔
4997
                                    const value_def* vd,
4998
                                    value_kind_t kind)
4999
{
5000
    if (vd == nullptr) {
2,398✔
5001
        auto retval = logline_value_meta(
5002
            ypc->get_path(), kind, logline_value_meta::external_column{}, this);
57✔
5003

5004
        retval.lvm_hidden = this->jlf_hide_extra;
57✔
5005
        return retval;
57✔
5006
    }
57✔
5007

5008
    auto lvm = vd->vd_meta;
2,341✔
5009

5010
    lvm.lvm_kind = kind;
2,341✔
5011
    return lvm;
2,341✔
5012
}
2,341✔
5013

5014
void
5015
external_log_format::json_append(const log_format_file_state& lffs,
8,911✔
5016
                                 const json_format_element& jfe,
5017
                                 const value_def* vd,
5018
                                 const string_fragment& sf)
5019
{
5020
    if (jfe.jfe_align == json_format_element::align_t::RIGHT) {
8,911✔
5021
        auto sf_width = sf.column_width();
346✔
5022
        if (sf_width < jfe.jfe_min_width) {
346✔
5023
            this->json_append_to_cache(jfe.jfe_min_width - sf_width);
×
5024
        } else if (jfe.jfe_auto_width && vd != nullptr
32✔
5025
                   && sf_width
378✔
5026
                       < lffs.lffs_value_stats[vd->vd_meta.lvm_values_index
32✔
5027
                                                   .value()]
32✔
5028
                             .lvs_width)
32✔
5029
        {
5030
            this->json_append_to_cache(
8✔
5031
                lffs.lffs_value_stats[vd->vd_meta.lvm_values_index.value()]
8✔
5032
                    .lvs_width
8✔
5033
                - sf_width);
8✔
5034
        }
5035
    }
5036
    this->json_append_to_cache(sf.data(), sf.length());
8,911✔
5037
    if ((jfe.jfe_align == json_format_element::align_t::LEFT
8,911✔
5038
         || jfe.jfe_align == json_format_element::align_t::NONE)
8,853✔
5039
        && (jfe.jfe_min_width > 0 || jfe.jfe_auto_width))
8,565✔
5040
    {
5041
        auto sf_width = sf.column_width();
1,226✔
5042
        if (sf_width < jfe.jfe_min_width) {
1,226✔
5043
            this->json_append_to_cache(jfe.jfe_min_width - sf_width);
369✔
5044
        } else if (jfe.jfe_auto_width && vd != nullptr
732✔
5045
                   && sf_width
1,589✔
5046
                       < lffs.lffs_value_stats[vd->vd_meta.lvm_values_index
644✔
5047
                                                   .value()]
644✔
5048
                             .lvs_width)
644✔
5049
        {
5050
            this->json_append_to_cache(
×
5051
                lffs.lffs_value_stats[vd->vd_meta.lvm_values_index.value()]
×
5052
                    .lvs_width
×
5053
                - sf_width);
×
5054
        }
5055
    }
5056
}
8,911✔
5057

5058
intern_string_t
5059
external_log_format::get_pattern_name(const pattern_locks& pl,
50✔
5060
                                      uint64_t line_number) const
5061
{
5062
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
50✔
5063
        static auto structured = intern_string::lookup("structured");
5064

5065
        return structured;
×
5066
    }
5067
    auto pat_index = pl.pattern_index_for_line(line_number);
50✔
5068
    return this->elf_pattern_order[pat_index]->p_name;
50✔
5069
}
5070

5071
std::string
5072
log_format::get_pattern_path(const pattern_locks& pl,
×
5073
                             uint64_t line_number) const
5074
{
5075
    auto pat_index = pl.pattern_index_for_line(line_number);
×
5076
    return fmt::format(FMT_STRING("builtin ({})"), pat_index);
×
5077
}
5078

5079
intern_string_t
5080
log_format::get_pattern_name(const pattern_locks& pl,
6✔
5081
                             uint64_t line_number) const
5082
{
5083
    char pat_str[128];
5084

5085
    auto pat_index = pl.pattern_index_for_line(line_number);
6✔
5086
    auto to_n_res = fmt::format_to_n(
×
5087
        pat_str, sizeof(pat_str) - 1, FMT_STRING("builtin ({})"), pat_index);
18✔
5088
    pat_str[to_n_res.size] = '\0';
6✔
5089
    return intern_string::lookup(pat_str);
12✔
5090
}
5091

5092
std::shared_ptr<log_format>
5093
log_format::find_root_format(const char* name)
1,276✔
5094
{
5095
    auto& fmts = get_root_formats();
1,276✔
5096
    for (auto& lf : fmts) {
49,458✔
5097
        if (lf->get_name() == name) {
49,458✔
5098
            return lf;
1,276✔
5099
        }
5100
    }
5101
    return nullptr;
×
5102
}
5103

5104
exttm
5105
log_format::tm_for_display(logfile::iterator ll, string_fragment sf)
579✔
5106
{
5107
    auto adjusted_time = ll->get_timeval();
579✔
5108
    exttm retval;
579✔
5109

5110
    retval.et_nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(
579✔
5111
                         std::chrono::microseconds{adjusted_time.tv_usec})
×
5112
                         .count();
579✔
5113
    if (this->lf_timestamp_flags & ETF_NANOS_SET) {
579✔
5114
        timeval actual_tv;
5115
        exttm tm;
×
5116
        if (this->lf_date_time.scan(sf.data(),
×
5117
                                    sf.length(),
×
5118
                                    this->get_timestamp_formats(),
5119
                                    &tm,
5120
                                    actual_tv,
5121
                                    false))
5122
        {
5123
            adjusted_time.tv_usec = actual_tv.tv_usec;
×
5124
            retval.et_nsec = tm.et_nsec;
×
5125
        }
5126
    }
5127
    gmtime_r(&adjusted_time.tv_sec, &retval.et_tm);
579✔
5128
    retval.et_flags = this->lf_timestamp_flags;
579✔
5129
    if (this->lf_timestamp_flags & ETF_ZONE_SET
579✔
5130
        && this->lf_date_time.dts_zoned_to_local)
489✔
5131
    {
5132
        retval.et_flags &= ~ETF_Z_IS_UTC;
489✔
5133
    }
5134
    retval.et_gmtoff = this->lf_date_time.dts_local_offset_cache;
579✔
5135

5136
    return retval;
1,158✔
5137
}
5138

5139
pattern_for_lines::pattern_for_lines(uint32_t pfl_line, uint32_t pfl_pat_index)
2,900✔
5140
    : pfl_line(pfl_line), pfl_pat_index(pfl_pat_index)
2,900✔
5141
{
5142
}
2,900✔
5143

5144
void
5145
logline_value_stats::merge(const logline_value_stats& other)
15,233✔
5146
{
5147
    if (other.lvs_count == 0) {
15,233✔
5148
        return;
14,088✔
5149
    }
5150

5151
    require(other.lvs_min_value <= other.lvs_max_value);
1,145✔
5152

5153
    if (other.lvs_width > this->lvs_width) {
1,145✔
5154
        this->lvs_width = other.lvs_width;
764✔
5155
    }
5156
    if (other.lvs_min_value < this->lvs_min_value) {
1,145✔
5157
        this->lvs_min_value = other.lvs_min_value;
791✔
5158
    }
5159
    if (other.lvs_max_value > this->lvs_max_value) {
1,145✔
5160
        this->lvs_max_value = other.lvs_max_value;
1,074✔
5161
    }
5162
    this->lvs_count += other.lvs_count;
1,145✔
5163
    this->lvs_total += other.lvs_total;
1,145✔
5164
    this->lvs_tdigest.insert(other.lvs_tdigest);
1,145✔
5165
    ensure(this->lvs_count >= 0);
1,145✔
5166
    ensure(this->lvs_min_value <= this->lvs_max_value);
1,145✔
5167
}
5168

5169
void
5170
logline_value_stats::add_value(double value)
31,433✔
5171
{
5172
    if (value < this->lvs_min_value) {
31,433✔
5173
        this->lvs_min_value = value;
1,668✔
5174
    }
5175
    if (value > this->lvs_max_value) {
31,433✔
5176
        this->lvs_max_value = value;
2,360✔
5177
    }
5178
    this->lvs_count += 1;
31,433✔
5179
    this->lvs_total += value;
31,433✔
5180
    this->lvs_tdigest.insert(value);
31,433✔
5181
}
31,433✔
5182

5183
std::vector<logline_value_meta>
5184
external_log_format::get_value_metadata() const
8,862✔
5185
{
5186
    std::vector<logline_value_meta> retval;
8,862✔
5187

5188
    for (const auto& vd : this->elf_value_def_order) {
93,051✔
5189
        retval.emplace_back(vd->vd_meta);
84,189✔
5190
    }
5191

5192
    return retval;
8,862✔
5193
}
×
5194

5195
std::optional<size_t>
5196
external_log_format::stats_index_for_value(const intern_string_t& name) const
72✔
5197
{
5198
    const auto iter = this->elf_value_defs.find(name);
72✔
5199
    if (iter != this->elf_value_defs.end()
72✔
5200
        && iter->second->vd_meta.lvm_values_index)
72✔
5201
    {
5202
        return iter->second->vd_meta.lvm_values_index.value();
72✔
5203
    }
5204

5205
    return std::nullopt;
×
5206
}
5207

5208
std::string
5209
external_log_format::get_pattern_regex(const pattern_locks& pl,
9✔
5210
                                       uint64_t line_number) const
5211
{
5212
    if (this->elf_type != elf_type_t::ELF_TYPE_TEXT) {
9✔
5213
        return "";
2✔
5214
    }
5215
    auto pat_index = pl.pattern_index_for_line(line_number);
8✔
5216
    return this->elf_pattern_order[pat_index]->p_pcre.pp_value->get_pattern();
8✔
5217
}
5218

5219
bool
5220
external_log_format::hide_field(const intern_string_t field_name, bool val)
12✔
5221
{
5222
    const auto vd_iter = this->elf_value_defs.find(field_name);
12✔
5223
    if (vd_iter == this->elf_value_defs.end()) {
12✔
5224
        log_warning("field to hide not found: %s.%s",
1✔
5225
                    this->elf_name.c_str(),
5226
                    field_name.c_str());
5227
        return false;
1✔
5228
    }
5229

5230
    vd_iter->second->vd_meta.lvm_user_hidden = val;
11✔
5231
    if (this->elf_type == elf_type_t::ELF_TYPE_JSON) {
11✔
5232
        bool found = false;
2✔
5233

5234
        if (!field_name.to_string_fragment().find('#')) {
2✔
5235
            for (const auto& jfe : this->jlf_line_format) {
18✔
5236
                if (jfe.jfe_value.pp_value == field_name) {
17✔
5237
                    log_debug(
×
5238
                        "hide-field not triggering rebuild since it is in "
5239
                        "line-format: %s.%s",
5240
                        this->elf_name.c_str(),
5241
                        field_name.c_str());
5242
                    found = true;
×
5243
                    break;
×
5244
                }
5245
            }
5246
        }
5247
        if (!found) {
2✔
5248
            log_info("format field %s.%s changed, rebuilding",
2✔
5249
                     this->elf_name.get(),
5250
                     field_name.get());
5251
            this->elf_value_defs_state->vds_generation += 1;
2✔
5252
        }
5253
    }
5254
    return true;
11✔
5255
}
5256

5257
bool
5258
external_log_format::format_changed()
2,584✔
5259
{
5260
    if (this->elf_specialized_value_defs_state.vds_generation
5,168✔
5261
        != this->elf_value_defs_state->vds_generation)
2,584✔
5262
    {
5263
        this->elf_specialized_value_defs_state = *this->elf_value_defs_state;
2✔
5264
        this->jlf_cached_offset = -1;
2✔
5265
        return true;
2✔
5266
    }
5267

5268
    return false;
2,582✔
5269
}
5270

5271
bool
5272
format_tag_def::path_restriction::matches(const char* fn) const
5✔
5273
{
5274
    return fnmatch(this->p_glob.c_str(), fn, 0) == 0;
5✔
5275
}
5276

5277
bool
5278
format_partition_def::path_restriction::matches(const char* fn) const
5✔
5279
{
5280
    return fnmatch(this->p_glob.c_str(), fn, 0) == 0;
5✔
5281
}
5282

5283
int
5284
pattern_locks::pattern_index_for_line(uint64_t line_number) const
6,794✔
5285
{
5286
    if (this->pl_lines.empty()) {
6,794✔
5287
        return -1;
×
5288
    }
5289

5290
    auto iter
5291
        = std::lower_bound(this->pl_lines.cbegin(),
6,794✔
5292
                           this->pl_lines.cend(),
5293
                           line_number,
5294
                           [](const pattern_for_lines& pfl, uint32_t line) {
6,853✔
5295
                               return pfl.pfl_line < line;
6,853✔
5296
                           });
5297

5298
    if (iter == this->pl_lines.end() || iter->pfl_line != line_number) {
6,794✔
5299
        --iter;
6,166✔
5300
    }
5301

5302
    return iter->pfl_pat_index;
6,794✔
5303
}
5304

5305
/* XXX */
5306
#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