-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogNexus_compress.cpp
More file actions
2389 lines (2174 loc) · 87.8 KB
/
Copy pathLogNexus_compress.cpp
File metadata and controls
2389 lines (2174 loc) · 87.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <algorithm>
#include <atomic>
#include <cctype>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <cstdlib>
#include <deque>
#include <filesystem>
#include <fstream>
#include <functional>
#include <future>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <queue>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
namespace fs = std::filesystem;
struct Pcre2Deleter {
void operator()(pcre2_code *re) const {
if (re)
pcre2_code_free(re);
}
};
using Pcre2UniquePtr = std::unique_ptr<pcre2_code, Pcre2Deleter>;
// ===== Threshold Parameters (for build_variable_tree) =====
double g_threshold_ratio = 0.02; // Recommended fixed threshold for untuned use
bool g_skip_stage2 = false; // RQ3 ablation: skip Variable Subtree Encoding
bool g_single_archive_mode = false; // RQ2: single-archive mode (no chunking)
bool g_s1_lzma_mode = false; // Stage 1 plus generic LZMA ablation
// ============================================================
// Optional counters for the Stage-2 case study. They are disabled unless the
// experiment launcher explicitly sets LOGNEXUS_CASE_STUDY_COUNTERS=1.
std::mutex g_case_study_counter_mutex;
bool case_study_counter_enabled() {
const char *env = std::getenv("LOGNEXUS_CASE_STUDY_COUNTERS");
return env && std::string(env) != "0";
}
void append_case_study_counter(const fs::path &base_output_dir,
const std::string &dataset_type,
int chunk_id, const std::string &mode,
unsigned long long log_count,
unsigned long long stage1_vars,
unsigned long long stage1_var_bytes,
unsigned long long stage2_encoded_vars,
unsigned long long stage2_encoded_var_bytes,
unsigned long long stage3_residual_vars,
unsigned long long stage3_residual_var_bytes) {
std::lock_guard<std::mutex> lock(g_case_study_counter_mutex);
fs::path counter_path = base_output_dir / "case_study_counters.csv";
const bool write_header = !fs::exists(counter_path);
std::ofstream out(counter_path, std::ios::app);
if (!out.is_open())
return;
if (write_header) {
out << "Dataset,Chunk,Mode,Log_Count,Stage1_Vars,Stage1_Var_Bytes,"
"Stage2_Encoded_Vars,Stage2_Encoded_Var_Bytes,"
"Stage3_Residual_Vars,Stage3_Residual_Var_Bytes\n";
}
out << dataset_type << "," << chunk_id << "," << mode << "," << log_count
<< "," << stage1_vars << "," << stage1_var_bytes << ","
<< stage2_encoded_vars << "," << stage2_encoded_var_bytes << ","
<< stage3_residual_vars << "," << stage3_residual_var_bytes << "\n";
}
constexpr uintmax_t SMALL_FILE_PACK_THRESHOLD_BYTES = 32 * 1024;
constexpr char SMALL_FILE_PACK_MAGIC[] = {'L', 'N', 'X', 'P', 'K', '1', '\0'};
struct SmallFilePackConfig {
bool enabled = true;
bool adaptive = false;
uintmax_t threshold_bytes = SMALL_FILE_PACK_THRESHOLD_BYTES;
size_t adaptive_min_files = 64;
uintmax_t adaptive_min_saved_bytes = 64 * 1024;
};
std::string trim(std::string_view str) {
size_t first = str.find_first_not_of(" \t\n\r");
if (std::string::npos == first)
return "";
size_t last = str.find_last_not_of(" \t\n\r");
return std::string(str.substr(first, (last - first + 1)));
}
std::vector<std::string> split(std::string_view s, char delimiter,
int maxsplit = -1) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream{std::string(s)};
int count = 0;
while (std::getline(tokenStream, token, delimiter)) {
if (maxsplit != -1 && count++ >= maxsplit) {
std::string rest;
std::getline(tokenStream, rest);
tokens.back() += delimiter;
tokens.back() += token;
if (!rest.empty()) {
tokens.back() += delimiter;
tokens.back() += rest;
}
break;
}
tokens.push_back(token);
}
return tokens;
}
std::vector<std::string> split_stream(std::string_view s) {
std::vector<std::string> tokens;
std::stringstream ss{std::string(s)};
std::string token;
while (ss >> token)
tokens.push_back(token);
return tokens;
}
bool has_numbers(std::string_view s) {
return std::any_of(s.begin(), s.end(), ::isdigit);
}
long long ip_to_int(std::string_view ip_str) {
std::string s(ip_str);
std::stringstream ss(s);
std::string segment;
std::stringstream padded_ss;
while (std::getline(ss, segment, '.')) {
padded_ss << std::setw(3) << std::setfill('0') << segment;
}
try {
return std::stoll(padded_ss.str());
} catch (const std::exception &) {
return 0;
}
}
long long string_to_padded_int(const std::string &input,
const std::vector<int> &padding_widths,
char delimiter = 0) {
std::vector<std::string> parts;
if (delimiter != 0) {
parts = split(input, delimiter);
} else {
std::string current_num;
for (char c : input) {
if (isdigit(c))
current_num += c;
}
if (!current_num.empty())
parts.push_back(current_num);
}
std::stringstream ss;
for (size_t i = 0; i < parts.size(); ++i) {
int width = (i < padding_widths.size())
? padding_widths[i]
: (padding_widths.empty() ? 0 : padding_widths.back());
ss << std::setw(width) << std::setfill('0') << parts[i];
}
try {
if (ss.str().empty())
return 0;
return std::stoll(ss.str());
} catch (const std::exception &) {
return 0;
}
}
long long digit_runs_to_padded_int(const std::string &input,
const std::vector<int> &padding_widths) {
std::vector<std::string> parts;
std::string current;
for (unsigned char c : input) {
if (std::isdigit(c)) {
current.push_back(static_cast<char>(c));
} else if (!current.empty()) {
parts.push_back(current);
current.clear();
}
}
if (!current.empty())
parts.push_back(current);
std::stringstream ss;
for (size_t i = 0; i < parts.size(); ++i) {
int width = (i < padding_widths.size())
? padding_widths[i]
: (padding_widths.empty() ? 0 : padding_widths.back());
ss << std::setw(width) << std::setfill('0') << parts[i];
}
try {
if (ss.str().empty())
return 0;
return std::stoll(ss.str());
} catch (const std::exception &) {
return 0;
}
}
long long numeric_string_to_long(const std::string &s) {
std::string num_str;
std::copy_if(s.begin(), s.end(), std::back_inserter(num_str), ::isdigit);
if (num_str.empty())
return 0;
try {
return std::stoll(num_str);
} catch (const std::exception &) {
return 0;
}
}
unsigned long long encode_linux_dt_shape_flag(const std::string &raw_value) {
auto space_pos = raw_value.find(' ');
if (space_pos == std::string::npos)
return 1ULL;
return space_pos == 1 ? 0ULL : 1ULL;
}
bool uses_dt_shape(const std::string &dataset_type) {
return dataset_type == "Linux" || dataset_type == "Apache" ||
dataset_type == "Mac" || dataset_type == "Thunderbird";
}
unsigned long long encode_colon_field_widths(const std::string &raw_value) {
std::vector<unsigned long long> widths;
unsigned long long current_width = 0;
bool in_digits = false;
for (unsigned char c : raw_value) {
if (std::isdigit(c)) {
++current_width;
in_digits = true;
} else if (c == ':' && in_digits) {
widths.push_back(current_width);
current_width = 0;
in_digits = false;
} else {
current_width = 0;
in_digits = false;
}
}
if (in_digits)
widths.push_back(current_width);
while (widths.size() < 4)
widths.push_back(0);
return widths[0] * 1000ULL + widths[1] * 100ULL + widths[2] * 10ULL +
widths[3];
}
// --- Core data structures ---
struct Record {
long long line_id;
std::vector<std::string> vars;
};
struct Node {
std::vector<std::unique_ptr<Node>> children;
std::unordered_map<std::string, Node *> child_dict;
int depth = 0;
int pos = -1;
std::string digitOrtoken;
long long cnt = 0;
std::string pathID;
std::vector<Record> log_records;
Node(std::string token = "", int d = 0, int p = -1)
: depth(d), pos(p), digitOrtoken(std::move(token)) {}
void add_child(std::unique_ptr<Node> child_node) {
child_dict[child_node->digitOrtoken] = child_node.get();
children.push_back(std::move(child_node));
}
Node *find_child(std::string_view token) {
auto it = child_dict.find(std::string(token));
return (it != child_dict.end()) ? it->second : nullptr;
}
};
using ExtractedColumns =
std::unordered_map<std::string, std::vector<long long>>;
constexpr const char *LINUX_DT_SHAPE_PLACEHOLDER = "<dt_shape>";
constexpr const char *TM_SHAPE_PLACEHOLDER = "<tm_shape>";
struct FinalGroupData {
std::vector<Record> records;
std::vector<std::string> template_path;
};
struct UnclassifiedVar {
int pos;
std::string token;
};
struct UnclassifiedLogInfo {
long long line_id;
std::string path_id;
std::string tree_node_id;
std::vector<UnclassifiedVar> unmatched_vars;
};
// --- Encoders ---
std::vector<char> elastic_encoder(long long num) {
std::vector<char> buffer;
uint64_t cur = (static_cast<uint64_t>(num) << 1) ^ (num >> 63);
while (true) {
if (cur < 0x80) {
buffer.push_back(static_cast<char>(cur));
break;
} else {
buffer.push_back(static_cast<char>((cur & 0x7f) | 0x80));
cur >>= 7;
}
}
return buffer;
}
std::vector<char> elastic_encoder_unsigned(unsigned long long num) {
std::vector<char> buffer;
unsigned long long cur = num;
while (true) {
if (cur < 0x80) {
buffer.push_back(static_cast<char>(cur));
break;
} else {
buffer.push_back(static_cast<char>((cur & 0x7f) | 0x80));
cur >>= 7;
}
}
return buffer;
}
constexpr char LINE_PREFIX_MAGIC[] = "LNXLP1";
constexpr char TREE_UNSIGNED_MAGIC[] = "LNXU1";
void write_encoded_unsigned(std::ostream &out, unsigned long long value) {
auto encoded = elastic_encoder_unsigned(value);
out.write(encoded.data(), encoded.size());
}
size_t common_prefix_length(std::string_view a, std::string_view b) {
const size_t n = std::min(a.size(), b.size());
size_t i = 0;
while (i < n && a[i] == b[i])
++i;
return i;
}
void write_prefix_encoded_templates(
const fs::path &path,
const std::vector<std::pair<std::string, long long>> &templates) {
std::vector<char> io_buffer(1 << 20);
std::ofstream out;
out.rdbuf()->pubsetbuf(io_buffer.data(),
static_cast<std::streamsize>(io_buffer.size()));
out.open(path, std::ios::binary);
if (!out.is_open())
return;
out.write(LINE_PREFIX_MAGIC, sizeof(LINE_PREFIX_MAGIC) - 1);
std::string_view previous;
for (const auto &entry : templates) {
std::string_view line(entry.first);
const size_t prefix = common_prefix_length(previous, line);
const size_t suffix_len = line.size() - prefix;
write_encoded_unsigned(out, static_cast<unsigned long long>(prefix));
write_encoded_unsigned(out, static_cast<unsigned long long>(suffix_len));
out.write(line.data() + prefix, suffix_len);
previous = line;
}
}
class ThreadPool {
public:
ThreadPool(size_t);
template <class F, class... Args>
auto enqueue(F &&f, Args &&...args)
-> std::future<typename std::invoke_result<F, Args...>::type>;
~ThreadPool();
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
ThreadPool::ThreadPool(size_t threads) : stop(false) {
for (size_t i = 0; i < threads; ++i)
workers.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(
lock, [this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
template <class F, class... Args>
auto ThreadPool::enqueue(F &&f, Args &&...args)
-> std::future<typename std::invoke_result<F, Args...>::type> {
using return_type = typename std::invoke_result<F, Args...>::type;
auto task = std::make_shared<std::packaged_task<return_type()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
if (stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return res;
}
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers)
worker.join();
}
// =========================================================================
// Processor class (contains specialized logic)
// =========================================================================
struct RegexPattern {
Pcre2UniquePtr compiled_regex;
std::string placeholder;
RegexPattern(Pcre2UniquePtr regex, std::string ph)
: compiled_regex(std::move(regex)), placeholder(std::move(ph)) {}
RegexPattern(const RegexPattern &) = delete;
RegexPattern &operator=(const RegexPattern &) = delete;
RegexPattern(RegexPattern &&) = default;
RegexPattern &operator=(RegexPattern &&) = default;
};
class ChunkProcessor {
public:
ChunkProcessor(const std::string &dataset_type);
std::pair<std::unique_ptr<Node>, ExtractedColumns>
process_log_chunk(int chunk_id, const std::vector<std::string> &log_lines,
size_t chunk_size,
int stage_1_threads = 4);
private:
void initialize_maps_and_regex();
struct SubChunkResult {
std::unique_ptr<Node> partial_tree;
ExtractedColumns extracted_columns;
};
SubChunkResult
process_sub_chunk(int sub_chunk_id,
const std::vector<std::string> &sub_chunk_lines,
size_t base_line_id);
void merge_extracted_columns(ExtractedColumns &target,
ExtractedColumns &&source);
void iterative_merge(Node *target_root, Node *source_root);
std::string dataset_type_;
std::unordered_map<std::string, std::vector<RegexPattern>> REGEX_MAP;
Pcre2UniquePtr MONTH_REGEX;
Pcre2UniquePtr DAY_REGEX;
std::unordered_map<std::string, int> MONTH_MAP;
std::unordered_map<std::string, int> DAY_MAP;
Pcre2UniquePtr extraction_regex;
};
ChunkProcessor::ChunkProcessor(const std::string &dataset_type)
: dataset_type_(dataset_type) {
initialize_maps_and_regex();
}
void ChunkProcessor::initialize_maps_and_regex() {
MONTH_MAP = {{"Jan", 1}, {"Feb", 2}, {"Mar", 3}, {"Apr", 4},
{"May", 5}, {"Jun", 6}, {"Jul", 7}, {"Aug", 8},
{"Sep", 9}, {"Oct", 10}, {"Nov", 11}, {"Dec", 12}};
DAY_MAP = {{"Sun", 1}, {"Mon", 2}, {"Tue", 3}, {"Wed", 4},
{"Thu", 5}, {"Fri", 6}, {"Sat", 7}};
auto compile_regex = [](const char *pattern) -> Pcre2UniquePtr {
int error_code;
PCRE2_SIZE error_offset;
pcre2_code *re = pcre2_compile((PCRE2_SPTR)pattern, PCRE2_ZERO_TERMINATED,
0, &error_code, &error_offset, nullptr);
if (!re) {
PCRE2_UCHAR buffer[256];
pcre2_get_error_message(error_code, buffer, sizeof(buffer));
throw std::runtime_error("PCRE2 compilation failed at offset " +
std::to_string(error_offset) + ": " +
(char *)buffer);
}
return Pcre2UniquePtr(re);
};
MONTH_REGEX =
compile_regex(R"(\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\b)");
DAY_REGEX = compile_regex(R"(\b(Sun|Mon|Tue|Wed|Thu|Fri|Sat)\b)");
std::map<std::string, std::vector<std::pair<const char *, const char *>>>
raw_regex = {
{"Android",
{{R"((?<!\S)(?:\d{1,3}\.){3}\d{1,3}(?!\S))", "<I>"},
{R"((\d{4})-(\d{2})-(\d{2}) (\d{1,2}):(\d{2}):(\d{1,2}):(\d{3}))", "<YmDtm>"},
{R"((?<![\d-])(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(?![:\d]))", "<mDt>"}}},
{"Apache",
{{R"((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))", "<I>"},
{R"((\d{1,2}) (\d+):(\d+):(\d+))", "<dt>"}}},
{"BGL",
{{R"((\d+)-(\d+)-(\d+)-(\d+)\.(\d+)\.(\d+))", "<E>"},
{R"((?<![A-Za-z0-9:])(\d{1,2}):(\d{2}):(\d{2})(?![A-Za-z0-9:]))", "<t>"},
{R"((\d{4})\.(\d{2})\.(\d{2}))", "<D>"},
{R"(\.(\d{6}))", "<m>"},
{R"(1\d{9})", "<S>"}}},
{"Hadoop",
{{R"((\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+),(\d+))", "<Dtm>"}}},
{"HDFS", {{R"((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))", "<I>"}}},
{"HealthApp", {{R"((\d+):(\d+):(\d+):(\d+))", "<tm>"}}},
{"HPC", {{R"(1\d{9})", "<S>"}}},
{"Linux",
{{R"((?<!\S)(?:\d{1,3}\.){3}\d{1,3}(?!\S))", "<I>"},
{R"((\d{1,2}) (\d{2}):(\d{2}):(\d{2}))", "<dt>"},
{R"(\[(\d+)\]:)", "<P>"}}},
{"Mac",
{{R"((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))", "<I>"},
{R"((\d{1,2}) (\d{2}):(\d{2}):(\d{2}))", "<dt>"},
{R"((\d{2}):(\d{2}):(\d{2})\.(\d{3}))", "<tm>"},
{R"((\d{2}):(\d{2}):(\d{2}))", "<t>"}}},
{"OpenSSH",
{{R"((\d{1,2}) (\d+):(\d+):(\d+))", "<dt>"},
{R"(sshd\[(\d+)\]:)", "<P>"}}},
{"OpenStack",
{{R"((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))", "<I>"},
{R"(\.(\d{4})-(\d{2})-(\d{2})_(\d{2}):(\d{2}):(\d{2}))", "<Dt>"},
{R"((\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3}))",
"<Dtm>"}}},
{"Proxifier", {{R"((\d+)\.(\d+) (\d+):(\d+):(\d+))", "<mDt>"}}},
{"Spark",
{{R"((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))", "<I>"},
{R"((\d{2})\/(\d{2})\/(\d{2}) (\d+):(\d+):(\d+))", "<Dt>"},
{R"((\d+)\.(\d{1}) MB)", "<M>"},
{R"((\d+)\.(\d{1}) KB)", "<K>"},
{R"((\d+)\.(\d{1}) GB)", "<G>"},
{R"((\d+)\.(\d{1}) B)", "<B>"}}},
{"Thunderbird",
{{R"((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))", "<I>"},
{R"((\d{1,2}) (\d+):(\d+):(\d+))", "<dt>"},
{R"((?<!\S)(\d{1,2}):(\d{2}):(\d{2})(?!\S))", "<t>"},
{R"((\d{4})\.(\d{2})\.(\d{2}))", "<D>"},
{R"((?<![A-Za-z0-9_./-])\[(\d+)\]:)", "<P>"},
{R"(1\d{9})", "<S>"}}},
{"Windows",
{{R"((\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+),)", "<Dt>"},
{R"((\d{2}):(\d{2}):(\d{2})\.(\d{3}))", "<tm>"}}},
{"Zookeeper",
{{R"((\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+),(\d+))", "<Dtm>"}}}};
for (const auto &pair : raw_regex) {
std::vector<RegexPattern> patterns;
for (const auto &p : pair.second) {
patterns.emplace_back(compile_regex(p.first), p.second);
}
REGEX_MAP[pair.first] = std::move(patterns);
}
extraction_regex = compile_regex(
R"((?<![A-Za-z0-9+\-])(?:[1-9]\d{1,14})(?![A-Za-z0-9+\-]))");
}
// Sub-chunk processing function
ChunkProcessor::SubChunkResult ChunkProcessor::process_sub_chunk(
int sub_chunk_id, const std::vector<std::string> &sub_chunk_lines,
size_t base_line_id) {
auto partial_tree_root = std::make_unique<Node>();
ExtractedColumns extracted_columns;
const std::vector<RegexPattern> *regex_patterns_ptr =
REGEX_MAP.count(dataset_type_) ? ®EX_MAP.at(dataset_type_) : nullptr;
pcre2_match_data *match_data = pcre2_match_data_create(32, nullptr);
for (size_t local_line_id = 0; local_line_id < sub_chunk_lines.size();
++local_line_id) {
std::string modified_line = trim(sub_chunk_lines[local_line_id]);
if (modified_line.empty())
continue;
if (dataset_type_ == "HDFS") {
auto tokens = split(modified_line, ' ', 3);
if (tokens.size() == 4) {
try {
extracted_columns["<Da>"].push_back(std::stoll(tokens[0]));
extracted_columns["<Ti>"].push_back(std::stoll(tokens[1]));
extracted_columns["<P>"].push_back(std::stoll(tokens[2]));
modified_line = "<Da> <Ti> <P> " + tokens[3];
} catch (const std::exception &) {
}
}
} else if (dataset_type_ == "HPC") {
auto tokens = split(modified_line, ' ', 1);
if (tokens.size() == 2) {
try {
extracted_columns["<Lid>"].push_back(std::stoll(tokens[0]));
modified_line = "<Lid> " + tokens[1];
} catch (const std::exception &) {
}
}
}
std::string temp_line;
PCRE2_SIZE last_match_end = 0;
temp_line.clear();
last_match_end = 0;
while (pcre2_match(MONTH_REGEX.get(), (PCRE2_SPTR)modified_line.c_str(),
modified_line.length(), last_match_end, 0, match_data,
nullptr) >= 0) {
PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
temp_line.append(modified_line, last_match_end,
ovector[0] - last_match_end);
std::string month_str(
modified_line.substr(ovector[2], ovector[3] - ovector[2]));
if (MONTH_MAP.count(month_str)) {
extracted_columns["<X>"].push_back(MONTH_MAP.at(month_str));
temp_line.append("<X>");
} else {
temp_line.append(month_str);
}
last_match_end = ovector[1];
}
temp_line.append(modified_line, last_match_end, std::string::npos);
if (last_match_end > 0)
modified_line = temp_line;
temp_line.clear();
last_match_end = 0;
while (pcre2_match(DAY_REGEX.get(), (PCRE2_SPTR)modified_line.c_str(),
modified_line.length(), last_match_end, 0, match_data,
nullptr) >= 0) {
PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
temp_line.append(modified_line, last_match_end,
ovector[0] - last_match_end);
std::string day_str(
modified_line.substr(ovector[2], ovector[3] - ovector[2]));
if (DAY_MAP.count(day_str)) {
extracted_columns["<Y>"].push_back(DAY_MAP.at(day_str));
temp_line.append("<Y>");
} else {
temp_line.append(day_str);
}
last_match_end = ovector[1];
}
temp_line.append(modified_line, last_match_end, std::string::npos);
if (last_match_end > 0)
modified_line = temp_line;
if (regex_patterns_ptr) {
for (const auto &pattern : *regex_patterns_ptr) {
temp_line.clear();
last_match_end = 0;
while (pcre2_match(pattern.compiled_regex.get(),
(PCRE2_SPTR)modified_line.c_str(),
modified_line.length(), last_match_end, 0,
match_data, nullptr) >= 0) {
PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
temp_line.append(modified_line, last_match_end,
ovector[0] - last_match_end);
std::string match_str(
modified_line.substr(ovector[0], ovector[1] - ovector[0]));
long long value_to_store = 0;
if (pattern.placeholder == "<I>") {
value_to_store = ip_to_int(match_str);
} else if (dataset_type_ == "HealthApp" &&
pattern.placeholder == "<tm>") {
value_to_store = string_to_padded_int(match_str, {2, 2, 2, 3}, ':');
} else if (dataset_type_ == "Android" &&
pattern.placeholder == "<mDt>") {
value_to_store = string_to_padded_int(match_str, {2, 2, 2, 2, 2});
} else if (dataset_type_ == "Android" &&
pattern.placeholder == "<YmDtm>") {
value_to_store =
digit_runs_to_padded_int(match_str, {4, 2, 2, 2, 2, 2, 3});
} else {
value_to_store = numeric_string_to_long(match_str);
}
extracted_columns[pattern.placeholder].push_back(value_to_store);
if (uses_dt_shape(dataset_type_) && pattern.placeholder == "<dt>") {
extracted_columns[LINUX_DT_SHAPE_PLACEHOLDER].push_back(
static_cast<long long>(encode_linux_dt_shape_flag(match_str)));
}
if (dataset_type_ == "HealthApp" && pattern.placeholder == "<tm>") {
extracted_columns[TM_SHAPE_PLACEHOLDER].push_back(
static_cast<long long>(encode_colon_field_widths(match_str)));
}
temp_line.append(pattern.placeholder);
last_match_end = ovector[1];
}
temp_line.append(modified_line, last_match_end, std::string::npos);
if (last_match_end > 0)
modified_line = temp_line;
}
}
long long global_line_id = base_line_id + local_line_id;
std::vector<std::string> logmessageL;
if (dataset_type_ == "HealthApp") {
auto parts = split(modified_line, '|', 3);
if (parts.size() >= 4) {
for (size_t i = 0; i < 3; ++i)
logmessageL.push_back(trim(parts[i]));
auto tail_parts = split_stream(parts[3]);
logmessageL.insert(logmessageL.end(), tail_parts.begin(),
tail_parts.end());
} else {
logmessageL = split_stream(modified_line);
}
} else {
logmessageL = split_stream(modified_line);
}
if (logmessageL.empty())
continue;
Node *current_node = partial_tree_root.get();
std::vector<std::string> initial_vars;
for (const auto &token : logmessageL) {
bool is_wildcard = has_numbers(token);
std::string token_to_find = is_wildcard ? "<*>" : token;
if (is_wildcard) {
initial_vars.push_back(token);
}
Node *child = current_node->find_child(token_to_find);
if (!child) {
auto new_child =
std::make_unique<Node>(token_to_find, current_node->depth + 1);
child = new_child.get();
current_node->add_child(std::move(new_child));
}
current_node = child;
current_node->cnt++;
}
current_node->log_records.push_back(
{global_line_id, std::move(initial_vars)});
}
pcre2_match_data_free(match_data);
return {std::move(partial_tree_root), std::move(extracted_columns)};
}
void ChunkProcessor::merge_extracted_columns(ExtractedColumns &target,
ExtractedColumns &&source) {
for (auto &[placeholder, values] : source) {
auto &target_vec = target[placeholder];
target_vec.insert(target_vec.end(), std::make_move_iterator(values.begin()),
std::make_move_iterator(values.end()));
}
}
void ChunkProcessor::iterative_merge(Node *target_root, Node *source_root) {
if (!source_root)
return;
std::vector<std::pair<Node *, Node *>> stack;
stack.push_back({target_root, source_root});
while (!stack.empty()) {
auto [target_node, source_node] = stack.back();
stack.pop_back();
for (auto &source_child_ptr : source_node->children) {
Node *source_child = source_child_ptr.get();
Node *target_child = target_node->find_child(source_child->digitOrtoken);
if (!target_child) {
auto new_child = std::make_unique<Node>(source_child->digitOrtoken,
target_node->depth + 1);
target_child = new_child.get();
target_node->add_child(std::move(new_child));
}
target_child->cnt += source_child->cnt;
if (!source_child->log_records.empty()) {
target_child->log_records.insert(
target_child->log_records.end(),
std::make_move_iterator(source_child->log_records.begin()),
std::make_move_iterator(source_child->log_records.end()));
}
if (!source_child->children.empty()) {
stack.push_back({target_child, source_child});
}
}
}
}
// === Main processing function: supports intra-chunk parallelism ===
std::pair<std::unique_ptr<Node>, ExtractedColumns>
ChunkProcessor::process_log_chunk(int chunk_id,
const std::vector<std::string> &log_lines,
size_t chunk_size, int stage_1_threads) {
// If data is too small or single-threaded, process sequentially
if (log_lines.size() < 10000 || stage_1_threads <= 1) {
auto result = process_sub_chunk(0, log_lines, chunk_id * chunk_size);
return {std::move(result.partial_tree),
std::move(result.extracted_columns)};
}
// === Intra-chunk parallel processing ===
// RQ2: Different sub_chunk_size calculation based on mode
size_t sub_chunk_size;
if (g_single_archive_mode) {
// Single-archive mode: each thread processes fixed 100K lines
// Exception: if total lines < stage_1_threads * 100K, divide evenly
const size_t threshold = static_cast<size_t>(stage_1_threads) * 100000;
if (log_lines.size() < threshold) {
// Small dataset: divide evenly among threads (same as Chunked Mode)
sub_chunk_size = (log_lines.size() + stage_1_threads - 1) / stage_1_threads;
} else {
// Large dataset: fixed 100K lines per thread to avoid memory explosion
sub_chunk_size = 100000;
}
} else {
// Normal chunked mode: divide chunk evenly among threads
sub_chunk_size = (log_lines.size() + stage_1_threads - 1) / stage_1_threads;
}
const int effective_threads = std::min<int>(
stage_1_threads,
static_cast<int>((log_lines.size() + sub_chunk_size - 1) / sub_chunk_size));
// Calculate total number of sub-chunks
const size_t total_sub_chunks = (log_lines.size() + sub_chunk_size - 1) / sub_chunk_size;
ThreadPool pool(effective_threads);
std::deque<std::future<SubChunkResult>> futures;
auto final_tree_root = std::make_unique<Node>();
ExtractedColumns final_extracted_columns;
auto merge_sub_chunk_result = [&](std::future<SubChunkResult> &future) {
SubChunkResult result = future.get();
iterative_merge(final_tree_root.get(), result.partial_tree.get());
merge_extracted_columns(final_extracted_columns,
std::move(result.extracted_columns));
};
// Keep at most one wave of sub-chunks resident. This mirrors Denum's
// bounded block scheduling and prevents large single archives from queuing
// every 100K-line sub-chunk before merging completed work.
for (size_t i = 0; i < total_sub_chunks; ++i) {
size_t start = i * sub_chunk_size;
if (start >= log_lines.size())
break;
size_t end = std::min(start + sub_chunk_size, log_lines.size());
std::vector<std::string> sub_chunk(log_lines.begin() + start,
log_lines.begin() + end);
size_t base_line_id = chunk_id * chunk_size + start;
futures.push_back(pool.enqueue(
[this, i, sub_chunk = std::move(sub_chunk), base_line_id]() {
return this->process_sub_chunk(static_cast<int>(i), sub_chunk, base_line_id);
}));
if (futures.size() >= static_cast<size_t>(effective_threads)) {
try {
merge_sub_chunk_result(futures.front());
} catch (const std::exception &e) {
std::cerr << "[Chunk " << chunk_id
<< "] Error processing sub-chunk: " << e.what() << std::endl;
}
futures.erase(futures.begin());
}
}
for (auto &future : futures) {
try {
merge_sub_chunk_result(future);
} catch (const std::exception &e) {
std::cerr << "[Chunk " << chunk_id
<< "] Error processing sub-chunk: " << e.what() << std::endl;
}
}
return {std::move(final_tree_root), std::move(final_extracted_columns)};
}
void ensure_directory_exists(const fs::path &path) {
if (!fs::exists(path)) {
try {
fs::create_directories(path);
} catch (const fs::filesystem_error &e) {
throw std::runtime_error("Failed to create directory " + path.string() +
": " + e.what());
}
}
}
void write_u16_le(std::ostream &out, uint16_t value) {
char bytes[2] = {static_cast<char>(value & 0xFF),
static_cast<char>((value >> 8) & 0xFF)};
out.write(bytes, sizeof(bytes));
}
void write_u32_le(std::ostream &out, uint32_t value) {
char bytes[4] = {static_cast<char>(value & 0xFF),
static_cast<char>((value >> 8) & 0xFF),
static_cast<char>((value >> 16) & 0xFF),
static_cast<char>((value >> 24) & 0xFF)};
out.write(bytes, sizeof(bytes));
}
std::string lower_ascii(std::string value) {
std::transform(value.begin(), value.end(), value.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return value;
}
bool env_flag_enabled(const char *name) {
const char *raw = std::getenv(name);
if (!raw || raw[0] == '\0')
return false;
std::string value = lower_ascii(raw);
return !(value == "0" || value == "false" || value == "off" ||
value == "none" || value == "no");
}
bool verbose_chunk_logs() {
static const bool enabled = env_flag_enabled("LOGNEXUS_VERBOSE_CHUNKS");
return enabled;
}
uintmax_t env_uintmax(const char *name, uintmax_t fallback) {
const char *raw = std::getenv(name);
if (!raw || raw[0] == '\0')
return fallback;
char *end = nullptr;
unsigned long long parsed = std::strtoull(raw, &end, 10);
if (end == raw)
return fallback;
return static_cast<uintmax_t>(parsed);
}
const SmallFilePackConfig &small_file_pack_config() {
static SmallFilePackConfig config = [] {
SmallFilePackConfig cfg;
if (const char *raw = std::getenv("LOGNEXUS_SMALL_FILE_PACK")) {
std::string mode = lower_ascii(raw);
if (mode == "0" || mode == "false" || mode == "off" ||
mode == "none") {
cfg.enabled = false;
} else if (mode == "adaptive") {
cfg.adaptive = true;
}
}
cfg.threshold_bytes = env_uintmax("LOGNEXUS_SMALL_FILE_PACK_THRESHOLD",
cfg.threshold_bytes);
cfg.adaptive_min_files = static_cast<size_t>(env_uintmax(
"LOGNEXUS_SMALL_FILE_PACK_MIN_FILES", cfg.adaptive_min_files));
cfg.adaptive_min_saved_bytes = env_uintmax(
"LOGNEXUS_SMALL_FILE_PACK_MIN_SAVED", cfg.adaptive_min_saved_bytes);
return cfg;
}();