Debian Codegraph @

core/nerdlog_agent_test.go

raw
1 package core
2
3 import (
4 "bufio"
5 "bytes"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "runtime"
11 "sort"
12 "strings"
13 "testing"
14 "time"
15
16 "github.com/dimonomid/nerdlog/core/testutils"
17 "github.com/dimonomid/nerdlog/util/sysloggen"
18 "github.com/juju/errors"
19 "github.com/stretchr/testify/assert"
20 "gopkg.in/yaml.v2"
21 )
22
23 const agentTestOutputRoot = "/tmp/nerdlog_agent_test_output"
24 const agentTestCaseYamlFname = "test_case.yaml"
25
26 type AgentTestCaseYaml struct {
27 // If Disabled is true, the test case is skipped.
28 Disabled bool `yaml:"disabled"`
29
30 Descr string `yaml:"descr"`
31 Logfiles testutils.TestCaseLogfiles `yaml:"logfiles"`
32
33 // CurYear and CurMonth specify today's date. If not specified, 1970-01 will
34 // be used. This matters for inferring the log's year (because traditional
35 // syslog timestamp format doesn't include year).
36 CurYear int `yaml:"cur_year"`
37 CurMonth int `yaml:"cur_month"`
38
39 // Env can contain extra environment variables to set, in the format
40 // VARIABLE=VALUE. It'll be passed to cmd.Env directly.
41 Env []string `yaml:"env"`
42
43 Args []string `yaml:"args"`
44 }
45
46 func TestNerdlogAgent(t *testing.T) {
47 _, filename, _, ok := runtime.Caller(0)
48 if !ok {
49 t.Fatal("unable to get caller info")
50 }
51
52 // Get directory of the current file
53 parentDir := filepath.Dir(filename)
54 testCasesDir := filepath.Join(parentDir, "core_testdata", "test_cases_agent")
55 nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
56
57 repoRoot := filepath.Dir(filepath.Dir(filename))
58
59 if err := os.MkdirAll(agentTestOutputRoot, 0755); err != nil {
60 t.Fatalf("unable to create agent test output root dir %s: %s", agentTestOutputRoot, err.Error())
61 }
62
63 testCaseDirs, err := testutils.GetTestCaseDirs(testCasesDir, agentTestCaseYamlFname)
64 if err != nil {
65 panic(err)
66 }
67
68 for _, testCaseDir := range testCaseDirs {
69 t.Run(testCaseDir, func(t *testing.T) {
70 if err := runAgentTestCase(t, nerdlogAgentShFname, testCasesDir, repoRoot, testCaseDir); err != nil {
71 t.Fatalf("running agent test case %s: %s", testCaseDir, err.Error())
72 }
73 })
74 }
75 }
76
77 func runAgentTestCase(t *testing.T, nerdlogAgentShFname, testCasesDir, repoRoot, testName string) error {
78 testCaseDir := filepath.Join(testCasesDir, testName)
79 testCaseDescrFname := filepath.Join(testCaseDir, agentTestCaseYamlFname)
80
81 testOutputDir := filepath.Join(agentTestOutputRoot, testName)
82 if err := os.MkdirAll(testOutputDir, 0755); err != nil {
83 return errors.Annotatef(err, "unable to create test output dir %s", testOutputDir)
84 }
85
86 data, err := os.ReadFile(testCaseDescrFname)
87 if err != nil {
88 return errors.Annotatef(err, "reading yaml test case descriptor %s", testCaseDescrFname)
89 }
90
91 var tc AgentTestCaseYaml
92 if err := yaml.Unmarshal(data, &tc); err != nil {
93 return errors.Annotatef(err, "unmarshaling yaml from %s", testCaseDescrFname)
94 }
95
96 if tc.Disabled {
97 fmt.Printf("WARNING: Skipping %s since it's disabled\n", testName)
98 return nil
99 }
100
101 resolved, err := testutils.ResolveLogfiles(testCaseDir, &tc.Logfiles)
102 if err != nil {
103 return errors.Annotatef(err, "resolving logfiles")
104 }
105
106 provisioned, err := testutils.ProvisionLogFiles(resolved, testOutputDir, repoRoot)
107 if err != nil {
108 return errors.Annotatef(err, "provisioning logfiles")
109 }
110
111 indexFname := filepath.Join(testOutputDir, "nerdlog_agent_index")
112
113 os.Remove(indexFname)
114
115 cmdArgs := []string{
116 nerdlogAgentShFname,
117 "query",
118 "--logfile-last", provisioned.LogfileLast,
119 "--logfile-prev", provisioned.LogfilePrev,
120 "--index-file", indexFname,
121 }
122
123 if provisioned.LogfileLast == "journalctl" {
124 // Specify time format (normally LStreamClient autodetects the time format
125 // and provides these).
126 cmdArgs = append(
127 cmdArgs,
128 "--awktime-month", "substr($0, 6, 2)",
129 "--awktime-year", "substr($0, 1, 4)",
130 "--awktime-day", "substr($0, 9, 2)",
131 "--awktime-hhmm", "substr($0, 12, 5)",
132 "--awktime-minute-key", "substr($0, 6, 11)",
133 )
134 }
135
136 cmdArgs = append(cmdArgs, tc.Args...)
137
138 // Do the full run, with the provided initial index (which in most cases
139 // means, without any index)
140 if err := runNerdlogAgent(t, &tc, cmdArgs, testCaseDir, provisioned.ExtraEnv, testName, testNerdlogAgentParams{
141 checkStderr: true,
142 }); err != nil {
143 return errors.Trace(err)
144 }
145
146 // For journalctl tests, there is no index, and therefore nothing else to do.
147 if provisioned.LogfileLast == "journalctl" {
148 return nil
149 }
150
151 // For log files tests, we rerun the test multiple times after removing some
152 // latest lines from the index, expecting it to index up and to produce the same
153 // result.
154
155 // If asked to skip these repetitions with indexing up, we're done.
156 //
157 // There are at least two valid reasons to skip:
158 //
159 // - When we're running "make update-test-expectations", because for that we
160 // need to capture stderr after the main test (without repetitions), since
161 // stderr will be different otherwise
162 // - To run tests much faster (these repetitions are the slowest part of tests)
163 if os.Getenv("NERDLOG_AGENT_TEST_SKIP_INDEX_UP") != "" {
164 return nil
165 }
166
167 // indexReduceStep specifies how many lines we remove from the index at every
168 // step here. For most tests, it's 25.
169 indexReduceStep := 25
170
171 // For the tests of handling decreased timestamps, reduce the index by a single
172 // line, to make sure that some corner case doesn't slip through.
173 if strings.Contains(testName, "decreased") {
174 indexReduceStep = 1
175 }
176
177 // Backup the resulting fully-built index
178 indexFullFname := filepath.Join(testOutputDir, "nerdlog_agent_index_full")
179 if err := testutils.CopyFile(indexFname, indexFullFname); err != nil {
180 return errors.Annotatef(err, "backing up index as full index: from %s to %s", indexFname, indexFullFname)
181 }
182
183 // Now, keep running the same query with smaller index: on every iteration,
184 // we'll remove one more line from the index end, and expect the same stdout
185 // (not stderr though, this one will be different).
186
187 numLines, err := getNumLines(indexFullFname)
188 if err != nil {
189 return errors.Annotatef(err, "getting numer of lines in %s", indexFullFname)
190 }
191
192 // We can only remove the "idx" lines from the index.
193 minLineno, err := getLastNonMatchingLine(indexFullFname, "idx")
194 if err != nil {
195 return errors.Annotatef(err, "getLastNonMatchingLine")
196 }
197
198 // minLineno points to the line containing the last non-"idx" entry, but
199 // we actually need at least one "idx" entry in the index file for it to work,
200 // so we increment it.
201 minLineno += 1
202
203 for keepLines := numLines - 1; ; keepLines -= indexReduceStep {
204 // If we step too much below the min, use the min (and we'll break below).
205 if keepLines < minLineno {
206 keepLines = minLineno
207 }
208
209 _, err := copyUpToNumLines(indexFullFname, indexFname, keepLines)
210 if err != nil {
211 return errors.Annotatef(
212 err, "copying up to %d lines from %s to %s",
213 keepLines, indexFullFname, indexFname,
214 )
215 }
216
217 t.Run(fmt.Sprintf("keep_%d_lines", keepLines), func(t *testing.T) {
218 if err := runNerdlogAgent(t, &tc, cmdArgs, testCaseDir, provisioned.ExtraEnv, testName, testNerdlogAgentParams{
219 // When changing the index, stderr would change too.
220 checkStderr: false,
221 }); err != nil {
222 t.Fatalf("error: %s", err.Error())
223 }
224 })
225
226 if keepLines <= minLineno {
227 break
228 }
229 }
230
231 // TODO: the stats lines in stdout (these starting from "s:") are printed in
232 // arbitrary order because they come from a hashmap, so simply comparing the
233 // output is a bad idea. Gotta do some post-processing, like sorting these "s:"
234 // lines, before comparing them.
235
236 return nil
237 }
238
239 type testNerdlogAgentParams struct {
240 checkStderr bool
241 }
242
243 func runNerdlogAgent(
244 t *testing.T, tc *AgentTestCaseYaml, bashArgs []string, testCaseDir string,
245 extraEnv []string,
246 testName string,
247 params testNerdlogAgentParams,
248 ) error {
249 assertArgs := []interface{}{"test case %s", testName}
250
251 testOutputDir := filepath.Join(agentTestOutputRoot, testName)
252
253 stdoutFname := filepath.Join(testOutputDir, "nerdlog_agent_stdout")
254 stderrFname := filepath.Join(testOutputDir, "nerdlog_agent_stderr")
255 os.Remove(stdoutFname)
256 os.Remove(stderrFname)
257
258 stdoutFile, err := os.Create(stdoutFname)
259 defer stdoutFile.Close()
260
261 stderrFile, err := os.Create(stderrFname)
262 defer stderrFile.Close()
263
264 cmd := exec.Command("/usr/bin/env", append([]string{"bash"}, bashArgs...)...)
265
266 curYear := tc.CurYear
267 if curYear == 0 {
268 curYear = 1970
269 }
270
271 curMonth := tc.CurMonth
272 if curMonth == 0 {
273 curMonth = 1
274 }
275
276 agentEnv := []string{
277 "TZ=UTC",
278 fmt.Sprintf("CUR_YEAR=%d", curYear),
279 fmt.Sprintf("CUR_MONTH=%d", curMonth),
280 }
281
282 agentEnv = append(agentEnv, tc.Env...)
283 agentEnv = append(agentEnv, extraEnv...)
284
285 cmd.Env = append(
286 os.Environ(),
287 agentEnv...,
288 )
289 cmd.Stdout = stdoutFile
290 cmd.Stderr = stderrFile
291
292 fmt.Printf("Running %+v\n", bashArgs)
293 if err := cmd.Run(); err != nil {
294 return errors.Annotatef(err, "running nerdlog query command %+v", bashArgs)
295 }
296
297 wantStdout, err := os.ReadFile(filepath.Join(testCaseDir, "want_stdout"))
298 if err != nil {
299 return errors.Annotatef(err, "reading want_stdout")
300 }
301
302 wantStderr, err := os.ReadFile(filepath.Join(testCaseDir, "want_stderr"))
303 if err != nil {
304 return errors.Annotatef(err, "reading want_stderr")
305 }
306
307 if err := sortStatBucketLinesInFile(stdoutFname); err != nil {
308 return errors.Annotatef(err, "transforming stdout %s using sortStatBucketLinesInFile", stdoutFname)
309 }
310
311 gotStdout, err := os.ReadFile(stdoutFname)
312 if err != nil {
313 return errors.Annotatef(err, "reading %s", stdoutFname)
314 }
315
316 gotStderr, err := os.ReadFile(stderrFname)
317 if err != nil {
318 return errors.Annotatef(err, "reading %s", stderrFname)
319 }
320
321 assert.Equal(t, string(wantStdout), string(gotStdout), assertArgs...)
322
323 if params.checkStderr {
324 assert.Equal(t, string(wantStderr), string(gotStderr), assertArgs...)
325 }
326
327 return nil
328 }
329
330 // sortStatBucketLines takes a string representing stdout output from the
331 // nerdlog agent script, like this:
332 //
333 // logfile:/tmp/nerdlog_agent_test_output/all_existing_logs/01_from_is_set_to_is_set/logfile.1:0
334 // logfile:/tmp/nerdlog_agent_test_output/all_existing_logs/01_from_is_set_to_is_set/logfile:19
335 // s:Mar 10 10:20,2
336 // s:Mar 10 09:39,1
337 // s:Mar 10 09:00,1
338 // s:Mar 10 09:59,1
339 // s:Mar 10 10:32,2
340 // m:34:Mar 10 10:51:01 myhost user[3758]: <crit> System running low on resources
341 // m:35:Mar 10 10:57:37 myhost news[5185]: <alert> Insufficient privileges
342 // exit_code:0
343 //
344 // And returns the same string, but all the lines starting from "s:" being sorted
345 // lexicographically. This is just for better testability.
346 func sortStatBucketLines(nerdlogStdout []byte) []byte {
347 scanner := bufio.NewScanner(bytes.NewReader(nerdlogStdout))
348 var out bytes.Buffer
349 var statLines []string
350
351 flushStatLines := func() {
352 if len(statLines) > 0 {
353 sort.Strings(statLines)
354 for _, line := range statLines {
355 out.WriteString(line)
356 out.WriteByte('\n')
357 }
358 statLines = nil
359 }
360 }
361
362 for scanner.Scan() {
363 line := scanner.Text()
364 if len(line) > 2 && line[:2] == "s:" {
365 statLines = append(statLines, line)
366 } else {
367 flushStatLines()
368 out.WriteString(line)
369 out.WriteByte('\n')
370 }
371 }
372
373 flushStatLines() // in case the input ends with s: lines
374
375 return out.Bytes()
376 }
377
378 // sortStatBucketLinesInFile reads all file contents using the given filename,
379 // transforms it using sortStatBucketLines, and writes back to the same file.
380 func sortStatBucketLinesInFile(fname string) error {
381 data, err := os.ReadFile(fname)
382 if err != nil {
383 return errors.Annotatef(err, "reading in sortStatBucketLinesInFile")
384 }
385
386 sorted := sortStatBucketLines(data)
387
388 err = os.WriteFile(fname, sorted, 0644)
389 if err != nil {
390 return errors.Annotatef(err, "writing in sortStatBucketLinesInFile")
391 }
392
393 return nil
394 }
395
396 func runNerdlogAgentForBenchmark(
397 bashArgs []string,
398 ) error {
399 cmd := exec.Command("/usr/bin/env", append([]string{"bash"}, bashArgs...)...)
400
401 cmd.Env = append(os.Environ(), "TZ=UTC")
402
403 if err := cmd.Run(); err != nil {
404 return errors.Annotatef(err, "running nerdlog query command %+v", bashArgs)
405 }
406
407 return nil
408 }
409
410 // getNumLines returns the number of lines in the given file.
411 func getNumLines(fname string) (int, error) {
412 file, err := os.Open(fname)
413 if err != nil {
414 return 0, errors.Annotatef(err, "failed to open file %q", fname)
415 }
416 defer file.Close()
417
418 scanner := bufio.NewScanner(file)
419 lineCount := 0
420 for scanner.Scan() {
421 lineCount++
422 }
423
424 if err := scanner.Err(); err != nil {
425 return 0, errors.Annotate(err, "error while scanning file")
426 }
427
428 return lineCount, nil
429 }
430
431 // getLastNonMatchingLine returns the number of the last line which does not start
432 // with the given string. Line numbers are 1-based.
433 func getLastNonMatchingLine(fname string, prefix string) (int, error) {
434 file, err := os.Open(fname)
435 if err != nil {
436 return 0, errors.Annotatef(err, "failed to open file: %s", fname)
437 }
438 defer file.Close()
439
440 scanner := bufio.NewScanner(file)
441 lineNumber := 0
442 lastNonMatchingLine := 0
443
444 for scanner.Scan() {
445 lineNumber++
446 line := scanner.Text()
447 if !strings.HasPrefix(line, prefix) {
448 lastNonMatchingLine = lineNumber
449 }
450 }
451
452 if err := scanner.Err(); err != nil {
453 return 0, errors.Annotate(err, "error scanning file")
454 }
455
456 return lastNonMatchingLine, nil
457 }
458
459 // copyUpToNumLines copies srcPath as destPath, but only the first maxNumLines.
460 // It returns the last line.
461 func copyUpToNumLines(srcPath, destPath string, maxNumLines int) (string, error) {
462 srcFile, err := os.Open(srcPath)
463 if err != nil {
464 return "", errors.Annotatef(err, "failed to open source file: %s", srcPath)
465 }
466 defer srcFile.Close()
467
468 destFile, err := os.Create(destPath)
469 if err != nil {
470 return "", errors.Annotatef(err, "failed to create destination file: %s", destPath)
471 }
472 defer destFile.Close()
473
474 scanner := bufio.NewScanner(srcFile)
475 writer := bufio.NewWriter(destFile)
476 defer writer.Flush()
477
478 var lastLine string
479 lineCount := 0
480
481 for scanner.Scan() {
482 line := scanner.Text()
483 if lineCount < maxNumLines {
484 _, err := writer.WriteString(line + "\n")
485 if err != nil {
486 return "", errors.Annotate(err, "failed to write line to destination file")
487 }
488 }
489 lastLine = line
490 lineCount++
491 if lineCount >= maxNumLines {
492 break
493 }
494 }
495
496 if err := scanner.Err(); err != nil {
497 return "", errors.Annotate(err, "error while scanning source file")
498 }
499
500 return lastLine, nil
501 }
502
503 func BenchmarkNerdlogAgentSmallLogNoIndex(b *testing.B) {
504 _, filename, _, ok := runtime.Caller(0)
505 if !ok {
506 b.Fatal("unable to get caller info")
507 }
508
509 parentDir := filepath.Dir(filename)
510 logfilesDir := filepath.Join(parentDir, "core_testdata", "input_logfiles", "small_mar")
511 nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
512
513 indexFname := filepath.Join(agentTestOutputRoot, "bench1_index")
514
515 cmdArgs := append(
516 []string{
517 nerdlogAgentShFname,
518 "query",
519 "--logfile-last", filepath.Join(logfilesDir, "syslog"),
520 "--logfile-prev", filepath.Join(logfilesDir, "syslog.1"),
521 "--index-file", indexFname,
522 "--max-num-lines", "100",
523 "--from", "2025-03-12-10:00",
524 },
525 )
526
527 b.ResetTimer()
528
529 for i := 0; i < b.N; i++ {
530 os.Remove(indexFname)
531 if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
532 b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
533 }
534 }
535 }
536
537 func BenchmarkNerdlogAgentSmallLogCompleteIndex(b *testing.B) {
538 _, filename, _, ok := runtime.Caller(0)
539 if !ok {
540 b.Fatal("unable to get caller info")
541 }
542
543 parentDir := filepath.Dir(filename)
544 logfilesDir := filepath.Join(parentDir, "core_testdata", "input_logfiles", "small_mar")
545 nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
546
547 indexFname := filepath.Join(agentTestOutputRoot, "bench1_index")
548
549 cmdArgs := append(
550 []string{
551 nerdlogAgentShFname,
552 "query",
553 "--logfile-last", filepath.Join(logfilesDir, "syslog"),
554 "--logfile-prev", filepath.Join(logfilesDir, "syslog.1"),
555 "--index-file", indexFname,
556 "--max-num-lines", "100",
557 "--from", "2025-03-12-10:00",
558 },
559 )
560
561 // Build the index
562 os.Remove(indexFname)
563 if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
564 b.Fatalf("initial runNerdlogAgentForBenchmark failed: %s", err)
565 }
566
567 b.ResetTimer()
568
569 for i := 0; i < b.N; i++ {
570 if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
571 b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
572 }
573 }
574 }
575
576 func BenchmarkNerdlogAgentLargeLogSmallPortionNoIndex(b *testing.B) {
577 if err := generateLogfilesLarge(); err != nil {
578 b.Fatalf("failed to generate log files: %s", err.Error())
579 }
580
581 _, filename, _, ok := runtime.Caller(0)
582 if !ok {
583 b.Fatal("unable to get caller info")
584 }
585
586 parentDir := filepath.Dir(filename)
587 nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
588
589 indexFname := filepath.Join(agentTestOutputRoot, "bench_large_index")
590
591 cmdArgs := append(
592 []string{
593 nerdlogAgentShFname,
594 "query",
595 "--logfile-last", "/tmp/nerdlog_agent_test_output/randomlog_large",
596 "--logfile-prev", "/tmp/nerdlog_agent_test_output/randomlog_large.1",
597 "--index-file", indexFname,
598 "--max-num-lines", "100",
599 "--from", "2025-03-11-00:00",
600 },
601 )
602
603 b.ResetTimer()
604
605 for i := 0; i < b.N; i++ {
606 os.Remove(indexFname)
607 if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
608 b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
609 }
610 }
611 }
612
613 func BenchmarkNerdlogAgentLargeLogSmallPortionCompleteIndex(b *testing.B) {
614 if err := generateLogfilesLarge(); err != nil {
615 b.Fatalf("failed to generate log files: %s", err.Error())
616 }
617
618 _, filename, _, ok := runtime.Caller(0)
619 if !ok {
620 b.Fatal("unable to get caller info")
621 }
622
623 parentDir := filepath.Dir(filename)
624 nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
625
626 indexFname := filepath.Join(agentTestOutputRoot, "bench_large_index")
627
628 cmdArgs := append(
629 []string{
630 nerdlogAgentShFname,
631 "query",
632 "--logfile-last", "/tmp/nerdlog_agent_test_output/randomlog_large",
633 "--logfile-prev", "/tmp/nerdlog_agent_test_output/randomlog_large.1",
634 "--index-file", indexFname,
635 "--max-num-lines", "100",
636 "--from", "2025-03-11-00:00",
637 },
638 )
639
640 // Build the index
641 os.Remove(indexFname)
642 if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
643 b.Fatalf("initial runNerdlogAgentForBenchmark failed: %s", err)
644 }
645
646 b.ResetTimer()
647
648 for i := 0; i < b.N; i++ {
649 if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
650 b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
651 }
652 }
653 }
654
655 func BenchmarkNerdlogAgentLargeLogTinyPortionCompleteIndex(b *testing.B) {
656 if err := generateLogfilesLarge(); err != nil {
657 b.Fatalf("failed to generate log files: %s", err.Error())
658 }
659
660 _, filename, _, ok := runtime.Caller(0)
661 if !ok {
662 b.Fatal("unable to get caller info")
663 }
664
665 parentDir := filepath.Dir(filename)
666 nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
667
668 indexFname := filepath.Join(agentTestOutputRoot, "bench_large_index")
669
670 cmdArgs := append(
671 []string{
672 nerdlogAgentShFname,
673 "query",
674 "--logfile-last", "/tmp/nerdlog_agent_test_output/randomlog_large",
675 "--logfile-prev", "/tmp/nerdlog_agent_test_output/randomlog_large.1",
676 "--index-file", indexFname,
677 "--max-num-lines", "100",
678 "--from", "2025-03-11-01:30",
679 },
680 )
681
682 // Build the index
683 os.Remove(indexFname)
684 if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
685 b.Fatalf("initial runNerdlogAgentForBenchmark failed: %s", err)
686 }
687
688 b.ResetTimer()
689
690 for i := 0; i < b.N; i++ {
691 if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
692 b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
693 }
694 }
695 }
696
697 func BenchmarkNerdlogAgentHugeLogOneHourCompleteIndex(b *testing.B) {
698 if err := generateLogfilesHuge(); err != nil {
699 b.Fatalf("failed to generate log files: %s", err.Error())
700 }
701
702 _, filename, _, ok := runtime.Caller(0)
703 if !ok {
704 b.Fatal("unable to get caller info")
705 }
706
707 parentDir := filepath.Dir(filename)
708 nerdlogAgentShFname := filepath.Join(parentDir, "nerdlog_agent.sh")
709
710 indexFname := filepath.Join(agentTestOutputRoot, "bench_huge_index")
711
712 cmdArgs := append(
713 []string{
714 nerdlogAgentShFname,
715 "query",
716 "--logfile-last", "/tmp/nerdlog_agent_test_output/randomlog_huge",
717 "--logfile-prev", "/tmp/nerdlog_agent_test_output/randomlog_huge.1",
718 "--index-file", indexFname,
719 "--max-num-lines", "100",
720 "--from", "2025-03-11-12:30",
721 },
722 )
723
724 // Build the index
725 os.Remove(indexFname)
726 if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
727 b.Fatalf("initial runNerdlogAgentForBenchmark failed: %s", err)
728 }
729
730 b.ResetTimer()
731
732 for i := 0; i < b.N; i++ {
733 if err := runNerdlogAgentForBenchmark(cmdArgs); err != nil {
734 b.Fatalf("runNerdlogAgentForBenchmark failed: %s", err)
735 }
736 }
737 }
738
739 func generateLogfilesLarge() error {
740 t, err := time.Parse(time.RFC3339, "2025-03-09T06:00:00Z")
741 if err != nil {
742 return errors.Trace(err)
743 }
744
745 t2, err := time.Parse(time.RFC3339, "2025-03-10T06:00:00Z")
746 if err != nil {
747 return errors.Trace(err)
748 }
749
750 err = sysloggen.GenerateSyslog(sysloggen.Params{
751 StartTime: t,
752 SecondLogTime: t2,
753
754 LogBasename: "/tmp/nerdlog_agent_test_output/randomlog_large",
755
756 NumLogs: 4000000,
757 MinDelayMS: 0,
758 MaxDelayMS: 80,
759
760 RandomSeed: 123,
761
762 SkipIfPrevLogSizeIs: 143841612,
763 SkipIfLastLogSizeIs: 122432250,
764 })
765 if err != nil {
766 return errors.Trace(err)
767 }
768
769 return nil
770 }
771
772 func generateLogfilesHuge() error {
773 t, err := time.Parse(time.RFC3339, "2025-03-09T06:00:00Z")
774 if err != nil {
775 return errors.Trace(err)
776 }
777
778 t2, err := time.Parse(time.RFC3339, "2025-03-09T09:00:00Z")
779 if err != nil {
780 return errors.Trace(err)
781 }
782
783 err = sysloggen.GenerateSyslog(sysloggen.Params{
784 StartTime: t,
785 SecondLogTime: t2,
786
787 LogBasename: "/tmp/nerdlog_agent_test_output/randomlog_huge",
788
789 NumLogs: 40000000,
790 MinDelayMS: 0,
791 MaxDelayMS: 10,
792
793 RandomSeed: 123,
794
795 SkipIfPrevLogSizeIs: 143833610,
796 SkipIfLastLogSizeIs: 2518973348,
797 })
798 if err != nil {
799 return errors.Trace(err)
800 }
801
802 return nil
803 }